text
stringlengths 7
1.01M
|
|---|
package org.proteored.miapeapi.cv.ge;
import org.proteored.miapeapi.cv.ControlVocabularyManager;
import org.proteored.miapeapi.cv.ControlVocabularySet;
public class DeviceModel extends ControlVocabularySet {
/* ; */
private static DeviceModel instance;
public static DeviceModel getInstance(ControlVocabularyManager cvManager) {
if (instance == null)
instance = new DeviceModel(cvManager);
return instance;
}
// "sep:00075" - > device
private DeviceModel(ControlVocabularyManager cvManager) {
super(cvManager);
String[] parentAccessionsTMP = { "sep:00075" };
this.parentAccessions = parentAccessionsTMP;
this.miapeSection = 52;
}
}
|
package sorcer.core.context;
import net.jini.core.transaction.Transaction;
import net.jini.core.transaction.TransactionException;
import sorcer.co.tuple.ExecDependency;
import sorcer.service.*;
import sorcer.service.Strategy.Access;
import sorcer.service.Strategy.Flow;
import sorcer.service.Strategy.Opti;
import sorcer.util.FileURLHandler;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.*;
/**
* Created by Mike Sobolewski
*/
public class ModelStrategy implements MogramStrategy, Serializable {
protected List<ThrowableTrace> exceptions = new ArrayList<ThrowableTrace>();
protected List<String> traceList = new ArrayList<String>();
private boolean isTraceable = false;
private boolean isMonitorable = false;
private boolean isProvisionable = false;
private Contextion target;
private Access accessType;
private Flow flowType;
private Opti optiType;
private List<Signature> signatures = new ArrayList<Signature>();
private Map<String, Service> freeServices;
protected transient FileURLHandler dataService;
// dependency management for this Model
protected List<Evaluation> modelDependers = new ArrayList<Evaluation>();
// dependency management for this Model entries
protected List<Evaluation> dependers = new ArrayList<Evaluation>();
protected boolean modelDependeciesExecuted = false;
protected String currentSelector;
// mapping from paths of this inConnector to input paths of this context
protected Context inConnector;
// mapping from paths of this context to input paths of requestors
protected Context outConnector;
// functional exec model dependencies
protected Map<String, List<ExecDependency>> dependentPaths;
// doamin exec transmodel dependencies
protected Map<String, List<ExecDependency>> dependentDomains;
protected ServiceFidelity selectedFidelity;
// select fidelities for this service context
protected Map<String, ServiceFidelity> selectFidelities;
// evaluated model response args
protected Context outcome;
protected Exec.State execState = Exec.State.NULL;
// reponse paths of the runtime model
protected List<Path> responsePaths = new ArrayList<Path>();
public ModelStrategy(Contextion service) {
target = service;
}
public void setExceptions(List<ThrowableTrace> exceptions) {
this.exceptions = exceptions;
}
public boolean isMonitorable() {
return isMonitorable;
}
@Override
public void setMonitorable(boolean state) {
isMonitorable = state;
}
@Override
public boolean isProvisionable() {
return isProvisionable;
}
@Override
public void setProvisionable(boolean state) {
isProvisionable = state;
}
@Override
public boolean isTracable() {
return isTraceable;
}
@Override
public void setTracable(boolean state) {
isTraceable = state;
}
@Override
public void setOpti(Strategy.Opti optiType) {
this.optiType = optiType;
}
@Override
public Strategy.Opti getOpti() {
return optiType;
}
@Override
public void addException(Throwable t) {
exceptions.add(new ThrowableTrace(t));
}
@Override
public void addException(String message, Throwable t) {
exceptions.add(new ThrowableTrace(message, t));
}
public void setIsMonitorable(boolean isMonitorable) {
this.isMonitorable = isMonitorable;
}
public List<ThrowableTrace> getExceptions() {
return exceptions;
}
public List<String> getTraceList() {
return traceList;
}
public void setTraceList(List<String> traceList) {
this.traceList = traceList;
}
public List<ThrowableTrace> getAllExceptions() {
return getExceptions();
}
public Map<String, List<ExecDependency>> getDependentPaths() {
if (dependentPaths == null) {
dependentPaths = new HashMap<String, List<ExecDependency>>();
}
return dependentPaths;
}
public Map<String, List<ExecDependency>> getDependentDomains() {
if (dependentDomains == null) {
dependentDomains = new HashMap<String, List<ExecDependency>>();
}
return dependentDomains;
}
public void setDependentDomains(Map<String, List<ExecDependency>> dependentDomains) {
this.dependentDomains = dependentDomains;
}
public Context getInConnector(Arg... arg) {
return inConnector;
}
public void setInConnector(Context inConnector) {
this.inConnector = inConnector;
}
public Context getOutConnector(Arg... args) {
return outConnector;
}
public void setOutConnector(Context outConnector) {
this.outConnector = outConnector;
}
public String getCurrentSelector() {
return currentSelector;
}
public void setCurrentSelector(String currentSelector) {
this.currentSelector = currentSelector;
}
public void addMdelDependers(Evaluation... dependers) {
if (this.modelDependers == null)
this.modelDependers = new ArrayList<Evaluation>();
for (Evaluation depender : dependers)
this.modelDependers.add(depender);
}
public List<Evaluation> getModelDependers() {
return modelDependers;
}
public void setModelDependers(List<Evaluation> modelDependers) {
this.modelDependers = modelDependers;
}
public void addDependers(Evaluation... dependers) {
if (this.dependers == null)
this.dependers = new ArrayList<Evaluation>();
for (Evaluation depender : dependers)
this.dependers.add(depender);
}
public List<Evaluation> getDependers() {
return dependers;
}
public void setSelectFidelities(Map<String, ServiceFidelity> selectFidelities) {
this.selectFidelities = selectFidelities;
}
public Context getOutcome() {
return outcome;
}
public void setResult(String path, Object value) throws ContextException {
if (!responsePaths.contains(path))
throw new ContextException("no such response path: " + path);
outcome.putValue(path, value);
}
public List<Path> getResponsePaths() {
return responsePaths;
}
public void setResponsePaths(String... paths) {
List<Path> list = new ArrayList<>();
for (String s : paths) {
list.add(new Path(s));
}
this.responsePaths = list;
}
public void setResponsePaths(Path[] responsePaths) {
this.responsePaths = Arrays.asList(responsePaths);
}
public void setResponsePaths(List responsePaths) {
this.responsePaths = responsePaths;
}
public <T extends Mogram> Mogram exert(Transaction txn, Arg... entries) throws TransactionException, MogramException, RemoteException {
return ((Mogram)target).exert(txn, entries);
}
public <T extends Mogram> Mogram exert(Arg... entries) throws TransactionException, MogramException, RemoteException {
return ((Mogram)target).exert(entries);
}
public boolean isModelDependeciesExecuted() {
return modelDependeciesExecuted;
}
public void setModelDependeciesExecuted(boolean modelDependeciesExecuted) {
this.modelDependeciesExecuted = modelDependeciesExecuted;
}
public Map<String, Service> getFreeServices() {
return freeServices;
}
public List<Signature> getSignatures() {
return signatures;
}
public void setSignatures(List<Signature> signatures) {
this.signatures = signatures;
}
public void setAccessType(Access access) {
accessType = access;
}
public Access getAccessType() {
return accessType;
}
public Flow getFlowType() {
return flowType;
}
public void setFlowType(Flow flowType) {
this.flowType = flowType;
}
public void setOutcome(Context outcome) {
this.outcome = outcome;
}
public Contextion getTarget() {
return target;
}
public void setTarget(Mogram target) {
this.target = target;
}
public ServiceFidelity getFidelity() {
return selectedFidelity;
}
public void setFidelity(ServiceFidelity fidelity) {
selectedFidelity = fidelity;
}
public void appendTrace(String info) {
traceList.add(info);
}
public List<String> getTrace() {
return traceList;
}
public FileURLHandler getDataService() {
return dataService;
}
public void setDataService(FileURLHandler dataService) {
this.dataService = dataService;
}
public Exec.State getExecState() {
return execState;
}
public void setExecState(Exec.State state) {
execState = state;
}
}
|
package ghost.framework.application.core.loader.maven;
import ghost.framework.beans.annotation.injection.Autowired;
import ghost.framework.beans.annotation.stereotype.Component;
import ghost.framework.context.application.IApplication;
import ghost.framework.context.base.ICoreInterface;
import ghost.framework.context.event.maven.IMavenLoaderEventTargetHandle;
import ghost.framework.context.maven.IMavenDepositoryLoader;
import ghost.framework.context.maven.IMavenLoader;
import ghost.framework.context.maven.IMavenModuleLoader;
import ghost.framework.context.module.IModuleClassLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @Author: 郭树灿{guo-w541}
* @link: 手机:13715848993, QQ 27048384
* @Description:应用maven加载类
* @Date: 8:09 2019/12/17
* @param <O> 发起发类型
* @param <T> 事件目标类型
* @param <M> 模块类加载器类型
* @param <E> maven加载事件目标处理类型
*/
@Component
public class MavenLoader
<
O extends ICoreInterface,
T extends Object,
M extends IModuleClassLoader,
E extends IMavenLoaderEventTargetHandle<O, T, M>>
// extends AbstractApplicationMavenLoader<O, T, E>
implements IMavenLoader<O, T, M, E> {
/**
* 初始化应用maven加载类
*
* @param app 应用接口
*/
public MavenLoader(@Autowired IApplication app) {
this.app = app;
}
private IApplication app;
private Log log = LogFactory.getLog(MavenLoader.class);
/**
* 加载maven包
*
* @param event 事件对象
*/
@Override
public void loader(E event) {
this.log.info("loader:" + event.toString());
//maven加载顺序按照下面的顺序
//1、注释maven仓库注释
event.getOwner().getBean(IMavenDepositoryLoader.class).loader(event);
//2、注释maven应用依赖包
// event.getOwner().getBean(IMavenApplicationDependencyLoader.class).loader(event);
//3、注释maven模块依赖包
event.getOwner().getBean(IMavenModuleLoader.class).loader(event);
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.expression.spel.standard;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.asm.ClassWriter;
import org.springframework.asm.MethodVisitor;
import org.springframework.asm.Opcodes;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.CompiledExpression;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.ast.SpelNodeImpl;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A SpelCompiler will take a regular parsed expression and create (and load) a class
* containing byte code that does the same thing as that expression. The compiled form of
* an expression will evaluate far faster than the interpreted form.
*
* <p>The SpelCompiler is not currently handling all expression types but covers many of
* the common cases. The framework is extensible to cover more cases in the future. For
* absolute maximum speed there is *no checking* in the compiled code. The compiled
* version of the expression uses information learned during interpreted runs of the
* expression when it generates the byte code. For example if it knows that a particular
* property dereference always seems to return a Map then it will generate byte code that
* expects the result of the property dereference to be a Map. This ensures maximal
* performance but should the dereference result in something other than a map, the
* compiled expression will fail - like a ClassCastException would occur if passing data
* of an unexpected type in a regular Java program.
*
* <p>Due to the lack of checking there are likely some expressions that should never be
* compiled, for example if an expression is continuously dealing with different types of
* data. Due to these cases the compiler is something that must be selectively turned on
* for an associated SpelExpressionParser (through the {@link SpelParserConfiguration}
* object), it is not on by default.
*
* <p>Individual expressions can be compiled by calling {@code SpelCompiler.compile(expression)}.
*
* @author Andy Clement
* @since 4.1
*/
public final class SpelCompiler implements Opcodes {
private static final Log logger = LogFactory.getLog(SpelCompiler.class);
private static final int CLASSES_DEFINED_LIMIT = 100;
// A compiler is created for each classloader, it manages a child class loader of that
// classloader and the child is used to load the compiled expressions.
private static final Map<ClassLoader, SpelCompiler> compilers = new ConcurrentReferenceHashMap<>();
// Counter suffix for generated classes within this SpelCompiler instance
private final AtomicInteger suffixId = new AtomicInteger(1);
// The child ClassLoader used to load the compiled expression classes
private ChildClassLoader ccl;
private SpelCompiler(@Nullable ClassLoader classloader) {
this.ccl = new ChildClassLoader(classloader);
}
/**
* Factory method for compiler instances. The returned SpelCompiler will
* attach a class loader as the child of the given class loader and this
* child will be used to load compiled expressions.
*
* @param classLoader the ClassLoader to use as the basis for compilation
* @return a corresponding SpelCompiler instance
*/
public static SpelCompiler getCompiler(@Nullable ClassLoader classLoader) {
ClassLoader clToUse = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
synchronized (compilers) {
SpelCompiler compiler = compilers.get(clToUse);
if (compiler == null) {
compiler = new SpelCompiler(clToUse);
compilers.put(clToUse, compiler);
}
return compiler;
}
}
/**
* Request that an attempt is made to compile the specified expression. It may fail if
* components of the expression are not suitable for compilation or the data types
* involved are not suitable for compilation. Used for testing.
*
* @return true if the expression was successfully compiled
*/
public static boolean compile(Expression expression) {
return (expression instanceof SpelExpression && ((SpelExpression) expression).compileExpression());
}
/**
* Request to revert to the interpreter for expression evaluation.
* Any compiled form is discarded but can be recreated by later recompiling again.
*
* @param expression the expression
*/
public static void revertToInterpreted(Expression expression) {
if (expression instanceof SpelExpression) {
((SpelExpression) expression).revertToInterpreted();
}
}
/**
* Attempt compilation of the supplied expression. A check is made to see
* if it is compilable before compilation proceeds. The check involves
* visiting all the nodes in the expression Ast and ensuring enough state
* is known about them that bytecode can be generated for them.
*
* @param expression the expression to compile
* @return an instance of the class implementing the compiled expression,
* or {@code null} if compilation is not possible
*/
@Nullable
public CompiledExpression compile(SpelNodeImpl expression) {
if (expression.isCompilable()) {
if (logger.isDebugEnabled()) {
logger.debug("SpEL: compiling " + expression.toStringAST());
}
Class<? extends CompiledExpression> clazz = createExpressionClass(expression);
if (clazz != null) {
try {
return ReflectionUtils.accessibleConstructor(clazz).newInstance();
} catch (Throwable ex) {
throw new IllegalStateException("Failed to instantiate CompiledExpression", ex);
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("SpEL: unable to compile " + expression.toStringAST());
}
return null;
}
private int getNextSuffix() {
return this.suffixId.incrementAndGet();
}
/**
* Generate the class that encapsulates the compiled expression and define it.
* The generated class will be a subtype of CompiledExpression.
*
* @param expressionToCompile the expression to be compiled
* @return the expression call, or {@code null} if the decision was to opt out of
* compilation during code generation
*/
@Nullable
private Class<? extends CompiledExpression> createExpressionClass(SpelNodeImpl expressionToCompile) {
// Create class outline 'spel/ExNNN extends org.springframework.expression.spel.CompiledExpression'
String className = "spel/Ex" + getNextSuffix();
ClassWriter cw = new ExpressionClassWriter();
cw.visit(V1_5, ACC_PUBLIC, className, null, "org/springframework/expression/spel/CompiledExpression", null);
// Create default constructor
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "org/springframework/expression/spel/CompiledExpression",
"<init>", "()V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
// Create getValue() method
mv = cw.visitMethod(ACC_PUBLIC, "getValue",
"(Ljava/lang/Object;Lorg/springframework/expression/EvaluationContext;)Ljava/lang/Object;", null,
new String[]{"org/springframework/expression/EvaluationException"});
mv.visitCode();
CodeFlow cf = new CodeFlow(className, cw);
// Ask the expression AST to generate the body of the method
try {
expressionToCompile.generateCode(mv, cf);
} catch (IllegalStateException ex) {
if (logger.isDebugEnabled()) {
logger.debug(expressionToCompile.getClass().getSimpleName() +
".generateCode opted out of compilation: " + ex.getMessage());
}
return null;
}
CodeFlow.insertBoxIfNecessary(mv, cf.lastDescriptor());
if ("V".equals(cf.lastDescriptor())) {
mv.visitInsn(ACONST_NULL);
}
mv.visitInsn(ARETURN);
mv.visitMaxs(0, 0); // not supplied due to COMPUTE_MAXS
mv.visitEnd();
cw.visitEnd();
cf.finish();
byte[] data = cw.toByteArray();
// TODO need to make this conditionally occur based on a debug flag
// dump(expressionToCompile.toStringAST(), clazzName, data);
return loadClass(StringUtils.replace(className, "/", "."), data);
}
/**
* Load a compiled expression class. Makes sure the classloaders aren't used too much
* because they anchor compiled classes in memory and prevent GC. If you have expressions
* continually recompiling over time then by replacing the classloader periodically
* at least some of the older variants can be garbage collected.
*
* @param name name of the class
* @param bytes bytecode for the class
* @return the Class object for the compiled expression
*/
@SuppressWarnings("unchecked")
private Class<? extends CompiledExpression> loadClass(String name, byte[] bytes) {
if (this.ccl.getClassesDefinedCount() > CLASSES_DEFINED_LIMIT) {
this.ccl = new ChildClassLoader(this.ccl.getParent());
}
return (Class<? extends CompiledExpression>) this.ccl.defineClass(name, bytes);
}
/**
* A ChildClassLoader will load the generated compiled expression classes.
*/
private static class ChildClassLoader extends URLClassLoader {
private static final URL[] NO_URLS = new URL[0];
private int classesDefinedCount = 0;
public ChildClassLoader(@Nullable ClassLoader classLoader) {
super(NO_URLS, classLoader);
}
int getClassesDefinedCount() {
return this.classesDefinedCount;
}
public Class<?> defineClass(String name, byte[] bytes) {
Class<?> clazz = super.defineClass(name, bytes, 0, bytes.length);
this.classesDefinedCount++;
return clazz;
}
}
private class ExpressionClassWriter extends ClassWriter {
public ExpressionClassWriter() {
super(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
}
@Override
protected ClassLoader getClassLoader() {
return ccl;
}
}
}
|
/*
* Copyright 2014-2019 Logo Business Solutions
* (a.k.a. LOGO YAZILIM SAN. VE TIC. A.S)
*
* 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.lbs.tedam.bsh.utils;
import com.lbs.tedam.model.DTO.LookupParameter;
import com.lbs.tedam.test.BaseServiceTest;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameter;
import java.util.List;
import static org.junit.Assert.assertNotEquals;
/**
* @author Tarik.Mikyas<br>
*/
public class ScriptServiceRegexTest extends BaseServiceTest {
/**
* ScriptService scriptService
*/
@Parameter
private static ScriptService scriptService;
/**
* @author Tarik.Mikyas <br>
* this method create scriptService before class created
*/
@BeforeClass
public static void testGetScriptService() {
scriptService = new ScriptService();
}
/**
* @author Tarik.Mikyas <br>
* this method testGetLookupParamProp
*/
@Test
public void testGetLookupParamProp() {
StringBuilder sb = new StringBuilder();
sb.append("<gs>[(105,04*)]</gs><gs>100!ps![(101,04*)]</gs>");// GridSearch
sb.append("<ff>5870</ff>");// FilterFill
sb.append("<fof>5869</fof>");// FormFill
sb.append("<gcs>110!ps![0]!ps!111</gcs>");// GridCellSelect
sb.append("<grs>110!ps![1]</grs>");// gridRowSelect
sb.append("<dc>100!ps!0</dc>");// doubleClick
sb.append("<rcv>100!ps!2!ps!1</rcv>");// rowCountVerify
sb.append("<fvv>2397</fvv>");// fieldValueVerify
sb.append("<mv>messageVerify</mv>");// messageVerify
sb.append("<bc>161</bc>");// buttonClick
sb.append("<bc>1000!ps!1002</bc>");// buttonClick
sb.append("<pu>Tutar</pu>");// popUp
sb.append("<pu>1501!ps!Hesap</pu>");// popUp
List<LookupParameter> lookupParameterList = scriptService.getLookupParamProp(sb.toString());
for (LookupParameter lookupParameter : lookupParameterList) {
System.out.println("lookupParameter :" + lookupParameter.getLookupMethod() + " map : " + lookupParameter.getParameters());
}
assertNotEquals(lookupParameterList.size(), 0);
}
}
|
package org.ethereum.beacon.ssz.type;
import java.util.List;
import java.util.stream.Collectors;
import org.ethereum.beacon.ssz.SSZSchemeException;
import org.ethereum.beacon.ssz.access.SSZField;
import org.ethereum.beacon.ssz.access.SSZUnionAccessor;
import tech.pegasys.artemis.util.collections.Union;
public class SSZUnionType implements SSZHeteroCompositeType {
private final SSZUnionAccessor accessor;
private final SSZField descriptor;
private final TypeResolver typeResolver;
private List<SSZType> childTypes;
public SSZUnionType(SSZUnionAccessor accessor, SSZField descriptor,
TypeResolver typeResolver) {
this.accessor = accessor;
this.descriptor = descriptor;
this.typeResolver = typeResolver;
}
@Override
public Type getType() {
return Type.UNION;
}
@Override
public int getSize() {
return VARIABLE_SIZE;
}
@Override
public SSZUnionAccessor getAccessor() {
return accessor;
}
@Override
public SSZField getTypeDescriptor() {
return descriptor;
}
@Override
public List<SSZType> getChildTypes() {
if (childTypes == null) {
List<SSZField> sszFields = accessor.getInstanceAccessor(getTypeDescriptor())
.getChildDescriptors();
if (sszFields.isEmpty()) {
throw new SSZSchemeException("No Union members found: " + this.getTypeDescriptor());
}
for (int i = 1; i < sszFields.size(); i++) {
if (sszFields.get(i).getRawClass() == Union.Null.class) {
throw new SSZSchemeException("Union Null should be the only Null member at index 0");
}
}
childTypes = sszFields.stream()
.map(typeResolver::resolveSSZType)
.collect(Collectors.toList());
}
return childTypes;
}
public boolean isNullable() {
return getChildTypes().get(0).getTypeDescriptor().getRawClass() == Union.Null.class;
}
}
|
package tarea6_alessandroreyes_11911224;
public class Maestro extends Persona{
private int Codigo;
private String Facultad;
public Maestro() {
super();
}
public Maestro(int codigo, String facultad) {
this.Codigo = codigo;
this.Facultad = facultad;
}
public Maestro(int Codigo, String Facultad, int id, String nombre) {
super(id, nombre);
this.Codigo = Codigo;
this.Facultad = Facultad;
}
public int getCodigo() {
return Codigo;
}
public void setCodigo(int Codigo) {
this.Codigo = Codigo;
}
public String getFacultad() {
return Facultad;
}
public void setFacultad(String Facultad) {
this.Facultad = Facultad;
}
@Override
public String toString() {
return super.toString()+"Maestro{" + "Codigo=" + Codigo + ", Facultad=" + Facultad + '}';
}
}
|
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.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.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2008 Ola Bini <ola.bini@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.openssl.impl;
import java.security.cert.X509CRL;
import java.util.Collection;
import org.bouncycastle.asn1.ASN1Encodable;
import org.jruby.ext.openssl.x509store.X509AuxCertificate;
/**
*
* @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a>
*/
public class PKCS7DataSigned extends PKCS7Data {
/* NID_pkcs7_signed */
private Signed sign;
public PKCS7DataSigned() {
this.sign = new Signed();
this.sign.setVersion(1);
}
public PKCS7DataSigned(Signed sign) {
this.sign = sign;
}
public int getType() {
return ASN1Registry.NID_pkcs7_signed;
}
@Override
public Object ctrl(int cmd, Object v, Object ignored) {
int ret = 0;
switch(cmd) {
case PKCS7.OP_SET_DETACHED_SIGNATURE:
ret = ((Integer)v).intValue();
if(ret != 0 && sign.contents.isData()) {
sign.contents.setData(null);
}
break;
case PKCS7.OP_GET_DETACHED_SIGNATURE:
if(sign == null || sign.contents.getData() == null) {
ret = 1;
} else {
ret = 0;
}
break;
default:
throw new RuntimeException("TODO: implement error handling");
}
return Integer.valueOf(ret);
}
@Override
public void setSign(Signed sign) {
this.sign = sign;
}
@Override
public Signed getSign() {
return this.sign;
}
@Override
public boolean isSigned() {
return true;
}
@Override
public void addSigner(SignerInfoWithPkey psi) {
this.sign.getMdAlgs().add(psi.getDigestAlgorithm());
this.sign.getSignerInfo().add(psi);
}
@Override
public void setContent(PKCS7 p7) {
this.sign.setContents(p7);
}
@Override
public Collection<SignerInfoWithPkey> getSignerInfo() {
return this.sign.getSignerInfo();
}
@Override
public void addCertificate(X509AuxCertificate cert) {
this.sign.getCert().add(cert);
}
@Override
public void addCRL(X509CRL crl) {
this.sign.getCrl().add(crl);
}
@Override
public String toString() {
return this.sign.toString();
}
public static PKCS7DataSigned fromASN1(ASN1Encodable content) throws PKCS7Exception {
return new PKCS7DataSigned(Signed.fromASN1(content));
}
@Override
public ASN1Encodable asASN1() {
return sign.asASN1();
}
}// PKCS7DataSigned
|
/*
* Copyright 2018-present yangguo@outlook.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 info.yangguo.waf.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import info.yangguo.waf.config.ClusterProperties;
import info.yangguo.waf.config.ContextHolder;
import info.yangguo.waf.model.*;
import info.yangguo.waf.request.security.*;
import info.yangguo.waf.response.ClickjackResponseProcess;
import info.yangguo.waf.response.ResponseProcess;
import info.yangguo.waf.util.JsonUtil;
import org.apache.commons.io.FileUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class ZkClusterService implements ClusterService {
private static Logger LOGGER = LoggerFactory.getLogger(ZkClusterService.class);
private static final String separator = "/";
private static final String securityPath = "/waf/config/security";
private static final String responsePath = "/waf/config/response";
private static final String upstreamPath = "/waf/config/upstream";
private static final String rewritePath = "/waf/config/rewrite";
private static final String redirectPath = "/waf/config/redirect";
private static final String forwardPath = "/waf/config/translate";
private static final String ENC = "UTF-8";
private static CuratorFramework client;
Map<String, SecurityConfig> requestConfigMap = Maps.newHashMap();
Map<String, ResponseConfig> responseConfigMap = Maps.newHashMap();
Map<String, WeightedRoundRobinScheduling> upstreamServerMap = Maps.newHashMap();
Map<String, BasicConfig> rewriteConfigrMap = Maps.newHashMap();
Map<String, BasicConfig> redirectConfigrMap = Maps.newHashMap();
Map<String, ForwardConfig> forwardConfigMap = Maps.newHashMap();
public ZkClusterService() throws Exception {
ClusterProperties.ZkProperty zkProperty = ((ClusterProperties) ContextHolder.applicationContext.getBean("clusterProperties")).getZk();
// these are reasonable arguments for the ExponentialBackoffRetry. The first
// retry will wait 1 second - the second will wait up to 2 seconds - the
// third will wait up to 4 seconds.
ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
// using the CuratorFrameworkFactory.builder() gives fine grained control
// over creation options. See the CuratorFrameworkFactory.Builder javadoc
// details
client = CuratorFrameworkFactory.builder()
.connectString(zkProperty.getConnectionString())
.retryPolicy(retryPolicy)
.build();
client.getUnhandledErrorListenable().addListener((message, e) -> {
LOGGER.error("zookeeper error:{}", message);
e.printStackTrace();
});
client.getConnectionStateListenable().addListener((c, newState) -> {
LOGGER.info("zookeeper state:{}", newState);
});
client.start();
syncConfig();
Arrays.stream(new Class[]{
ArgsSecurity.class,
CCSecurity.class,
CookieSecurity.class,
IpSecurity.class,
PostSecurity.class,
FileSecurity.class,
ScannerSecurity.class,
UaSecurity.class,
UrlSecurity.class,
WIpSecurity.class,
WUrlSecurity.class,
ScriptSecurity.class,
ClickjackResponseProcess.class
}).forEach(filterClass -> {
initFilter(filterClass);
});
if (client.checkExists().forPath(securityPath) == null) {
client.create().forPath(securityPath);
}
TreeCache requestTreeCache = TreeCache.newBuilder(client, securityPath).setCacheData(true).build();
requestTreeCache.start();
requestTreeCache.getListenable().addListener((client, event) -> {
if (TreeCacheEvent.Type.NODE_UPDATED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_ADDED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_REMOVED.equals(event.getType())
|| TreeCacheEvent.Type.INITIALIZED.equals(event.getType())) {
requestTreeCache.getCurrentChildren(securityPath).entrySet().stream().forEach(requestEntry -> {
String filterName = requestEntry.getKey();
String filterPath = requestEntry.getValue().getPath();
BasicConfig filterConfig = (BasicConfig) JsonUtil.fromJson(new String(requestEntry.getValue().getData()), BasicConfig.class);
List<SecurityConfigItem> securityConfigItems = Lists.newArrayList();
requestTreeCache.getCurrentChildren(filterPath).entrySet().stream().forEach(itemEntry -> {
String regex = null;
try {
regex = URLDecoder.decode(itemEntry.getKey(), ENC);
} catch (UnsupportedEncodingException e) {
LOGGER.error("Decode regex:[{}] ", itemEntry.getKey());
}
BasicConfig regexConfig = (BasicConfig) JsonUtil.fromJson(new String(itemEntry.getValue().getData()), BasicConfig.class);
securityConfigItems.add(SecurityConfigItem.builder().name(regex).config(regexConfig).build());
});
requestConfigMap.put(filterName, SecurityConfig.builder().filterName(filterName).config(filterConfig).securityConfigItems(securityConfigItems).build());
});
ConfigLocalCache.setRequestConfig(requestConfigMap);
}
});
if (client.checkExists().forPath(responsePath) == null) {
client.create().forPath(responsePath);
}
TreeCache responseTreeCache = TreeCache.newBuilder(client, responsePath).setCacheData(true).build();
responseTreeCache.start();
responseTreeCache.getListenable().addListener((client, event) -> {
if (TreeCacheEvent.Type.NODE_UPDATED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_ADDED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_REMOVED.equals(event.getType())
|| TreeCacheEvent.Type.INITIALIZED.equals(event.getType())) {
responseTreeCache.getCurrentChildren(responsePath).entrySet().stream().forEach(entry -> {
String filterName = entry.getKey();
BasicConfig config = (BasicConfig) JsonUtil.fromJson(new String(entry.getValue().getData()), BasicConfig.class);
responseConfigMap.put(filterName, ResponseConfig.builder().filterName(filterName).config(config).build());
});
ConfigLocalCache.setResponseConfig(responseConfigMap);
}
});
if (client.checkExists().forPath(upstreamPath) == null) {
client.create().forPath(upstreamPath);
}
TreeCache upstreamTreeCache = TreeCache.newBuilder(client, upstreamPath).setCacheData(true).build();
upstreamTreeCache.start();
upstreamTreeCache.getListenable().addListener((client, event) -> {
if (TreeCacheEvent.Type.NODE_UPDATED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_ADDED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_REMOVED.equals(event.getType())
|| TreeCacheEvent.Type.INITIALIZED.equals(event.getType())) {
Set<String> hosts = Sets.newHashSet();
upstreamTreeCache.getCurrentChildren(upstreamPath).entrySet().stream().forEach(hostEntry -> {
String host = hostEntry.getKey();
String hostPath = hostEntry.getValue().getPath();
BasicConfig hostBasicConfig = (BasicConfig) JsonUtil.fromJson(new String(hostEntry.getValue().getData()), BasicConfig.class);
List<ServerConfig> serverConfigs = Lists.newArrayList();
upstreamTreeCache.getCurrentChildren(hostPath).entrySet().stream().forEach(serverEntry -> {
String[] serverInfo = serverEntry.getKey().split(":");
String ip = serverInfo[0];
int port = Integer.parseInt(serverInfo[1]);
ServerBasicConfig serverBasicConfig = (ServerBasicConfig) JsonUtil.fromJson(new String(serverEntry.getValue().getData()), ServerBasicConfig.class);
ServerConfig serverConfig = ServerConfig.builder()
.ip(ip)
.port(port)
.config(serverBasicConfig)
.build();
serverConfigs.add(serverConfig);
});
WeightedRoundRobinScheduling weightedRoundRobinScheduling = new WeightedRoundRobinScheduling(serverConfigs, hostBasicConfig);
upstreamServerMap.put(host, weightedRoundRobinScheduling);
hosts.add(host);
});
//将已经删除的节点从upstreamServerMap中剔除掉
upstreamServerMap.keySet().stream().collect(Collectors.toList()).stream().forEach(key -> {
if (!hosts.contains(key))
upstreamServerMap.remove(key);
});
ConfigLocalCache.setUpstreamConfig(upstreamServerMap);
}
});
if (client.checkExists().forPath(rewritePath) == null) {
client.create().forPath(rewritePath);
}
TreeCache rewriteTreeCache = TreeCache.newBuilder(client, rewritePath).setCacheData(true).build();
rewriteTreeCache.start();
rewriteTreeCache.getListenable().addListener((client, event) -> {
if (TreeCacheEvent.Type.NODE_UPDATED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_ADDED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_REMOVED.equals(event.getType())
|| TreeCacheEvent.Type.INITIALIZED.equals(event.getType())) {
Set<String> wafRoutes = Sets.newHashSet();
rewriteTreeCache.getCurrentChildren(rewritePath).entrySet().stream().forEach(hostEntry -> {
String wafRoute = hostEntry.getKey();
BasicConfig basicConfig = (BasicConfig) JsonUtil.fromJson(new String(hostEntry.getValue().getData()), BasicConfig.class);
rewriteConfigrMap.put(wafRoute, basicConfig);
wafRoutes.add(wafRoute);
});
//将已经删除的节点从rewriteConfigrMap中剔除掉
rewriteConfigrMap.keySet().stream().collect(Collectors.toList()).stream().forEach(key -> {
if (!wafRoutes.contains(key))
rewriteConfigrMap.remove(key);
});
ConfigLocalCache.setRewriteConfig(rewriteConfigrMap);
}
});
if (client.checkExists().forPath(redirectPath) == null) {
client.create().forPath(redirectPath);
}
TreeCache redirectTreeCache = TreeCache.newBuilder(client, redirectPath).setCacheData(true).build();
redirectTreeCache.start();
redirectTreeCache.getListenable().addListener((client, event) -> {
if (TreeCacheEvent.Type.NODE_UPDATED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_ADDED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_REMOVED.equals(event.getType())
|| TreeCacheEvent.Type.INITIALIZED.equals(event.getType())) {
Set<String> wafRoutes = Sets.newHashSet();
redirectTreeCache.getCurrentChildren(redirectPath).entrySet().stream().forEach(hostEntry -> {
String wafRoute = hostEntry.getKey();
BasicConfig basicConfig = (BasicConfig) JsonUtil.fromJson(new String(hostEntry.getValue().getData()), BasicConfig.class);
redirectConfigrMap.put(wafRoute, basicConfig);
wafRoutes.add(wafRoute);
});
//将已经删除的节点从redirectConfigrMap中剔除掉
redirectConfigrMap.keySet().stream().collect(Collectors.toList()).stream().forEach(key -> {
if (!wafRoutes.contains(key))
redirectConfigrMap.remove(key);
});
ConfigLocalCache.setRedirectConfig(redirectConfigrMap);
}
});
if (client.checkExists().forPath(forwardPath) == null) {
client.create().forPath(forwardPath);
}
TreeCache forwardTreeCache = TreeCache.newBuilder(client, forwardPath).setCacheData(true).build();
forwardTreeCache.start();
forwardTreeCache.getListenable().addListener((client, event) -> {
if (TreeCacheEvent.Type.NODE_UPDATED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_ADDED.equals(event.getType())
|| TreeCacheEvent.Type.NODE_REMOVED.equals(event.getType())
|| TreeCacheEvent.Type.INITIALIZED.equals(event.getType())) {
Set<String> wafRoutes = Sets.newHashSet();
forwardTreeCache.getCurrentChildren(forwardPath).entrySet().stream().forEach(forwardEntry -> {
String forwardConfigKey = forwardEntry.getKey();
String forwardConfigPath = forwardEntry.getValue().getPath();
BasicConfig forwardConfig = (BasicConfig) JsonUtil.fromJson(new String(forwardEntry.getValue().getData()), BasicConfig.class);
List<ForwardConfigItem> forwardConfigItems = Lists.newArrayList();
forwardTreeCache.getCurrentChildren(forwardConfigPath).entrySet().stream().forEach(itemEntry -> {
String regex = null;
try {
regex = URLDecoder.decode(itemEntry.getKey(), ENC);
} catch (UnsupportedEncodingException e) {
LOGGER.error("Decode regex:[{}] ", itemEntry.getKey());
}
BasicConfig regexConfig = (BasicConfig) JsonUtil.fromJson(new String(itemEntry.getValue().getData()), BasicConfig.class);
forwardConfigItems.add(ForwardConfigItem.builder().name(regex).config(regexConfig).build());
});
forwardConfigMap.put(forwardConfigKey, ForwardConfig.builder().wafRoute(forwardConfigKey).config(forwardConfig).forwardConfigItems(forwardConfigItems).build());
wafRoutes.add(forwardConfigKey);
});
//将已经删除的节点从redirectConfigrMap中剔除掉
forwardConfigMap.keySet().stream().collect(Collectors.toList()).stream().forEach(key -> {
if (!wafRoutes.contains(key))
forwardConfigMap.remove(key);
});
ConfigLocalCache.setTranslateConfig(forwardConfigMap);
}
});
}
@Override
public Map<String, SecurityConfig> getSecurityConfigs() {
return requestConfigMap;
}
@Override
public void setSecurityConfig(Optional<String> filterName, Optional<BasicConfig> config) {
try {
if (filterName.isPresent() && config.isPresent()) {
String path = securityPath + separator + filterName.get();
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(path) == null) {
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", path, data);
} else {
client.setData().forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been set.", path, data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void setSecurityConfigItem(Optional<String> filterName, Optional<String> item, Optional<BasicConfig> config) {
try {
if (filterName.isPresent() && item.isPresent() && config.isPresent()) {
String filterPath = securityPath + separator + filterName.get();
if (client.checkExists().forPath(filterPath) == null) {
String data = JsonUtil.toJson(BasicConfig.builder().isStart(false).build(), false);
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(filterPath, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", filterPath, data);
}
String rulePath = filterPath + separator + URLEncoder.encode(item.get(), ENC);
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(rulePath) == null) {
client.create().forPath(rulePath, data.getBytes());
LOGGER.info("Path[{}]|Regex[{}]|Data[{}] has been created.", rulePath, item.get(), data);
} else {
client.setData().forPath(rulePath, data.getBytes());
LOGGER.info("Path[{}]|Regex[{}]|Data[{}] has been set.", rulePath, item.get(), data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteSecurityConfigItem(Optional<String> filterName, Optional<String> item) {
try {
if (filterName.isPresent() && item.isPresent()) {
String itemPath = securityPath + separator + filterName.get() + separator + URLEncoder.encode(item.get(), ENC);
if (client.checkExists().forPath(itemPath) != null) {
client.delete().forPath(itemPath);
LOGGER.info("Path[{}]|Regex[{}] has been deleted.", itemPath, item.get());
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Map<String, ResponseConfig> getResponseConfigs() {
return responseConfigMap;
}
@Override
public void setResponseConfig(Optional<String> filterName, Optional<BasicConfig> config) {
try {
if (filterName.isPresent() && config.isPresent()) {
String path = responsePath + separator + filterName.get();
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(path) == null) {
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", path, data);
} else {
client.setData().forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been set.", path, data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Map<String, WeightedRoundRobinScheduling> getUpstreamConfig() {
return upstreamServerMap;
}
@Override
public void setUpstreamConfig(Optional<String> hostOptional, Optional<BasicConfig> config) {
try {
if (hostOptional.isPresent() && config.isPresent()) {
String path = upstreamPath + separator + hostOptional.get();
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(path) != null) {
client.setData().forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been set.", path, data);
} else {
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", path, data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void setUpstreamServerConfig(Optional<String> hostOptional, Optional<String> ipOptional, Optional<Integer> portOptional, Optional<ServerBasicConfig> config) {
try {
if (hostOptional.isPresent() && ipOptional.isPresent() && portOptional.isPresent() && config.isPresent()) {
String hostPath = upstreamPath + separator + hostOptional.get();
if (client.checkExists().forPath(hostPath) == null) {
String data = JsonUtil.toJson(BasicConfig.builder().isStart(false).build(), false);
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(hostPath, data.getBytes());
}
String serverPath = hostPath + separator + ipOptional.get() + ":" + portOptional.get();
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(serverPath) != null) {
client.setData().forPath(serverPath, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been set.", serverPath, data);
} else {
client.create().withMode(CreateMode.PERSISTENT).forPath(serverPath, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", serverPath, data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteUpstream(Optional<String> hostOptional) {
hostOptional.ifPresent(new Consumer<String>() {
@Override
public void accept(String s) {
String hostPath = upstreamPath + separator + hostOptional.get();
try {
if (client.checkExists().forPath(hostPath) != null) {
client.delete().deletingChildrenIfNeeded().forPath(hostPath);
LOGGER.info("Path[{}] has been deleted.", hostPath);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public void deleteUpstreamServer(Optional<String> hostOptional, Optional<String> ipOptional, Optional<Integer> portOptional) {
if (hostOptional.isPresent() && ipOptional.isPresent() && portOptional.isPresent()) {
String serverPath = upstreamPath + separator + hostOptional.get() + separator + ipOptional.get() + ":" + portOptional.get();
try {
if (client.checkExists().forPath(serverPath) != null) {
client.delete().forPath(serverPath);
LOGGER.info("Path[{}] has been deleted.", serverPath);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public Map<String, BasicConfig> getRewriteConfigs() {
return rewriteConfigrMap;
}
@Override
public void setRewriteConfig(Optional<String> wafRoute, Optional<BasicConfig> config) {
try {
if (wafRoute.isPresent() && config.isPresent()) {
String path = rewritePath + separator + wafRoute.get();
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(path) == null) {
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", path, data);
} else {
client.setData().forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been set.", path, data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteRewrite(Optional<String> wafRoute) {
wafRoute.ifPresent(new Consumer<String>() {
@Override
public void accept(String s) {
String wafRoutePath = rewritePath + separator + wafRoute.get();
try {
if (client.checkExists().forPath(wafRoutePath) != null) {
client.delete().deletingChildrenIfNeeded().forPath(wafRoutePath);
LOGGER.info("Path[{}] has been deleted.", wafRoutePath);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public Map<String, BasicConfig> getRedirectConfigs() {
return redirectConfigrMap;
}
@Override
public void setRedirectConfig(Optional<String> wafRoute, Optional<BasicConfig> config) {
try {
if (wafRoute.isPresent() && config.isPresent()) {
String path = redirectPath + separator + wafRoute.get();
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(path) == null) {
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", path, data);
} else {
client.setData().forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been set.", path, data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteRedirect(Optional<String> wafRoute) {
wafRoute.ifPresent(new Consumer<String>() {
@Override
public void accept(String s) {
String wafRoutePath = redirectPath + separator + wafRoute.get();
try {
if (client.checkExists().forPath(wafRoutePath) != null) {
client.delete().deletingChildrenIfNeeded().forPath(wafRoutePath);
LOGGER.info("Path[{}] has been deleted.", wafRoutePath);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public Map<String, ForwardConfig> getTranslateConfigs() {
return forwardConfigMap;
}
@Override
public void setTranslateConfig(Optional<String> wafRoute, Optional<BasicConfig> config) {
try {
if (wafRoute.isPresent() && config.isPresent()) {
String path = forwardPath + separator + wafRoute.get();
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(path) == null) {
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", path, data);
} else {
client.setData().forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been set.", path, data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void setTranslateConfigItem(Optional<String> wafRoute, Optional<String> item, Optional<BasicConfig> config) {
try {
if (wafRoute.isPresent() && item.isPresent() && config.isPresent()) {
String wafRoutePath = forwardPath + separator + wafRoute.get();
if (client.checkExists().forPath(wafRoutePath) == null) {
String data = JsonUtil.toJson(BasicConfig.builder().isStart(false).build(), false);
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(wafRoutePath, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been created.", wafRoutePath, data);
}
String rulePath = wafRoutePath + separator + URLEncoder.encode(item.get(), ENC);
String data = JsonUtil.toJson(config.get(), false);
if (client.checkExists().forPath(rulePath) == null) {
client.create().forPath(rulePath, data.getBytes());
LOGGER.info("Path[{}]|Regex[{}]|Data[{}] has been created.", rulePath, item.get(), data);
} else {
client.setData().forPath(rulePath, data.getBytes());
LOGGER.info("Path[{}]|Regex[{}]|Data[{}] has been set.", rulePath, item.get(), data);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteTranslateConfigItem(Optional<String> wafRoute, Optional<String> item) {
try {
if (wafRoute.isPresent() && item.isPresent()) {
String itemPath = forwardPath + separator + wafRoute.get() + separator + URLEncoder.encode(item.get(), ENC);
if (client.checkExists().forPath(itemPath) != null) {
client.delete().forPath(itemPath);
LOGGER.info("Path[{}]|Regex[{}] has been deleted.", itemPath, item.get());
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteTranslateConfig(Optional<String> wafRoute) {
wafRoute.ifPresent(new Consumer<String>() {
@Override
public void accept(String s) {
String forwardPath = ZkClusterService.forwardPath + separator + wafRoute.get();
try {
if (client.checkExists().forPath(forwardPath) != null) {
client.delete().forPath(forwardPath);
LOGGER.info("Path[{}] has been deleted.", forwardPath);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
private void initFilter(Class filterClass) {
String path;
if (Security.class.isAssignableFrom(filterClass)) {
path = securityPath + separator + filterClass.getName();
} else if (ResponseProcess.class.isAssignableFrom(filterClass)) {
path = responsePath + separator + filterClass.getName();
} else {
throw new RuntimeException("Filter class:[" + filterClass.getName() + "] has error when to initialize filter.");
}
try {
if (client.checkExists().forPath(path) == null) {
String data = JsonUtil.toJson(BasicConfig.builder().isStart(false).build(), false);
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, data.getBytes());
LOGGER.info("Path[{}]|Data[{}] has been initialized", path, data);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void syncConfig() {
try {
if (client.checkExists().forPath(securityPath) == null) {
ConfigLocalCache
.getRequestConfig()
.entrySet()
.stream()
.forEach(entry -> {
String filterName = entry.getKey();
SecurityConfig requestConfig = entry.getValue();
setSecurityConfig(Optional.of(filterName), Optional.of(requestConfig.getConfig()));
requestConfig.getSecurityConfigItems().stream().forEach(itemConfig -> {
setSecurityConfigItem(Optional.of(filterName), Optional.of(itemConfig.getName()), Optional.of(itemConfig.getConfig()));
});
});
}
} catch (Exception e) {
LOGGER.warn("security config sync fail");
}
try {
if (client.checkExists().forPath(responsePath) == null) {
ConfigLocalCache
.getResponseConfig()
.entrySet()
.stream()
.forEach(entry -> {
String filterName = entry.getKey();
ResponseConfig responseConfig = entry.getValue();
setResponseConfig(Optional.of(filterName), Optional.of(responseConfig.getConfig()));
});
}
} catch (Exception e) {
LOGGER.warn("response config sync fail");
}
try {
if (client.checkExists().forPath(upstreamPath) == null) {
ConfigLocalCache
.getUpstreamConfig()
.entrySet()
.stream()
.forEach(entry1 -> {
String wafRoute = entry1.getKey();
WeightedRoundRobinScheduling weightedRoundRobinScheduling = entry1.getValue();
setUpstreamConfig(Optional.of(wafRoute), Optional.of(weightedRoundRobinScheduling.getBasicConfig()));
weightedRoundRobinScheduling
.getServersMap()
.entrySet()
.stream()
.forEach(entry2 -> {
ServerConfig serverConfig = entry2.getValue();
setUpstreamServerConfig(Optional.of(wafRoute), Optional.of(serverConfig.getIp()), Optional.of(serverConfig.getPort()), Optional.of(serverConfig.getConfig()));
});
});
}
} catch (Exception e) {
LOGGER.warn("upstream config sync fail");
}
try {
if (client.checkExists().forPath(rewritePath) == null) {
ConfigLocalCache
.getRewriteConfig()
.entrySet()
.stream()
.forEach(entry -> {
String wafRoute = entry.getKey();
BasicConfig basicConfig = entry.getValue();
setRewriteConfig(Optional.of(wafRoute), Optional.of(basicConfig));
});
}
} catch (Exception e) {
LOGGER.warn("rewrite config sync fail");
}
try {
if (client.checkExists().forPath(redirectPath) == null) {
ConfigLocalCache
.getRedirectConfig()
.entrySet()
.stream()
.forEach(entry -> {
String wafRoute = entry.getKey();
BasicConfig basicConfig = entry.getValue();
setRedirectConfig(Optional.of(wafRoute), Optional.of(basicConfig));
});
}
} catch (Exception e) {
LOGGER.warn("redirect config sync fail");
}
try {
if (client.checkExists().forPath(forwardPath) == null) {
ConfigLocalCache
.getTranslateConfig()
.entrySet()
.stream()
.forEach(entry -> {
String wafRoute = entry.getKey();
ForwardConfig forwardConfig = entry.getValue();
setTranslateConfig(Optional.of(wafRoute), Optional.of(forwardConfig.getConfig()));
forwardConfig.getForwardConfigItems().stream().forEach(itemConfig -> {
setTranslateConfigItem(Optional.of(wafRoute), Optional.of(itemConfig.getName()), Optional.of(itemConfig.getConfig()));
});
});
}
} catch (Exception e) {
LOGGER.warn("security config sync fail");
}
}
/**
* 将配置缓存到本地,如果配置中心宕机,切换到新的配置中心时,会自动将本地缓存配置同步到新的配置中心,从而减少配置负担。
*/
private static class ConfigLocalCache {
private static String cachePath = System.getProperties().getProperty("user.home") + "/.waf";
private static String requestCacheFile = cachePath + "/request-config.json";
private static String responseCacheile = cachePath + "/response-config.json";
private static String upstreamCacheFile = cachePath + "/upstream-config.json";
private static String rewriteCacheFile = cachePath + "/rewrite-config.json";
private static String redirectCacheFile = cachePath + "/redirect-config.json";
private static String forwardCacheFile = cachePath + "/translate-config.json";
public static Map<String, SecurityConfig> getRequestConfig() {
Map<String, SecurityConfig> config = Maps.newHashMap();
File file = new File(requestCacheFile);
if (file.exists()) {
try {
config.putAll(JsonUtil.fromJson(FileUtils.readFileToString(file), new TypeReference<Map<String, SecurityConfig>>() {
}));
} catch (Exception e) {
file.delete();
LOGGER.warn("format of request local config is incorrect", e);
}
}
return config;
}
public static void setRequestConfig(Map<String, SecurityConfig> config) {
try {
FileUtils.write(new File(requestCacheFile), JsonUtil.toJson(config, true));
} catch (IOException e) {
LOGGER.error("request local cache setting is fail", e);
}
}
public static Map<String, ResponseConfig> getResponseConfig() {
Map<String, ResponseConfig> config = Maps.newHashMap();
File file = new File(responseCacheile);
if (file.exists()) {
try {
config.putAll(JsonUtil.fromJson(FileUtils.readFileToString(file), new TypeReference<Map<String, ResponseConfig>>() {
}));
} catch (Exception e) {
file.delete();
LOGGER.warn("format of response local config is incorrect", e);
}
}
return config;
}
public static void setResponseConfig(Map<String, ResponseConfig> config) {
try {
FileUtils.write(new File(responseCacheile), JsonUtil.toJson(config, true));
} catch (IOException e) {
LOGGER.error("response local cache setting is fail", e);
}
}
public static Map<String, WeightedRoundRobinScheduling> getUpstreamConfig() {
Map<String, WeightedRoundRobinScheduling> config = Maps.newHashMap();
File file = new File(upstreamCacheFile);
if (file.exists()) {
try {
config.putAll(JsonUtil.fromJson(FileUtils.readFileToString(file), new TypeReference<Map<String, WeightedRoundRobinScheduling>>() {
}));
} catch (Exception e) {
file.delete();
LOGGER.warn("format of upstream local config is incorrect", e);
}
}
return config;
}
public static void setUpstreamConfig(Map<String, WeightedRoundRobinScheduling> config) {
try {
FileUtils.write(new File(upstreamCacheFile), JsonUtil.toJson(config, true));
} catch (IOException e) {
LOGGER.error("upstream local cache setting is fail", e);
}
}
public static Map<String, BasicConfig> getRewriteConfig() {
Map<String, BasicConfig> config = Maps.newHashMap();
File file = new File(rewriteCacheFile);
if (file.exists()) {
try {
config.putAll(JsonUtil.fromJson(FileUtils.readFileToString(file), new TypeReference<Map<String, BasicConfig>>() {
}));
} catch (Exception e) {
file.delete();
LOGGER.warn("format of rewrite local config is incorrect", e);
}
}
return config;
}
public static void setRewriteConfig(Map<String, BasicConfig> config) {
try {
FileUtils.write(new File(rewriteCacheFile), JsonUtil.toJson(config, true));
} catch (IOException e) {
LOGGER.error("rewrite local cache setting is fail", e);
}
}
public static Map<String, BasicConfig> getRedirectConfig() {
Map<String, BasicConfig> config = Maps.newHashMap();
File file = new File(redirectCacheFile);
if (file.exists()) {
try {
config.putAll(JsonUtil.fromJson(FileUtils.readFileToString(file), new TypeReference<Map<String, BasicConfig>>() {
}));
} catch (Exception e) {
file.delete();
LOGGER.warn("format of redirect local config is incorrect", e);
}
}
return config;
}
public static void setRedirectConfig(Map<String, BasicConfig> config) {
try {
FileUtils.write(new File(redirectCacheFile), JsonUtil.toJson(config, true));
} catch (IOException e) {
LOGGER.error("redirect local cache setting is fail", e);
}
}
public static void setTranslateConfig(Map<String, ForwardConfig> config) {
try {
FileUtils.write(new File(forwardCacheFile), JsonUtil.toJson(config, true));
} catch (IOException e) {
LOGGER.error("translate local cache setting is fail", e);
}
}
public static Map<String, ForwardConfig> getTranslateConfig() {
Map<String, ForwardConfig> config = Maps.newHashMap();
File file = new File(forwardCacheFile);
if (file.exists()) {
try {
config.putAll(JsonUtil.fromJson(FileUtils.readFileToString(file), new TypeReference<Map<String, ForwardConfig>>() {
}));
} catch (Exception e) {
file.delete();
LOGGER.warn("format of translate local config is incorrect", e);
}
}
return config;
}
}
}
|
package de.polocloud.network.codec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
public class PacketLengthDeserializer extends ByteToMessageDecoder {
private final int byteSize = 5;
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
try {
if (!channelHandlerContext.channel().isActive()) {
byteBuf.skipBytes(byteBuf.readableBytes());
return;
}
if (!byteBuf.isReadable()) return;
final var readerIndex = byteBuf.readerIndex();
final var bytes = new byte[this.byteSize];
for (var i = 0; i < this.byteSize; i++) {
if (!byteBuf.isReadable()) {
byteBuf.readerIndex(readerIndex);
return;
}
bytes[i] = byteBuf.readByte();
if (bytes[i] >= 0) {
final var buf = Unpooled.wrappedBuffer(bytes);
try {
final var length = this.readVarIntUnchecked(buf);
if (byteBuf.readableBytes() < length) {
byteBuf.readerIndex(readerIndex);
return;
}
list.add(byteBuf.readBytes(length));
} finally {
buf.release();
}
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private int readVarIntUnchecked(ByteBuf byteBuf) {
var i = 0;
final var maxRead = Math.min(this.byteSize, byteBuf.readableBytes());
for (var j = 0; j < maxRead; j++) {
var k = byteBuf.readByte();
i |= (k & 127) << j * 7;
if ((k & 128) != 128) {
return i;
}
}
return i;
}
}
|
package com.sqxxcx.util.enums;
public enum StatusService implements StatusEnum {
SUCCESS(200,"处理成功"),FAIL(4404,"访问资源不存在"),PARAM_ERROR(4600,"请求参数异常"),SERVICE_ERROR(5210,"接口调用异常");
private final int code;
private final String message;
@Override
public Class<?> getStatusEnumType() {
// TODO Auto-generated method stub
return getClass();
}
@Override
public int getStatusEnumCode() {
// TODO Auto-generated method stub
return this.code;
}
@Override
public String getStatusName() {
// TODO Auto-generated method stub
return name();
}
@Override
public String getStatusReason() {
// TODO Auto-generated method stub
return this.message;
}
@Override
public String getMessage() {
// TODO Auto-generated method stub
return this.message;
}
private StatusService(int code, String message) {
this.code = code;
this.message = message;
}
}
|
package com.microboot.cn.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class BBSNew {
private Long id;
private String name;
private String contact;
private Date createTime;
public BBSNew(Long id, String name, String contact, Date createTime) {
this.id = id;
this.name = name;
this.contact = contact;
this.createTime = createTime;
}
}
|
/*
* Copyright 1997-2019 Unidata Program Center/University Corporation for
* Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
* support@unidata.ucar.edu.
*
* This library 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 library 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 library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package ucar.visad.display;
import visad.*;
import visad.bom.*;
import java.awt.event.InputEvent;
import java.rmi.RemoteException;
/**
* Provides support for a Displayable that comprises a rubber band box.
* The box can be drawn in spherical and other non-Cartesian coordinate
* systems by selecting the appropriate X and Y RealTypes.<P>
* Sample usage:<P>
* <PRE>
* RubberBandBox rbBox =
* new RubberBandBox(RealType.Latitude, RealType.Longitude);
* rbBox.addAction(new ActionImpl() {
* public void doAction()
* throws VisADException, RemoteException
* {
* Gridded2DSet bounds = rbBox.getBounds();
* (do something useful with the box)
* }
* });
* </PRE>
* @author Don Murray
* @version $Revision: 1.10 $
*/
public class RubberBandBox extends LineDrawing {
/** x type for the box */
private RealType xType;
/** y type for the box */
private RealType yType;
/** renderer */
private RubberBandBoxRendererJ3D rubberBandBox;
/** bounds defined by the rubber band box */
private Gridded2DSet bounds;
/** mouse event mask */
private int mask;
/**
* Construct a RubberBandBox using xType as the X coordinate and
* yType as the Y coordinate of the box.
*
* @param xType RealType of the X coordinate of the box
* @param yType RealType of the Y coordinate of the box
*
* @throws VisADException VisAD error
* @throws RemoteException Remote error
*/
public RubberBandBox(RealType xType, RealType yType)
throws VisADException, RemoteException {
this(xType, yType, 0);
}
/**
* Construct a RubberBandBox using xType as the X coordinate and
* yType as the Y coordinate of the box.
*
* @param xType RealType of the X coordinate of the box
* @param yType RealType of the Y coordinate of the box
* @param mask key mask to use for rubberbanding
*
* @throws VisADException VisAD error
* @throws RemoteException Remote error
*/
public RubberBandBox(RealType xType, RealType yType, int mask)
throws VisADException, RemoteException {
super("Rubber Band Box");
this.xType = xType;
this.yType = yType;
this.mask = mask;
bounds = new Gridded2DSet(new RealTupleType(xType, yType), null, 1);
setData(bounds);
}
/**
* Constructor for creating a RubberBandBox from another instance
*
* @param that other instance
*
* @throws VisADException VisAD error
* @throws RemoteException Remote error
*/
protected RubberBandBox(RubberBandBox that)
throws VisADException, RemoteException {
super(that);
this.xType = that.xType;
this.yType = that.yType;
this.bounds = that.bounds;
}
/**
* Invoked when box mouse is released. Subclasses should invoke
* super.dataChange() to ensure the the bounds are set.
*
* @throws RemoteException
* @throws VisADException
*/
protected void dataChange() throws VisADException, RemoteException {
bounds = (Gridded2DSet) getData();
/* debug
float[] highs = bounds.getHi();
float[] lows = bounds.getLow();
if (highs != null && lows != null)
System.out.println("box: X range = " + lows[0] + " to " +
highs[0] +
"; Y range = " + lows[1] + " to " + highs[1] );
*/
super.dataChange();
}
/**
* Return the bounds of the RubberBandBox. The Gridded2DSet that
* is returned contains the opposite (starting and ending) corners
* of the box.
*
* @return set containing the opposite corners of the box.
*/
public Gridded2DSet getBounds() {
return bounds;
}
/**
* Get the range of values for the X RealType as a Linear1DSet
*
* @return array of min and max values
* @throws VisADException VisAD error
* public Linear1DSet getXRange()
* throws VisADException
* {
* float[] highs = bounds.getHi();
* float[] lows = bounds.getLow();
* return
* (highs == null || lows == null)
* ? (Linear1DSet) null
* : new Linear1DSet(xType, lows[0], highs[0], 2);
* }
*/
/**
* Get the range of values for the Y RealType
*
* @return array of min and max values
* @throws VisADException VisAD error
* public Linear1DSet getYRange()
* throws VisADException
* {
* float[] highs = bounds.getHi();
* float[] lows = bounds.getLow();
* return
* (highs == null || lows == null)
* ? (Linear1DSet) null
* : new Linear1DSet(yType, lows[1], highs[1], 2);
* }
*/
/**
* Get the DataRenderer used for this displayable.
*
* @return RubberBandBoxRendererJ3D associated with this displayable
*/
protected DataRenderer getDataRenderer() {
rubberBandBox = new RubberBandBoxRendererJ3D(xType, yType, mask,
mask);
return rubberBandBox;
}
/**
* _more_
*/
public void reSetBounds() {
try {
bounds = new Gridded2DSet(new RealTupleType(xType, yType), null,
1);
} catch (Exception ee) {}
}
/**
* Returns a clone of this instance suitable for another VisAD display.
* Underlying data objects are not cloned.
*
* @return A semi-deep clone of this instance.
*
* @throws VisADException VisAD failure.
* @throws RemoteException Java RMI failure.
*/
public Displayable cloneForDisplay()
throws RemoteException, VisADException {
return new RubberBandBox(this);
}
}
|
package com.linln.modules.system.service.impl;
import com.linln.modules.system.domain.Scale;
import com.linln.modules.system.repository.ScaleRepository;
import com.linln.modules.system.service.ScaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author 小懒虫
* @date 2018/8/14
*/
@Service
public class ScaleServiceImpl implements ScaleService {
@Autowired
ScaleRepository scaleRepository;
@Override
public Page<Scale> fetchScaleBySearch(String searchText, Pageable request) {
return scaleRepository.fetchScaleBySearch(searchText,request);
}
@Override
public Scale save(Scale scale) {
return scaleRepository.save(scale);
}
@Override
public Scale getOne(String scaleId) {
return scaleRepository.getOne(scaleId);
}
@Override
public Scale findByOnlyNoId(String onlyNoId) {
return scaleRepository.findByOnlyNoId(onlyNoId);
}
/**
* 根据测评计划id查询所属的量表
* @param asseId
* @return
*/
@Override
public List<Scale> findScaleByAsseId(String asseId) {
return scaleRepository.findScaleByAsseId(asseId);
}
@Override
public Page<List<Map<String,String>>> findScales(String assId, Pageable request) {
return scaleRepository.findScales(assId,request);
}
@Override
public List<Map<String, String>> findListByAss(String asseId,Long userId) {
return scaleRepository.findListByAss(asseId,userId);
}
@Override
public List<Scale> findByIsGroup(Object[] arr) {
return scaleRepository.findByIsGroup(arr);
}
}
|
package com.example.bruno.ilernaauto_bruno_castro_v2;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class LoginIlernaAuto extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_ilerna_auto);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_ilerna_auto, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.preferencias) {
Intent intent = new Intent(getApplicationContext(), EleccionVehiculo.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public void cambioActividad(View view) {
Intent intent = new Intent(getApplicationContext(), CompraVenta.class);
startActivity(intent);
}
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.xml.serialization;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.Attribute;
import system.xml.schema.XmlSchemaForm;
/**
* The base .NET class managing System.Xml.Serialization.XmlArrayItemAttribute, System.Private.Xml, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51. Extends {@link NetObject}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Xml.Serialization.XmlArrayItemAttribute" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Xml.Serialization.XmlArrayItemAttribute</a>
*/
public class XmlArrayItemAttribute extends Attribute {
/**
* Fully assembly qualified name: System.Private.Xml, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
*/
public static final String assemblyFullName = "System.Private.Xml, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51";
/**
* Assembly name: System.Private.Xml
*/
public static final String assemblyShortName = "System.Private.Xml";
/**
* Qualified class name: System.Xml.Serialization.XmlArrayItemAttribute
*/
public static final String className = "System.Xml.Serialization.XmlArrayItemAttribute";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XmlArrayItemAttribute(Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link XmlArrayItemAttribute}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link XmlArrayItemAttribute} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static XmlArrayItemAttribute cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new XmlArrayItemAttribute(from.getJCOInstance());
}
// Constructors section
public XmlArrayItemAttribute() throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XmlArrayItemAttribute(java.lang.String elementName) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(elementName));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XmlArrayItemAttribute(java.lang.String elementName, NetType type) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(elementName, type == null ? null : type.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XmlArrayItemAttribute(NetType type) throws Throwable {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(type == null ? null : type.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
// Properties section
public boolean getIsNullable() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (boolean)classInstance.Get("IsNullable");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setIsNullable(boolean IsNullable) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("IsNullable", IsNullable);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public int getNestingLevel() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (int)classInstance.Get("NestingLevel");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setNestingLevel(int NestingLevel) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("NestingLevel", NestingLevel);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getDataType() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("DataType");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setDataType(java.lang.String DataType) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("DataType", DataType);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getElementName() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("ElementName");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setElementName(java.lang.String ElementName) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("ElementName", ElementName);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getNamespace() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("Namespace");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setNamespace(java.lang.String Namespace) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("Namespace", Namespace);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public NetType getType() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("Type");
return new NetType(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setType(NetType Type) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("Type", Type == null ? null : Type.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XmlSchemaForm getForm() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("Form");
return new XmlSchemaForm(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void setForm(XmlSchemaForm Form) throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Set("Form", Form == null ? null : Form.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
}
|
/**
* Copyright © 2016-2022 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.rules.flow;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.thingsboard.rule.engine.metadata.TbGetAttributesNodeConfiguration;
import org.thingsboard.server.actors.ActorSystemContext;
import org.thingsboard.server.common.data.*;
import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry;
import org.thingsboard.server.common.data.kv.StringDataEntry;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.common.data.rule.RuleChainMetaData;
import org.thingsboard.server.common.data.rule.RuleNode;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg;
import org.thingsboard.server.common.msg.queue.TbMsgCallback;
import org.thingsboard.server.controller.AbstractRuleEngineControllerTest;
import org.thingsboard.server.dao.attributes.AttributesService;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Valerii Sosliuk
*/
@Slf4j
public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRuleEngineControllerTest {
protected Tenant savedTenant;
protected User tenantAdmin;
@Autowired
protected ActorSystemContext actorSystem;
@Autowired
protected AttributesService attributesService;
@Before
public void beforeTest() throws Exception {
loginSysAdmin();
Tenant tenant = new Tenant();
tenant.setTitle("My tenant");
savedTenant = doPost("/api/tenant", tenant, Tenant.class);
Assert.assertNotNull(savedTenant);
ruleChainService.deleteRuleChainsByTenantId(savedTenant.getId());
tenantAdmin = new User();
tenantAdmin.setAuthority(Authority.TENANT_ADMIN);
tenantAdmin.setTenantId(savedTenant.getId());
tenantAdmin.setEmail("tenant2@thingsboard.org");
tenantAdmin.setFirstName("Joe");
tenantAdmin.setLastName("Downs");
createUserAndLogin(tenantAdmin, "testPassword1");
}
@After
public void afterTest() throws Exception {
loginSysAdmin();
if (savedTenant != null) {
doDelete("/api/tenant/" + savedTenant.getId().getId().toString()).andExpect(status().isOk());
}
}
@Test
public void testRuleChainWithTwoRules() throws Exception {
// Creating Rule Chain
RuleChain ruleChain = new RuleChain();
ruleChain.setName("Simple Rule Chain");
ruleChain.setTenantId(savedTenant.getId());
ruleChain.setRoot(true);
ruleChain.setDebugMode(true);
ruleChain = saveRuleChain(ruleChain);
Assert.assertNull(ruleChain.getFirstRuleNodeId());
RuleChainMetaData metaData = new RuleChainMetaData();
metaData.setRuleChainId(ruleChain.getId());
RuleNode ruleNode1 = new RuleNode();
ruleNode1.setName("Simple Rule Node 1");
ruleNode1.setType(org.thingsboard.rule.engine.metadata.TbGetAttributesNode.class.getName());
ruleNode1.setDebugMode(true);
TbGetAttributesNodeConfiguration configuration1 = new TbGetAttributesNodeConfiguration();
configuration1.setServerAttributeNames(Collections.singletonList("serverAttributeKey1"));
ruleNode1.setConfiguration(mapper.valueToTree(configuration1));
RuleNode ruleNode2 = new RuleNode();
ruleNode2.setName("Simple Rule Node 2");
ruleNode2.setType(org.thingsboard.rule.engine.metadata.TbGetAttributesNode.class.getName());
ruleNode2.setDebugMode(true);
TbGetAttributesNodeConfiguration configuration2 = new TbGetAttributesNodeConfiguration();
configuration2.setServerAttributeNames(Collections.singletonList("serverAttributeKey2"));
ruleNode2.setConfiguration(mapper.valueToTree(configuration2));
metaData.setNodes(Arrays.asList(ruleNode1, ruleNode2));
metaData.setFirstNodeIndex(0);
metaData.addConnectionInfo(0, 1, "Success");
metaData = saveRuleChainMetaData(metaData);
Assert.assertNotNull(metaData);
ruleChain = getRuleChain(ruleChain.getId());
Assert.assertNotNull(ruleChain.getFirstRuleNodeId());
// Saving the device
Device device = new Device();
device.setName("My device");
device.setType("default");
device = doPost("/api/device", device, Device.class);
attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))).get();
attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))).get();
TbMsgCallback tbMsgCallback = Mockito.mock(TbMsgCallback.class);
Mockito.when(tbMsgCallback.isMsgValid()).thenReturn(true);
TbMsg tbMsg = TbMsg.newMsg("CUSTOM", device.getId(), new TbMsgMetaData(), "{}", tbMsgCallback);
QueueToRuleEngineMsg qMsg = new QueueToRuleEngineMsg(savedTenant.getId(), tbMsg, null, null);
// Pushing Message to the system
actorSystem.tell(qMsg);
Mockito.verify(tbMsgCallback, Mockito.timeout(10000)).onSuccess();
PageData<Event> eventsPage = getDebugEvents(savedTenant.getId(), ruleChain.getFirstRuleNodeId(), 1000);
List<Event> events = eventsPage.getData().stream().filter(filterByCustomEvent()).collect(Collectors.toList());
Assert.assertEquals(2, events.size());
Event inEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.IN)).findFirst().get();
Assert.assertEquals(ruleChain.getFirstRuleNodeId(), inEvent.getEntityId());
Assert.assertEquals(device.getId().getId().toString(), inEvent.getBody().get("entityId").asText());
Event outEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.OUT)).findFirst().get();
Assert.assertEquals(ruleChain.getFirstRuleNodeId(), outEvent.getEntityId());
Assert.assertEquals(device.getId().getId().toString(), outEvent.getBody().get("entityId").asText());
Assert.assertEquals("serverAttributeValue1", getMetadata(outEvent).get("ss_serverAttributeKey1").asText());
RuleChain finalRuleChain = ruleChain;
RuleNode lastRuleNode = metaData.getNodes().stream().filter(node -> !node.getId().equals(finalRuleChain.getFirstRuleNodeId())).findFirst().get();
eventsPage = getDebugEvents(savedTenant.getId(), lastRuleNode.getId(), 1000);
events = eventsPage.getData().stream().filter(filterByCustomEvent()).collect(Collectors.toList());
Assert.assertEquals(2, events.size());
inEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.IN)).findFirst().get();
Assert.assertEquals(lastRuleNode.getId(), inEvent.getEntityId());
Assert.assertEquals(device.getId().getId().toString(), inEvent.getBody().get("entityId").asText());
outEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.OUT)).findFirst().get();
Assert.assertEquals(lastRuleNode.getId(), outEvent.getEntityId());
Assert.assertEquals(device.getId().getId().toString(), outEvent.getBody().get("entityId").asText());
Assert.assertEquals("serverAttributeValue1", getMetadata(outEvent).get("ss_serverAttributeKey1").asText());
Assert.assertEquals("serverAttributeValue2", getMetadata(outEvent).get("ss_serverAttributeKey2").asText());
}
@Test
public void testTwoRuleChainsWithTwoRules() throws Exception {
// Creating Rule Chain
RuleChain rootRuleChain = new RuleChain();
rootRuleChain.setName("Root Rule Chain");
rootRuleChain.setTenantId(savedTenant.getId());
rootRuleChain.setRoot(true);
rootRuleChain.setDebugMode(true);
rootRuleChain = saveRuleChain(rootRuleChain);
Assert.assertNull(rootRuleChain.getFirstRuleNodeId());
// Creating Rule Chain
RuleChain secondaryRuleChain = new RuleChain();
secondaryRuleChain.setName("Secondary Rule Chain");
secondaryRuleChain.setTenantId(savedTenant.getId());
secondaryRuleChain.setRoot(false);
secondaryRuleChain.setDebugMode(true);
secondaryRuleChain = saveRuleChain(secondaryRuleChain);
Assert.assertNull(secondaryRuleChain.getFirstRuleNodeId());
RuleChainMetaData rootMetaData = new RuleChainMetaData();
rootMetaData.setRuleChainId(rootRuleChain.getId());
RuleNode ruleNode1 = new RuleNode();
ruleNode1.setName("Simple Rule Node 1");
ruleNode1.setType(org.thingsboard.rule.engine.metadata.TbGetAttributesNode.class.getName());
ruleNode1.setDebugMode(true);
TbGetAttributesNodeConfiguration configuration1 = new TbGetAttributesNodeConfiguration();
configuration1.setServerAttributeNames(Collections.singletonList("serverAttributeKey1"));
ruleNode1.setConfiguration(mapper.valueToTree(configuration1));
rootMetaData.setNodes(Collections.singletonList(ruleNode1));
rootMetaData.setFirstNodeIndex(0);
rootMetaData.addRuleChainConnectionInfo(0, secondaryRuleChain.getId(), "Success", mapper.createObjectNode());
rootMetaData = saveRuleChainMetaData(rootMetaData);
Assert.assertNotNull(rootMetaData);
rootRuleChain = getRuleChain(rootRuleChain.getId());
Assert.assertNotNull(rootRuleChain.getFirstRuleNodeId());
RuleChainMetaData secondaryMetaData = new RuleChainMetaData();
secondaryMetaData.setRuleChainId(secondaryRuleChain.getId());
RuleNode ruleNode2 = new RuleNode();
ruleNode2.setName("Simple Rule Node 2");
ruleNode2.setType(org.thingsboard.rule.engine.metadata.TbGetAttributesNode.class.getName());
ruleNode2.setDebugMode(true);
TbGetAttributesNodeConfiguration configuration2 = new TbGetAttributesNodeConfiguration();
configuration2.setServerAttributeNames(Collections.singletonList("serverAttributeKey2"));
ruleNode2.setConfiguration(mapper.valueToTree(configuration2));
secondaryMetaData.setNodes(Collections.singletonList(ruleNode2));
secondaryMetaData.setFirstNodeIndex(0);
secondaryMetaData = saveRuleChainMetaData(secondaryMetaData);
Assert.assertNotNull(secondaryMetaData);
// Saving the device
Device device = new Device();
device.setName("My device");
device.setType("default");
device = doPost("/api/device", device, Device.class);
attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))).get();
attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE,
Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))).get();
TbMsgCallback tbMsgCallback = Mockito.mock(TbMsgCallback.class);
Mockito.when(tbMsgCallback.isMsgValid()).thenReturn(true);
TbMsg tbMsg = TbMsg.newMsg("CUSTOM", device.getId(), new TbMsgMetaData(), "{}", tbMsgCallback);
QueueToRuleEngineMsg qMsg = new QueueToRuleEngineMsg(savedTenant.getId(), tbMsg, null, null);
// Pushing Message to the system
actorSystem.tell(qMsg);
Mockito.verify(tbMsgCallback, Mockito.timeout(10000)).onSuccess();
PageData<Event> eventsPage = getDebugEvents(savedTenant.getId(), rootRuleChain.getFirstRuleNodeId(), 1000);
List<Event> events = eventsPage.getData().stream().filter(filterByCustomEvent()).collect(Collectors.toList());
Assert.assertEquals(2, events.size());
Event inEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.IN)).findFirst().get();
Assert.assertEquals(rootRuleChain.getFirstRuleNodeId(), inEvent.getEntityId());
Assert.assertEquals(device.getId().getId().toString(), inEvent.getBody().get("entityId").asText());
Event outEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.OUT)).findFirst().get();
Assert.assertEquals(rootRuleChain.getFirstRuleNodeId(), outEvent.getEntityId());
Assert.assertEquals(device.getId().getId().toString(), outEvent.getBody().get("entityId").asText());
Assert.assertEquals("serverAttributeValue1", getMetadata(outEvent).get("ss_serverAttributeKey1").asText());
RuleChain finalRuleChain = rootRuleChain;
RuleNode lastRuleNode = secondaryMetaData.getNodes().stream().filter(node -> !node.getId().equals(finalRuleChain.getFirstRuleNodeId())).findFirst().get();
eventsPage = getDebugEvents(savedTenant.getId(), lastRuleNode.getId(), 1000);
events = eventsPage.getData().stream().filter(filterByCustomEvent()).collect(Collectors.toList());
Assert.assertEquals(2, events.size());
inEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.IN)).findFirst().get();
Assert.assertEquals(lastRuleNode.getId(), inEvent.getEntityId());
Assert.assertEquals(device.getId().getId().toString(), inEvent.getBody().get("entityId").asText());
outEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.OUT)).findFirst().get();
Assert.assertEquals(lastRuleNode.getId(), outEvent.getEntityId());
Assert.assertEquals(device.getId().getId().toString(), outEvent.getBody().get("entityId").asText());
Assert.assertEquals("serverAttributeValue1", getMetadata(outEvent).get("ss_serverAttributeKey1").asText());
Assert.assertEquals("serverAttributeValue2", getMetadata(outEvent).get("ss_serverAttributeKey2").asText());
}
}
|
/* 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.flowable.cmmn.test.delegate;
import org.flowable.cmmn.api.delegate.DelegatePlanItemInstance;
import org.flowable.cmmn.api.delegate.PlanItemJavaDelegate;
import org.flowable.engine.common.api.delegate.Expression;
/**
* @author Tijs Rademakers
*/
public class TestFieldsJavaDelegate implements PlanItemJavaDelegate {
protected String testValue;
protected Expression testExpression;
@Override
public void execute(DelegatePlanItemInstance planItemInstance) {
planItemInstance.setVariable("testValue", testValue);
planItemInstance.setVariable("testExpression", testExpression.getValue(planItemInstance));
}
}
|
package com.everyDayUse.serviceImpl;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.erveryDayUse.domain.User;
import com.everyDayUse.dao.IGenericDao;
import com.everyDayUse.service.UserService;
public class UserServiceImpl extends BaseService implements UserService {
@Autowired
private IGenericDao<User, Integer> genericDao;
@Override
public User findUserByLoginNameAndLoginPassword(User model) {
DetachedCriteria criteria = DetachedCriteria.forClass(User.class)
.add(Restrictions.eq("userName", model.getUserName()))
.add(Restrictions.eq("password", model.getPassword()));
return (User) genericDao.findObject(criteria);
}
@Override
public void updateUserToDataBase(User model) {
User user = genericDao.findObjectById(User.class, model.getId());
user.setConsumes(model.getConsumes());
user.setCrewNum(model.getCrewNum());
}
@Override
public User finUserById(User model) {
return genericDao.findObjectById(User.class, model.getId());
}
}
|
package org.noear.fineio.core;
import org.noear.fineio.FineException;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* 网络客户端
* */
public class NetClient<T> implements Sender<T>{
private ResourcePool<NetConnector<T>> connectors;
private final IoConfig<T> config;
public NetClient(Protocol<T> protocol, NetConnectorFactory<T> connectorFactory) {
this(protocol, new IoConfig<T>(), connectorFactory);
}
public NetClient(Protocol<T> protocol, IoConfig<T> cfg, NetConnectorFactory<T> connectorFactory) {
this.config = cfg;
this.config.setProtocol(protocol);
this.connectors = new ResourcePool<>(Runtime.getRuntime().availableProcessors() * 2 + 1, new ResourceFactory<NetConnector<T>>() {
@Override
public NetConnector<T> create() throws Throwable {
return connectorFactory.create(config);
}
@Override
public NetConnector<T> check(NetConnector<T> connector) {
return connectorFactory.check(connector);
}
@Override
public NetConnector<T> free(NetConnector<T> connector) {
return connectorFactory.free(connector);
}
@Override
public void close(NetConnector<T> connector) {
connectorFactory.close(connector);
}
});
}
public IoConfig<T> config() {
return this.config;
}
public NetClient<T> bind(InetSocketAddress address) {
config.setAddress(address);
return this;
}
public NetClient<T> bind(String hostname, int port) {
if (hostname == null) {
return bind(new InetSocketAddress(port));
} else {
return bind(new InetSocketAddress(hostname, port));
}
}
public NetClient<T> connectionTimeout(int seconds) {
config.setConnectionTimeout(seconds);
return this;
}
/**
* 接收
*/
public NetClient<T> handle(MessageHandler<T> handler) {
config.setHandler(handler);
return this;
}
/**
* 发送
*/
public void send(T message) {
NetConnector<T> c = connectors.apply();
if (c != null) {
try {
c.send(message);
} finally {
connectors.free();
}
} else {
throw new FineException("Failed to get connection!");
}
}
/**
* 获取一个连接
*/
public NetConnector<T> getConnector() {
return connectors.apply();
}
/**
* 关闭客户端
*/
public void colse() {
connectors.clear();
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho;
import com.facebook.litho.annotations.Event;
/**
* Event triggered when a Component enters the Visible Range. This happens when at least a pixel of
* the Component is visible.
*/
@Event
public class VisibleEvent {}
|
package com.java110.dto;
import com.java110.dto.fee.FeeDto;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* @ClassName FloorDto
* @Description 小区房屋数据层封装
* @Author wuxw
* @Date 2019/4/24 8:52
* @Version 1.0
* add by wuxw 2019/4/24
**/
public class RoomDto extends PageDto implements Serializable {
public static final String STATE_SELL = "2001"; // 已入住
public static final String STATE_FREE = "2002"; //未入住
public static final String STATE_DELIVERY = "2003";//已交房
public static final String STATE_RENOVATION = "2005";//已装修
public static final String STATE_SHOP_FIRE = "2006";//已经租
public static final String STATE_SHOP_SELL = "2007";//已售
public static final String STATE_SHOP_FREE = "2008";//空闲
public static final String ROOM_TYPE_ROOM = "1010301";//普通房屋
public static final String ROOM_TYPE_SHOPS = "2020602";//商铺
private String feeCoefficient;
private String section;
private String remark;
private String userId;
private String roomId;
private String[] roomIds;
private String layer;
private String builtUpArea;
private String roomNum;
private String unitId;
private String unitArea;
private String apartment;
private String apartmentName;
private String communityId;
private String floorId;
private String floorNum;
private String floorArea;
private String userName;
private String ownerId;
private String ownerName;
private String idCard;
private String link;
private String roomType;
private String state;
private String[] states;
private String stateName;
private String unitNum;
private List<RoomAttrDto> roomAttrDto;
private List<FeeDto> fees;
private Date createTime;
private String statusCd = "0";
public String getFeeCoefficient() {
return feeCoefficient;
}
public void setFeeCoefficient(String feeCoefficient) {
this.feeCoefficient = feeCoefficient;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRoomId() {
return roomId;
}
public void setRoomId(String roomId) {
this.roomId = roomId;
}
public String getLayer() {
return layer;
}
public void setLayer(String layer) {
this.layer = layer;
}
public String getBuiltUpArea() {
return builtUpArea;
}
public void setBuiltUpArea(String builtUpArea) {
this.builtUpArea = builtUpArea;
}
public String getRoomNum() {
return roomNum;
}
public void setRoomNum(String roomNum) {
this.roomNum = roomNum;
}
public String getUnitId() {
return unitId;
}
public void setUnitId(String unitId) {
this.unitId = unitId;
}
public String getApartment() {
return apartment;
}
public void setApartment(String apartment) {
this.apartment = apartment;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getStatusCd() {
return statusCd;
}
public void setStatusCd(String statusCd) {
this.statusCd = statusCd;
}
public List<RoomAttrDto> getRoomAttrDto() {
return roomAttrDto;
}
public void setRoomAttrDto(List<RoomAttrDto> roomAttrDto) {
this.roomAttrDto = roomAttrDto;
}
public String getCommunityId() {
return communityId;
}
public void setCommunityId(String communityId) {
this.communityId = communityId;
}
public String getFloorId() {
return floorId;
}
public void setFloorId(String floorId) {
this.floorId = floorId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUnitNum() {
return unitNum;
}
public void setUnitNum(String unitNum) {
this.unitNum = unitNum;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
public String getFloorNum() {
return floorNum;
}
public void setFloorNum(String floorNum) {
this.floorNum = floorNum;
}
public String[] getRoomIds() {
return roomIds;
}
public void setRoomIds(String[] roomIds) {
this.roomIds = roomIds;
}
public String getApartmentName() {
return apartmentName;
}
public void setApartmentName(String apartmentName) {
this.apartmentName = apartmentName;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getUnitArea() {
return unitArea;
}
public void setUnitArea(String unitArea) {
this.unitArea = unitArea;
}
public String getFloorArea() {
return floorArea;
}
public void setFloorArea(String floorArea) {
this.floorArea = floorArea;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String[] getStates() {
return states;
}
public void setStates(String[] states) {
this.states = states;
}
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public List<FeeDto> getFees() {
return fees;
}
public void setFees(List<FeeDto> fees) {
this.fees = fees;
}
}
|
/*
* Copyright 2017 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.cucumber.platform.smartmetering.glue.steps.ws.smartmetering.smartmeteringbundle;
import static org.assertj.core.api.Assertions.assertThat;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.bundle.ActualMeterReadsResponse;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.bundle.GetActualMeterReadsRequest;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.common.Response;
public class BundledGetActualMeterReadsSteps extends BaseBundleSteps {
@Given("^the bundle request contains a get actual meter reads action$")
public void theBundleRequestContainsAGetActualMeterReadsAction() throws Throwable {
final GetActualMeterReadsRequest action = new GetActualMeterReadsRequest();
this.addActionToBundleRequest(action);
}
@Then("^the bundle response should contain a get actual meter reads response$")
public void theBundleResponseShouldContainAGetActualMeterReadsResponse() throws Throwable {
final Response response = this.getNextBundleResponse();
assertThat(response instanceof ActualMeterReadsResponse).as("Not a valid response").isTrue();
}
}
|
package io.github.elkin.commandline;
public interface HelpGenerator {
String generateHelp(CommandLineConfiguration configuration);
}
|
package com.millenniumprogrammers.neocomer.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Zonasdisponibles{
private int id_zona;
private String Apodo;
private double longitud;
private double latitud;
private boolean estado;
}
|
package org.springrain.weixin.sdk.mp.api;
import java.io.File;
import java.util.Map;
import org.springrain.weixin.sdk.common.exception.WxErrorException;
import org.springrain.weixin.sdk.common.service.IWxMpConfig;
import org.springrain.weixin.sdk.mp.bean.pay.WxPayJsSDKCallback;
import org.springrain.weixin.sdk.mp.bean.pay.request.WxEntPayRequest;
import org.springrain.weixin.sdk.mp.bean.pay.request.WxPayRefundRequest;
import org.springrain.weixin.sdk.mp.bean.pay.request.WxPaySendRedpackRequest;
import org.springrain.weixin.sdk.mp.bean.pay.request.WxPayUnifiedOrderRequest;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxEntPayQueryResult;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxEntPayResult;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxPayOrderCloseResult;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxPayOrderQueryResult;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxPayRedpackQueryResult;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxPayRefundQueryResult;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxPayRefundResult;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxPaySendRedpackResult;
import org.springrain.weixin.sdk.mp.bean.pay.result.WxPayUnifiedOrderResult;
/**
* 微信支付相关接口
* Created by springrain on 2017/1/8.
*
* @author springrain (http://git.oschina.net/chunanyong/springrain)
*/
public interface IWxMpPayService {
/**
* <pre>
* 查询订单(详见https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_2)
* 该接口提供所有微信支付订单的查询,商户可以通过查询订单接口主动查询订单状态,完成下一步的业务逻辑。
* 需要调用查询接口的情况:
* ◆ 当商户后台、网络、服务器等出现异常,商户系统最终未接收到支付通知;
* ◆ 调用支付接口后,返回系统错误或未知交易状态情况;
* ◆ 调用被扫支付API,返回USERPAYING的状态;
* ◆ 调用关单或撤销接口API之前,需确认支付状态;
* 接口地址:https://api.mch.weixin.qq.com/pay/orderquery
* </pre>
*
* @param transactionId 微信支付分配的商户号
* @param outTradeNo 商户系统内部的订单号,当没提供transaction_id时需要传这个。
* @throws WxErrorException
*/
WxPayOrderQueryResult queryOrder(IWxMpConfig wxmpconfig,String transactionId, String outTradeNo) throws WxErrorException;
/**
* <pre>
* 关闭订单
* 应用场景
* 以下情况需要调用关单接口:
* 1. 商户订单支付失败需要生成新单号重新发起支付,要对原订单号调用关单,避免重复支付;
* 2. 系统下单后,用户支付超时,系统退出不再受理,避免用户继续,请调用关单接口。
* 注意:订单生成后不能马上调用关单接口,最短调用时间间隔为5分钟。
* 接口地址:https://api.mch.weixin.qq.com/pay/closeorder
* 是否需要证书: 不需要。
* </pre>
*
* @param outTradeNo 商户系统内部的订单号,当没提供transaction_id时需要传这个。
* @throws WxErrorException
*/
WxPayOrderCloseResult closeOrder(IWxMpConfig wxmpconfig,String outTradeNo) throws WxErrorException;
/**
* 统一下单(详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)
* 在发起微信支付前,需要调用统一下单接口,获取"预支付交易会话标识"
* 接口地址:https://api.mch.weixin.qq.com/pay/unifiedorder
*
* @param request 请求对象,注意一些参数如appid、mchid等不用设置,方法内会自动从配置对象中获取到(前提是对应配置中已经设置)
* @throws WxErrorException
*/
WxPayUnifiedOrderResult unifiedOrder(IWxMpConfig wxmpconfig,WxPayUnifiedOrderRequest request) throws WxErrorException;
/**
* 该接口调用“统一下单”接口,并拼装发起支付请求需要的参数
* 详见http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN
*
* @param request 请求对象,注意一些参数如appid、mchid等不用设置,方法内会自动从配置对象中获取到(前提是对应配置中已经设置)
* @throws WxErrorException
*/
Map<String, String> getPayInfo(IWxMpConfig wxmpconfig,WxPayUnifiedOrderRequest request) throws WxErrorException;
/**
* <pre>
* 微信支付-申请退款
* 详见 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
* 接口链接:https://api.mch.weixin.qq.com/secapi/pay/refund
* </pre>
*
* @param request 请求对象
* @param keyFile 证书文件对象
* @return 退款操作结果
*/
WxPayRefundResult refund(IWxMpConfig wxmpconfig,WxPayRefundRequest request, File keyFile) throws WxErrorException;
/**
* <pre>
* 微信支付-查询退款
* 应用场景:
* 提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。
* 详见 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_5
* 接口链接:https://api.mch.weixin.qq.com/pay/refundquery
* </pre>
* 以下四个参数四选一
* @param transactionId 微信订单号
* @param outTradeNo 商户订单号
* @param outRefundNo 商户退款单号
* @param refundId 微信退款单号
* @return 退款信息
*/
WxPayRefundQueryResult refundQuery(IWxMpConfig wxmpconfig,String transactionId, String outTradeNo, String outRefundNo, String refundId) throws WxErrorException;
/**
* 读取支付结果通知
* 详见http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
*/
WxPayJsSDKCallback getJSSDKCallbackData(IWxMpConfig wxmpconfig,String xmlData) throws WxErrorException;
/**
* <pre>
* 计算Map键值对是否和签名相符,
* 按照字段名的 ASCII 码从小到大排序(字典序)后,使用 URL 键值对的 格式(即 key1=value1&key2=value2...)拼接成字符串
* </pre>
*/
boolean checkJSSDKCallbackDataSignature(IWxMpConfig wxmpconfig,Map<String, String> kvm, String signature);
/**
* 发送微信红包给个人用户
* <pre>
* 文档详见:
* 发送普通红包 https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
* 接口地址:https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack
* 发送裂变红包 https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_5&index=4
* 接口地址:https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack
* </pre>
*
* @param request 请求对象
* @param keyFile 证书文件对象
*/
WxPaySendRedpackResult sendRedpack(IWxMpConfig wxmpconfig,WxPaySendRedpackRequest request, File keyFile) throws WxErrorException;
/**
* <pre>
* 查询红包记录
* 用于商户对已发放的红包进行查询红包的具体信息,可支持普通红包和裂变包。
* 请求Url https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo
* 是否需要证书 是(证书及使用说明详见商户证书)
* 请求方式 POST
* </pre>
* @param mchBillNo 商户发放红包的商户订单号,比如10000098201411111234567890
* @param keyFile 证书文件对象
*/
WxPayRedpackQueryResult queryRedpack(IWxMpConfig wxmpconfig,String mchBillNo, File keyFile) throws WxErrorException;
/**
* <pre>
* 企业付款业务是基于微信支付商户平台的资金管理能力,为了协助商户方便地实现企业向个人付款,针对部分有开发能力的商户,提供通过API完成企业付款的功能。
* 比如目前的保险行业向客户退保、给付、理赔。
* 企业付款将使用商户的可用余额,需确保可用余额充足。查看可用余额、充值、提现请登录商户平台“资金管理”https://pay.weixin.qq.com/进行操作。
* 注意:与商户微信支付收款资金并非同一账户,需要单独充值。
* 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
* 接口链接:https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers
* </pre>
*
* @param request 请求对象
* @param keyFile 证书文件对象
*/
WxEntPayResult entPay(IWxMpConfig wxmpconfig,WxEntPayRequest request, File keyFile) throws WxErrorException;
/**
* <pre>
* 查询企业付款API
* 用于商户的企业付款操作进行结果查询,返回付款操作详细结果。
* 文档详见:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3
* 接口链接:https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo
* </pre>
*
* @param partnerTradeNo 商户订单号
* @param keyFile 证书文件对象
*/
WxEntPayQueryResult queryEntPay(IWxMpConfig wxmpconfig,String partnerTradeNo, File keyFile) throws WxErrorException;
}
|
package com.example.ggxiaozhi.yotucomponent.share;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ggxiaozhi.yotucomponent.R;
import com.example.ggxiaozhi.yotucomponent.network.RequestCenter;
import java.util.HashMap;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
/**
* Created by renzhiqiang on 16/8/13.
*/
public class ShareDialog extends Dialog implements View.OnClickListener {
private Context mContext;
private DisplayMetrics dm;
/**
* UI
*/
private RelativeLayout mWeixinLayout;
private RelativeLayout mWeixinMomentLayout;
private RelativeLayout mQQLayout;
private RelativeLayout mQZoneLayout;
private RelativeLayout mDownloadLayout;
private TextView mCancelView;
/**
* share 类型
*/
private int mShareType; //指定分享类型
private String mShareTitle; //指定分享内容标题
private String mShareText; //指定分享内容文本
private String mSharePhoto; //指定分享本地图片
private String mShareTileUrl;
private String mShareSiteUrl;
private String mShareSite;//来源
private String mUrl;
private String mResourceUrl;
private boolean isShowDownload;
public ShareDialog(Context context, boolean isShowDownload) {
super(context, R.style.SheetDialogStyle);
mContext = context;
dm = mContext.getResources().getDisplayMetrics();
this.isShowDownload = false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_share_layout);
initView();
}
private void initView() {
/**
* 通过获取到dialog的window来控制dialog的宽高及位置
*/
Window dialogWindow = getWindow();
dialogWindow.setGravity(Gravity.BOTTOM);
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.width = dm.widthPixels; //设置宽度
dialogWindow.setAttributes(lp);
mWeixinLayout = (RelativeLayout) findViewById(R.id.weixin_layout);
mWeixinLayout.setOnClickListener(this);
mWeixinMomentLayout = (RelativeLayout) findViewById(R.id.moment_layout);
mWeixinMomentLayout.setOnClickListener(this);
mQQLayout = (RelativeLayout) findViewById(R.id.qq_layout);
mQQLayout.setOnClickListener(this);
mQZoneLayout = (RelativeLayout) findViewById(R.id.qzone_layout);
mQZoneLayout.setOnClickListener(this);
mDownloadLayout = (RelativeLayout) findViewById(R.id.download_layout);
mDownloadLayout.setOnClickListener(this);
if (isShowDownload) {
mDownloadLayout.setVisibility(View.VISIBLE);
}
mCancelView = (TextView) findViewById(R.id.cancel_view);
mCancelView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.weixin_layout:
shareData(ShareManager.PlatofrmType.WeChat);
break;
case R.id.moment_layout:
shareData(ShareManager.PlatofrmType.WechatMoments);
break;
case R.id.qq_layout:
shareData(ShareManager.PlatofrmType.QQ);
break;
case R.id.qzone_layout:
shareData(ShareManager.PlatofrmType.QZone);
break;
case R.id.cancel_view:
dismiss();
break;
}
}
private PlatformActionListener mListener = new PlatformActionListener() {
@Override
public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
}
@Override
public void onError(Platform platform, int i, Throwable throwable) {
}
@Override
public void onCancel(Platform platform, int i) {
}
};
private void shareData(ShareManager.PlatofrmType platofrm) {
ShareData mData = new ShareData();
Platform.ShareParams params = new Platform.ShareParams();
params.setShareType(mShareType);
params.setTitle(mShareTitle);
params.setTitleUrl(mShareTileUrl);
params.setSite(mShareSite);
params.setSiteUrl(mShareSiteUrl);
params.setText(mShareText);
params.setImagePath(mSharePhoto);
params.setUrl(mUrl);
mData.mType = platofrm;
mData.mParams = params;
ShareManager.getInstance().shareData(mData, mListener);
}
public void setResourceUrl(String resourceUrl) {
mResourceUrl = resourceUrl;
}
public void setShareTitle(String title) {
mShareTitle = title;
}
public void setImagePhoto(String photo) {
mSharePhoto = photo;
}
public void setShareType(int type) {
mShareType = type;
}
public void setShareSite(String site) {
mShareSite = site;
}
public void setShareTitleUrl(String titleUrl) {
mShareTileUrl = titleUrl;
}
public void setUrl(String url) {
mUrl = url;
}
public void setShareSiteUrl(String siteUrl) {
mShareSiteUrl = siteUrl;
}
public void setShareText(String text) {
mShareText = text;
}
}
|
package com.mk.portal.framework.page.html.tags;
import com.mk.portal.framework.html.objects.Tag;
public class BDOTag extends Tag {
@Override
public boolean hasEndTag() {
return true;
}
@Override
public String getTagName() {
return "bdo";
}
}
|
package com.github.bali.attachment.service;
import com.github.bali.attachment.domain.vo.Upload;
import com.github.bali.attachment.domain.vo.UploadResult;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
/**
* 附件操作
* @author Petty
*/
public interface IAttachmentOperaService {
/**
* 文件操作-文件上传
*
* @param userId userId
* @param upload Upload
* @param file MultipartFile
* @return UploadResult
*/
UploadResult upload(String userId, Upload upload, MultipartFile file);
/**
* 文件操作-文件下载
*
* @param id 文件ID
* @param response HttpServletResponse
* @throws Exception Exception
*/
void download(String id, HttpServletResponse response) throws Exception;
/**
* 文件操作-文件查看
*
* @param id 文件ID
* @param response HttpServletResponse
* @throws Exception Exception
*/
void view(String id, HttpServletResponse response) throws Exception;
/**
* 文件操作-删除文件
*
* @param id 文件ID
* @return Boolean
*/
Boolean delete(String id);
/**
* 文件操作-批量删除文件
*
* @param ids 文件ID
* @return Boolean
*/
Boolean deleteBatch(String[] ids);
}
|
package io.jenkins.plugins.analysis.warnings;
import org.kohsuke.stapler.DataBoundConstructor;
import org.jenkinsci.Symbol;
import hudson.Extension;
import io.jenkins.plugins.analysis.core.model.AnalysisModelParser;
import io.jenkins.plugins.analysis.core.model.IconLabelProvider;
import io.jenkins.plugins.analysis.core.model.StaticAnalysisLabelProvider;
/**
* Provides a parser and customized messages for CheckStyle.
*
* @author Ullrich Hafner
*/
public class CheckStyle extends AnalysisModelParser {
private static final long serialVersionUID = -7944828406964963020L;
private static final String ID = "checkstyle";
/** Creates a new instance of {@link CheckStyle}. */
@DataBoundConstructor
public CheckStyle() {
super();
// empty constructor required for stapler
}
/** Descriptor for this static analysis tool. */
@Symbol("checkStyle")
@Extension
public static class Descriptor extends AnalysisModelParserDescriptor {
/** Creates the descriptor instance. */
public Descriptor() {
super(ID);
}
@Override
public boolean canScanConsoleLog() {
return false;
}
@Override
public StaticAnalysisLabelProvider getLabelProvider() {
return new IconLabelProvider(ID, getDisplayName(), getDescriptionProvider());
}
}
}
|
package org.skia.androidkit;
import android.graphics.Bitmap;
import org.skia.androidkit.Canvas;
public class Surface {
private long mNativeInstance;
private Canvas mCanvas;
/**
* Create a Surface backed by the provided Bitmap.
*
* The Bitmap must be mutable and its pixels are locked for the lifetime of the Surface.
*/
public Surface(Bitmap bitmap) {
this(CreateBitmapInstance(bitmap));
}
/**
* The Canvas associated with this Surface.
*/
public Canvas getCanvas() {
return mCanvas;
}
/**
* Releases any resources associated with this Surface.
*/
public void release() {
nRelease(mNativeInstance);
mNativeInstance = 0;
}
@Override
protected void finalize() throws Throwable
{
release();
}
private Surface(long native_instance) {
mNativeInstance = native_instance;
mCanvas = new Canvas(this, nGetNativeCanvas(native_instance));
}
private static long CreateBitmapInstance(Bitmap bitmap) {
if (!bitmap.isMutable()) {
throw new IllegalStateException("Immutable bitmap passed to Surface constructor");
}
return nCreateBitmap(bitmap);
}
private static native long nCreateBitmap(Bitmap bitmap);
private static native void nRelease(long nativeInstance);
private static native long nGetNativeCanvas(long nativeInstance);
}
|
/*
* This file is part of sChat, licensed under the MIT License.
* Copyright (C) Silthus <https://www.github.com/silthus>
* Copyright (C) sChat team and 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 net.silthus.schat.bukkit.placeholderapi;
import me.clip.placeholderapi.PlaceholderAPI;
import net.silthus.schat.message.MessageSource;
import net.silthus.schat.ui.placeholder.Replacements;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
public class PlaceholderApiIntegration {
private final Replacements replacements;
public PlaceholderApiIntegration(Replacements replacements) {
this.replacements = replacements;
}
public void init() {
replacements.addReplacementProvider((message, text) -> {
if (message.source().equals(MessageSource.nil()))
return null;
else
return replacePlaceholderAPIPlaceholders(Bukkit.getOfflinePlayer(message.source().uniqueId()), text);
});
}
private String replacePlaceholderAPIPlaceholders(OfflinePlayer player, String text) {
return PlaceholderAPI.setPlaceholders(player, text);
}
}
|
package com.stackroute.recommendationservice.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stackroute.recommendationservice.model.Answer;
import com.stackroute.recommendationservice.model.Question;
import com.stackroute.recommendationservice.model.QuestionNode;
import com.stackroute.recommendationservice.model.UserNode;
import com.stackroute.recommendationservice.repository.UserRepository;
import com.stackroute.recommendationservice.service.RecommendationServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.Arrays;
import java.util.Collections;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@WebMvcTest
public class RecommendationControllerTest {
private static final int QUESTION_ID = 3;
private static final QuestionNode QUESTION_NODE_ONE = QuestionNode.builder().questionId(QUESTION_ID).upvote(20).build();
private static final QuestionNode QUESTION_NODE_TWO = QuestionNode.builder().questionId(QUESTION_ID).upvote(0).build();
private static final Answer ANSWER_REQUESTED = Answer.builder().build();
private static final Question QUESTION_DOCUMENT_ONE = Question.builder().questionId(3)
.answer(Arrays.asList(ANSWER_REQUESTED, ANSWER_REQUESTED, ANSWER_REQUESTED, ANSWER_REQUESTED, ANSWER_REQUESTED))
.build();
private static final UserNode USER_NODE = UserNode.builder().username("Sunidhi").reputation(100).build();
private static final Question QUESTION_DOCUMENT_TWO = Question.builder()
.answer(Collections.singletonList(ANSWER_REQUESTED)).build();
private static final String USERNAME = "USERNAME";
@MockBean
private RecommendationServiceImpl recommendationService;
@MockBean
private UserRepository userRepository;
@Autowired
private RecommendationController recommendationController;
@Autowired
private MockMvc mockMvc;
private String asJsonString(Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(recommendationController).build();
ReflectionTestUtils.setField(recommendationController, "questionUpvoteThreshold", 10);
ReflectionTestUtils.setField(recommendationController, "numberOfAnswersThreshold", 5);
ReflectionTestUtils.setField(recommendationController, "reputationNeeded", 50);
ReflectionTestUtils.setField(recommendationController, "timestampThreshold", 5);
}
@Test
public void testForTrendingQuestionsPresent() throws Exception {
when(recommendationService.getTrendingQuestionsForRegisteredUser(USERNAME)).thenReturn(Collections.singletonList(QUESTION_NODE_ONE));
when(recommendationService.getDocumentByQuestionId(QUESTION_ID)).thenReturn(QUESTION_DOCUMENT_ONE);
mockMvc.perform(MockMvcRequestBuilders.get("/member/trending?username=USERNAME")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(QUESTION_NODE_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testForTrendingQuestionsNotPresent() throws Exception {
when(recommendationService.getTrendingQuestionsForRegisteredUser(USERNAME)).thenReturn(Collections.emptyList());
when(recommendationService.getDocumentByQuestionId(QUESTION_ID)).thenReturn(null);
mockMvc.perform(MockMvcRequestBuilders.get("/member/trending?username=USERNAME")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(QUESTION_NODE_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testForUpvotesLessThanThreshold() throws Exception {
when(recommendationService.getTrendingQuestionsForRegisteredUser(USERNAME)).thenReturn(Collections.singletonList(QUESTION_NODE_TWO));
when(recommendationService.getDocumentByQuestionId(QUESTION_ID)).thenReturn(QUESTION_DOCUMENT_ONE);
mockMvc.perform(MockMvcRequestBuilders.get("/member/trending?username=USERNAME")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(QUESTION_NODE_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testForAnswersLessThanThreshold() throws Exception {
when(recommendationService.getTrendingQuestionsForRegisteredUser(USERNAME)).thenReturn(Collections.singletonList(QUESTION_NODE_ONE));
when(recommendationService.getDocumentByQuestionId(QUESTION_ID)).thenReturn(QUESTION_DOCUMENT_TWO);
mockMvc.perform(MockMvcRequestBuilders.get("/member/trending?username=USERNAME")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(QUESTION_NODE_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testForTopicRelatedUsersArePresent() throws Exception {
when(recommendationService.getAllUsersRelatedToQuestion(QUESTION_ID)).thenReturn(Collections.singletonList(USER_NODE));
mockMvc.perform(MockMvcRequestBuilders.get("/member/notify?questionId=3")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(USER_NODE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testForTopicRelatedUsersAreNotPresent() throws Exception {
when(recommendationService.getAllUsersRelatedToQuestion(QUESTION_ID)).thenReturn(Collections.emptyList());
mockMvc.perform(MockMvcRequestBuilders.get("/member/notify?questionId=3")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(USER_NODE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testUnansweredQuestionPresent() throws Exception {
when(recommendationService.getAllUnansweredQuestionsForRegisteredUser(USERNAME)).thenReturn(Collections.singletonList(QUESTION_NODE_ONE));
when(recommendationService.getDocumentByQuestionId(QUESTION_ID)).thenReturn(QUESTION_DOCUMENT_ONE);
mockMvc.perform(MockMvcRequestBuilders.get("/member/unanswered/USERNAME")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(QUESTION_NODE_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testUnansweredQuestionNotPresent() throws Exception {
when(recommendationService.getAllUnansweredQuestionsForRegisteredUser(USERNAME)).thenReturn(Collections.emptyList());
when(recommendationService.getDocumentByQuestionId(QUESTION_ID)).thenReturn(QUESTION_DOCUMENT_ONE);
mockMvc.perform(MockMvcRequestBuilders.get("/member/unanswered/USERNAME")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(QUESTION_NODE_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testAcceptedQuestionsPresent() throws Exception {
when(recommendationService.getAllAcceptedAnswersOfDomain(USERNAME)).thenReturn(Collections.singletonList(QUESTION_NODE_ONE));
when(recommendationService.getDocumentByQuestionId(QUESTION_ID)).thenReturn(QUESTION_DOCUMENT_ONE);
mockMvc.perform(MockMvcRequestBuilders.get("/acceptedAnswers?username=USERNAME")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(QUESTION_NODE_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testAcceptedQuestionsNotPresent() throws Exception {
when(recommendationService.getAllAcceptedAnswersOfDomain(USERNAME)).thenReturn(Collections.emptyList());
when(recommendationService.getDocumentByQuestionId(QUESTION_ID)).thenReturn(QUESTION_DOCUMENT_ONE);
mockMvc.perform(MockMvcRequestBuilders.get("/acceptedAnswers?username=USERNAME")
.contentType(MediaType.APPLICATION_JSON).content(asJsonString(QUESTION_NODE_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testAcceptedQuestionsPresentForGuestUser() throws Exception {
when(recommendationService.getAllAcceptedAnswersForGuestUser()).thenReturn(Collections.singletonList(QUESTION_DOCUMENT_ONE));
mockMvc.perform(MockMvcRequestBuilders.get("/guest/acceptedAnswers")
.contentType(MediaType.APPLICATION_JSON_UTF8).content(asJsonString(QUESTION_DOCUMENT_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testAcceptedQuestionsNotPresentForGuestUser() throws Exception {
when(recommendationService.getAllAcceptedAnswersForGuestUser()).thenReturn(Collections.emptyList());
mockMvc.perform(MockMvcRequestBuilders.get("/guest/acceptedAnswers")
.contentType(MediaType.APPLICATION_JSON_UTF8).content(asJsonString(QUESTION_DOCUMENT_ONE)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.orc.reader;
import com.facebook.presto.spi.block.Block;
import java.io.IOException;
public interface SelectiveStreamReader
extends StreamReader
{
/**
* Extract values at the specified positions, apply filter and buffer the values that pass
* the filter.
*
* @param positions Monotonically increasing positions to read
* @param positionCount Number of valid positions in the positions array; may be less than the
* size of the array
* @return the number of positions that passed the filter
*/
int read(int offset, int[] positions, int positionCount)
throws IOException;
/**
* @return an array of positions that passed the filter during most recent read(); the return
* value of read() is the number of valid entries in this array; the return value is a strict
* subset of positions passed into read()
*/
int[] getReadPositions();
/**
* Return a subset of the values extracted during most recent read() for the specified positions
* @param positions Monotonically increasing positions to return; must be a strict subset of both
* the list of positions passed into read() and the list of positions returned
* from getReadPositions()
* @param positionCount Number of valid positions in the positions array; may be less than the
* size of the array
*/
Block getBlock(int[] positions, int positionCount);
void close();
}
|
/*
* This file is part of JourneyMapFix, licensed under the MIT License (MIT).
*
* Copyright (c) 2017 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 io.github.barteks2x.journeymapfix.core;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.SortingIndex;
import javax.annotation.Nullable;
import java.util.Map;
@SortingIndex(10000)
public class JMPatchCoremod implements IFMLLoadingPlugin {
@Override public String[] getASMTransformerClass() {
return new String[]{"io.github.barteks2x.journeymapfix.core.JMPatchTransformer"};
}
@Override public String getModContainerClass() {
return null;
}
@Nullable @Override public String getSetupClass() {
return null;
}
@Override public void injectData(Map<String, Object> data) {
}
@Override public String getAccessTransformerClass() {
return null;
}
}
|
package org.laziji.commons.js.model.node;
import com.google.common.collect.ImmutableList;
import org.laziji.commons.js.model.manager.NodeConfiguration;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
public abstract class BasePlanNode extends BaseNode {
private List<BiFunction<Node, Node, Node>> plan;
protected Node[] current;
public BasePlanNode(Node parent) {
super(parent);
}
public BasePlanNode(NodeConfiguration configuration, Node parent) {
super(configuration, parent);
}
@Override
public Node append(TokenUnit unit) throws Exception {
if (plan == null) {
plan = getPlan();
current = new Node[plan.size()];
}
for (int i = 0; i < plan.size(); i++) {
if (current[i] != null) {
continue;
}
if (i > 0 && !current[i - 1].isDone()) {
throw new Exception(String.format("[%s] is not the expected token.", unit.getToken().toString()));
}
current[i] = plan.get(i).apply(this, i > 0 ? current[i - 1] : null);
return current[i].append(unit);
}
if (!current[plan.size() - 1].isDone()) {
throw new Exception(String.format("[%s] is not the expected token.", unit.getToken().toString()));
}
if (getParent() != null) {
return getParent().append(unit);
}
throw new Exception(String.format("[%s] is not the expected token.", unit.getToken().toString()));
}
@Override
public boolean isDone() {
for (Node node : current) {
if (node == null || !node.isDone()) {
return false;
}
}
return true;
}
@Override
public String toString(int depth, boolean start) {
if (getStringFormat() == null) {
return nodesJoin(Arrays.asList(current), " ", false, depth, start);
}
Object[] values = new Object[current.length];
for (int i = 0; i < current.length; i++) {
values[i] = current[i].toString(depth, i == 0 && start);
}
return String.format(getStringFormat(), values);
}
public List<Node> getNodes() {
return ImmutableList.copyOf(current);
}
protected String getStringFormat() {
return null;
}
protected abstract List<BiFunction<Node, Node, Node>> getPlan();
}
|
package it.unibz.inf.ontop.model.term.functionsymbol.db.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Maps;
import it.unibz.inf.ontop.model.term.ImmutableTerm;
import it.unibz.inf.ontop.model.term.TermFactory;
import it.unibz.inf.ontop.model.term.functionsymbol.InequalityLabel;
import it.unibz.inf.ontop.model.term.functionsymbol.db.*;
import it.unibz.inf.ontop.model.type.*;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
public abstract class AbstractSQLDBFunctionSymbolFactory extends AbstractDBFunctionSymbolFactory {
protected static final String UPPER_STR = "UPPER";
protected static final String UCASE_STR = "UCASE";
protected static final String LOWER_STR = "LOWER";
protected static final String LCASE_STR = "LCASE";
protected static final String CONCAT_STR = "CONCAT";
protected static final String REPLACE_STR = "REPLACE";
protected static final String REGEXP_REPLACE_STR = "REGEXP_REPLACE";
protected static final String REGEXP_LIKE_STR = "REGEXP_LIKE";
protected static final String AND_STR = "AND";
protected static final String OR_STR = "OR";
protected static final String NOT_STR = "NOT";
protected static final String SUBSTR_STR = "SUBSTR";
protected static final String SUBSTRING_STR = "SUBSTRING";
protected static final String CHAR_LENGTH_STR = "CHAR_LENGTH";
protected static final String LENGTH_STR = "LENGTH";
protected static final String RIGHT_STR = "RIGHT";
protected static final String MULTIPLY_STR = "*";
protected static final String DIVIDE_STR = "/";
protected static final String ADD_STR = "+";
protected static final String SUBSTRACT_STR = "-";
protected static final String ABS_STR = "ABS";
protected static final String CEIL_STR = "CEIL";
protected static final String ROUND_STR = "ROUND";
protected static final String FLOOR_STR = "FLOOR";
protected static final String RAND_STR = "RAND";
protected static final String CURRENT_TIMESTAMP_STR = "CURRENT_TIMESTAMP";
protected static final String COALESCE_STR = "COALESCE";
protected static final String CONCAT_OP_STR = "||";
protected static final String NULLIF_STR = "NULLIF";
protected DBTypeFactory dbTypeFactory;
protected final TypeFactory typeFactory;
protected final DBTermType dbStringType;
protected final DBTermType dbBooleanType;
protected final DBTermType dbDoubleType;
protected final DBTermType dbIntegerType;
protected final DBTermType dbDecimalType;
protected final DBTermType abstractRootDBType;
protected final TermType abstractRootType;
private final Map<Integer, DBConcatFunctionSymbol> nullRejectingConcatMap;
private final Map<Integer, DBConcatFunctionSymbol> concatOperatorMap;
// Created in init()
private DBFunctionSymbol ifThenElse;
// Created in init()
private DBBooleanFunctionSymbol isStringEmpty;
// Created in init()
private DBIsNullOrNotFunctionSymbol isNull;
// Created in init()
private DBIsNullOrNotFunctionSymbol isNotNull;
// Created in init()
private DBIsTrueFunctionSymbol isTrue;
protected AbstractSQLDBFunctionSymbolFactory(ImmutableTable<String, Integer, DBFunctionSymbol> regularFunctionTable,
TypeFactory typeFactory) {
super(regularFunctionTable, typeFactory);
this.dbTypeFactory = typeFactory.getDBTypeFactory();
this.typeFactory = typeFactory;
this.dbStringType = dbTypeFactory.getDBStringType();
this.dbBooleanType = dbTypeFactory.getDBBooleanType();
this.dbDoubleType = dbTypeFactory.getDBDoubleType();
this.dbIntegerType = dbTypeFactory.getDBLargeIntegerType();
this.dbDecimalType = dbTypeFactory.getDBDecimalType();
this.abstractRootDBType = dbTypeFactory.getAbstractRootDBType();
this.abstractRootType = typeFactory.getAbstractAtomicTermType();
this.nullRejectingConcatMap = Maps.newConcurrentMap();
this.concatOperatorMap = Maps.newConcurrentMap();
}
@Override
protected void init() {
// Always call it first
super.init();
ifThenElse = createDBIfThenElse(dbBooleanType, abstractRootDBType);
isStringEmpty = createIsStringEmpty(dbBooleanType, abstractRootDBType);
isNull = createDBIsNull(dbBooleanType, abstractRootDBType);
isNotNull = createDBIsNotNull(dbBooleanType, abstractRootDBType);
isTrue = createDBIsTrue(dbBooleanType);
}
@Override
protected DBFunctionSymbol createDBCount(boolean isUnary, boolean isDistinct) {
DBTermType integerType = dbTypeFactory.getDBLargeIntegerType();
return isUnary
? new DBCountFunctionSymbolImpl(abstractRootDBType, integerType, isDistinct)
: new DBCountFunctionSymbolImpl(integerType, isDistinct);
}
@Override
protected DBFunctionSymbol createDBSum(DBTermType termType, boolean isDistinct) {
return new NullIgnoringDBSumFunctionSymbol(termType, isDistinct);
}
@Override
protected DBFunctionSymbol createDBAvg(DBTermType inputType, boolean isDistinct) {
DBTermType targetType = inputType.equals(dbIntegerType) ? dbDecimalType : inputType;
return new NullIgnoringDBAvgFunctionSymbol(inputType, targetType, isDistinct);
}
@Override
protected DBFunctionSymbol createDBMin(DBTermType termType) {
return new DBMinFunctionSymbolImpl(termType);
}
@Override
protected DBFunctionSymbol createDBMax(DBTermType termType) {
return new DBMaxFunctionSymbolImpl(termType);
}
protected static ImmutableTable<String, Integer, DBFunctionSymbol> createDefaultRegularFunctionTable(TypeFactory typeFactory) {
DBTypeFactory dbTypeFactory = typeFactory.getDBTypeFactory();
DBTermType dbStringType = dbTypeFactory.getDBStringType();
DBTermType dbIntType = dbTypeFactory.getDBLargeIntegerType();
DBTermType dbDateTimestamp = dbTypeFactory.getDBDateTimestampType();
DBTermType abstractRootDBType = dbTypeFactory.getAbstractRootDBType();
DBTermType dbBooleanType = dbTypeFactory.getDBBooleanType();
ImmutableTable.Builder<String, Integer, DBFunctionSymbol> builder = ImmutableTable.builder();
// TODO: provide the base input types
DBFunctionSymbol upperFunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(UPPER_STR, 1, dbStringType,
false, abstractRootDBType);
builder.put(UPPER_STR, 1, upperFunctionSymbol);
builder.put(UCASE_STR, 1, upperFunctionSymbol);
DBFunctionSymbol lowerFunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(LOWER_STR, 1, dbStringType,
false, abstractRootDBType);
builder.put(LOWER_STR, 1, lowerFunctionSymbol);
builder.put(LCASE_STR, 1, lowerFunctionSymbol);
DBFunctionSymbol replace3FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(REPLACE_STR, 3, dbStringType,
false, abstractRootDBType);
builder.put(REPLACE_STR, 3, replace3FunctionSymbol);
DBFunctionSymbol regexpReplace3FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(REGEXP_REPLACE_STR, 3, dbStringType,
false, abstractRootDBType);
builder.put(REGEXP_REPLACE_STR, 3, regexpReplace3FunctionSymbol);
DBFunctionSymbol regexpReplace4FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(REGEXP_REPLACE_STR, 4, dbStringType,
false, abstractRootDBType);
builder.put(REGEXP_REPLACE_STR, 4, regexpReplace4FunctionSymbol);
DBFunctionSymbol subString2FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(SUBSTRING_STR, 2, dbStringType,
false, abstractRootDBType);
builder.put(SUBSTRING_STR, 2, subString2FunctionSymbol);
DBFunctionSymbol subStr2FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(SUBSTR_STR, 2, dbStringType,
false, abstractRootDBType);
builder.put(SUBSTR_STR, 2, subStr2FunctionSymbol);
DBFunctionSymbol subString3FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(SUBSTRING_STR, 3, dbStringType,
false, abstractRootDBType);
builder.put(SUBSTRING_STR, 3, subString3FunctionSymbol);
DBFunctionSymbol subStr3FunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(SUBSTR_STR, 3, dbStringType,
false, abstractRootDBType);
builder.put(SUBSTR_STR, 3, subStr3FunctionSymbol);
DBFunctionSymbol rightFunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(RIGHT_STR, 2, dbStringType,
false, abstractRootDBType);
builder.put(RIGHT_STR, 2, rightFunctionSymbol);
// TODO: check precise output type
DBFunctionSymbol strlenFunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(CHAR_LENGTH_STR, 1, dbIntType,
false, abstractRootDBType);
builder.put(CHAR_LENGTH_STR, 1, strlenFunctionSymbol);
//TODO: move away this synonym as it is non-standard
DBFunctionSymbol lengthFunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(LENGTH_STR, 1, dbIntType,
false, abstractRootDBType);
builder.put(LENGTH_STR, 1, lengthFunctionSymbol);
DBFunctionSymbol nowFunctionSymbol = new DefaultSQLSimpleTypedDBFunctionSymbol(CURRENT_TIMESTAMP_STR, 0,
dbDateTimestamp, true, abstractRootDBType);
builder.put(CURRENT_TIMESTAMP_STR, 0, nowFunctionSymbol);
// Common for many dialects
DBBooleanFunctionSymbol regexpLike2 = new DefaultSQLSimpleDBBooleanFunctionSymbol(REGEXP_LIKE_STR, 2, dbBooleanType,
abstractRootDBType);
builder.put(REGEXP_LIKE_STR, 2, regexpLike2);
DBBooleanFunctionSymbol regexpLike3 = new RegexpLike3FunctionSymbol(dbBooleanType, abstractRootDBType);
builder.put(REGEXP_LIKE_STR, 3, regexpLike3);
DBFunctionSymbol nullIfFunctionSymbol = new NullIfDBFunctionSymbolImpl(abstractRootDBType);
builder.put(NULLIF_STR, 2, nullIfFunctionSymbol);
return builder.build();
}
@Override
public DBConcatFunctionSymbol getNullRejectingDBConcat(int arity) {
if (arity < 2)
throw new IllegalArgumentException("Arity of CONCAT must be >= 2");
return nullRejectingConcatMap
.computeIfAbsent(arity, a -> createNullRejectingDBConcat(arity));
}
@Override
public DBConcatFunctionSymbol getDBConcatOperator(int arity) {
if (arity < 2)
throw new IllegalArgumentException("Arity of CONCAT must be >= 2");
return concatOperatorMap
.computeIfAbsent(arity, a -> createDBConcatOperator(arity));
}
protected abstract DBConcatFunctionSymbol createNullRejectingDBConcat(int arity);
protected abstract DBConcatFunctionSymbol createDBConcatOperator(int arity);
@Override
protected DBFunctionSymbol createRegularUntypedFunctionSymbol(String nameInDialect, int arity) {
// TODO: avoid if-then-else
if (isAnd(nameInDialect))
return createDBAnd(arity);
else if (isOr(nameInDialect))
return createDBOr(arity);
else if (isConcat(nameInDialect))
return createRegularDBConcat(arity);
// TODO: allow its recognition in the mapping. Challenging for detecting that NULLs are fitered out.
// else if (isCoalesce(nameInDialect))
// return getDBCoalesce(arity);
return new DefaultUntypedDBFunctionSymbol(nameInDialect, arity, dbTypeFactory.getAbstractRootDBType());
}
@Override
protected DBBooleanFunctionSymbol createRegularBooleanFunctionSymbol(String nameInDialect, int arity) {
return new DefaultSQLSimpleDBBooleanFunctionSymbol(nameInDialect, arity, dbBooleanType, abstractRootDBType);
}
protected boolean isConcat(String nameInDialect) {
return nameInDialect.equals(CONCAT_STR);
}
protected boolean isAnd(String nameInDialect) {
return nameInDialect.equals(AND_STR);
}
protected boolean isOr(String nameInDialect) {
return nameInDialect.equals(OR_STR);
}
protected boolean isCoalesce(String nameInDialect) {
return nameInDialect.equals(COALESCE_STR);
}
/**
* CONCAT regular function symbol, not an operator (like || or +)
*/
protected abstract DBConcatFunctionSymbol createRegularDBConcat(int arity);
protected DBBooleanFunctionSymbol createDBAnd(int arity) {
return new DefaultDBAndFunctionSymbol(AND_STR, arity, dbBooleanType);
}
protected DBBooleanFunctionSymbol createDBOr(int arity) {
return new DefaultDBOrFunctionSymbol(OR_STR, arity, dbBooleanType);
}
@Override
protected DBNotFunctionSymbol createDBNotFunctionSymbol(DBTermType dbBooleanType) {
return new DefaultDBNotFunctionSymbol(NOT_STR, dbBooleanType);
}
protected DBFunctionSymbol createDBIfThenElse(DBTermType dbBooleanType, DBTermType abstractRootDBType) {
return new DefaultSQLIfThenElseFunctionSymbol(dbBooleanType, abstractRootDBType);
}
protected DBBooleanFunctionSymbol createIsStringEmpty(DBTermType dbBooleanType, DBTermType abstractRootDBType) {
return new DefaultSQLIsStringEmptyFunctionSymbol(dbBooleanType, abstractRootDBType);
}
protected DBIsNullOrNotFunctionSymbol createDBIsNull(DBTermType dbBooleanType, DBTermType rootDBTermType) {
return new DefaultSQLDBIsNullOrNotFunctionSymbol(true, dbBooleanType, rootDBTermType);
}
protected DBIsNullOrNotFunctionSymbol createDBIsNotNull(DBTermType dbBooleanType, DBTermType rootDBTermType) {
return new DefaultSQLDBIsNullOrNotFunctionSymbol(false, dbBooleanType, rootDBTermType);
}
protected DBIsTrueFunctionSymbol createDBIsTrue(DBTermType dbBooleanType) {
return new DefaultDBIsTrueFunctionSymbol(dbBooleanType);
}
@Override
protected DBTypeConversionFunctionSymbol createSimpleCastFunctionSymbol(DBTermType targetType) {
return new DefaultSimpleDBCastFunctionSymbol(dbTypeFactory.getAbstractRootDBType(), targetType,
Serializers.getCastSerializer(targetType));
}
@Override
protected DBTypeConversionFunctionSymbol createSimpleCastFunctionSymbol(DBTermType inputType, DBTermType targetType) {
if (targetType.equals(dbBooleanType))
return new DefaultSimpleDBBooleanCastFunctionSymbol(inputType, targetType,
Serializers.getCastSerializer(targetType));
DBTermType.Category inputCategory = inputType.getCategory();
if (inputCategory.equals(targetType.getCategory())) {
switch (inputCategory) {
case INTEGER:
return createIntegerToIntegerCastFunctionSymbol(inputType, targetType);
case DECIMAL:
return createDecimalToDecimalCastFunctionSymbol(inputType, targetType);
case FLOAT_DOUBLE:
return createFloatDoubleToFloatDoubleCastFunctionSymbol(inputType, targetType);
case STRING:
return createStringToStringCastFunctionSymbol(inputType, targetType);
case DATETIME:
return createDatetimeToDatetimeCastFunctionSymbol(inputType, targetType);
default:
return new DefaultSimpleDBCastFunctionSymbol(inputType, targetType,
Serializers.getCastSerializer(targetType));
}
}
if (targetType.equals(dbStringType)) {
switch (inputCategory) {
case INTEGER:
return createIntegerToStringCastFunctionSymbol(inputType);
case DECIMAL:
return createDecimalToStringCastFunctionSymbol(inputType);
case FLOAT_DOUBLE:
return createFloatDoubleToStringCastFunctionSymbol(inputType);
default:
return createDefaultCastToStringFunctionSymbol(inputType);
}
}
return new DefaultSimpleDBCastFunctionSymbol(inputType, targetType,
Serializers.getCastSerializer(targetType));
}
/**
* Implicit
*/
protected DBTypeConversionFunctionSymbol createIntegerToIntegerCastFunctionSymbol(DBTermType inputType, DBTermType targetType) {
return new DefaultImplicitDBCastFunctionSymbol(inputType, targetType);
}
/**
* TODO: make it implicit by default?
*/
protected DBTypeConversionFunctionSymbol createDecimalToDecimalCastFunctionSymbol(DBTermType inputType, DBTermType targetType) {
return new DefaultSimpleDBCastFunctionSymbol(inputType, targetType,
Serializers.getCastSerializer(targetType));
}
/**
* TODO: make it implicit by default?
*/
protected DBTypeConversionFunctionSymbol createFloatDoubleToFloatDoubleCastFunctionSymbol(DBTermType inputType, DBTermType targetType) {
return new DefaultSimpleDBCastFunctionSymbol(inputType, targetType,
Serializers.getCastSerializer(targetType));
}
protected DBTypeConversionFunctionSymbol createStringToStringCastFunctionSymbol(DBTermType inputType,
DBTermType targetType) {
return new DefaultImplicitDBCastFunctionSymbol(inputType, targetType);
}
/**
* By default explicit
*/
protected DBTypeConversionFunctionSymbol createDatetimeToDatetimeCastFunctionSymbol(DBTermType inputType,
DBTermType targetType) {
return new DefaultSimpleDBCastFunctionSymbol(inputType, targetType, Serializers.getCastSerializer(targetType));
}
/**
* The returned function symbol can apply additional optimizations
*/
protected DBTypeConversionFunctionSymbol createIntegerToStringCastFunctionSymbol(DBTermType inputType) {
return new DefaultCastIntegerToStringFunctionSymbol(inputType, dbStringType,
Serializers.getCastSerializer(dbStringType));
}
/**
* Hook
*/
protected DBTypeConversionFunctionSymbol createDecimalToStringCastFunctionSymbol(DBTermType inputType) {
return createDefaultCastToStringFunctionSymbol(inputType);
}
/**
* Hook
*/
protected DBTypeConversionFunctionSymbol createFloatDoubleToStringCastFunctionSymbol(DBTermType inputType) {
return createDefaultCastToStringFunctionSymbol(inputType);
}
protected DBTypeConversionFunctionSymbol createDefaultCastToStringFunctionSymbol(DBTermType inputType) {
return new DefaultSimpleDBCastFunctionSymbol(inputType, dbStringType,
Serializers.getCastSerializer(dbStringType));
}
@Override
protected DBFunctionSymbol createDBCase(int arity, boolean doOrderingMatter) {
return new DefaultDBCaseFunctionSymbol(arity, dbBooleanType, abstractRootDBType, doOrderingMatter);
}
@Override
protected DBBooleanFunctionSymbol createDBBooleanCase(int arity, boolean doOrderingMatter) {
return new DBBooleanCaseFunctionSymbolImpl(arity, dbBooleanType, abstractRootDBType, doOrderingMatter);
}
@Override
protected DBFunctionSymbol createCoalesceFunctionSymbol(int arity) {
return new DefaultDBCoalesceFunctionSymbol(COALESCE_STR, arity, abstractRootDBType,
Serializers.getRegularSerializer(COALESCE_STR));
}
@Override
protected DBStrictEqFunctionSymbol createDBStrictEquality(int arity) {
return new DefaultDBStrictEqFunctionSymbol(arity, abstractRootType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createDBStrictNEquality(int arity) {
return new DefaultDBStrictNEqFunctionSymbol(arity, abstractRootType, dbBooleanType);
}
@Override
protected DBFunctionSymbol createR2RMLIRISafeEncode() {
return new DefaultSQLR2RMLSafeIRIEncodeFunctionSymbol(dbStringType);
}
@Override
protected DBFunctionSymbol createAbsFunctionSymbol(DBTermType dbTermType) {
return new DefaultSQLSimpleMultitypedDBFunctionSymbolImpl(ABS_STR, 1, dbTermType, false);
}
@Override
protected DBFunctionSymbol createCeilFunctionSymbol(DBTermType dbTermType) {
return new DefaultSQLSimpleMultitypedDBFunctionSymbolImpl(CEIL_STR, 1, dbTermType, false);
}
@Override
protected DBFunctionSymbol createFloorFunctionSymbol(DBTermType dbTermType) {
return new DefaultSQLSimpleMultitypedDBFunctionSymbolImpl(FLOOR_STR, 1, dbTermType, false);
}
@Override
protected DBFunctionSymbol createRoundFunctionSymbol(DBTermType dbTermType) {
return new DefaultSQLSimpleMultitypedDBFunctionSymbolImpl(ROUND_STR, 1, dbTermType, false);
}
@Override
protected String serializeYearFromDatetime(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return serializeYear(terms, termConverter, termFactory);
}
@Override
protected String serializeYearFromDate(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return serializeYear(terms, termConverter, termFactory);
}
/**
* By default, we assume that this function works both for TIMESTAMP and DATE
*/
protected String serializeYear(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return String.format("EXTRACT(YEAR FROM %s)", termConverter.apply(terms.get(0)));
}
@Override
protected String serializeMonthFromDatetime(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return serializeMonth(terms, termConverter, termFactory);
}
@Override
protected String serializeMonthFromDate(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return serializeMonth(terms, termConverter, termFactory);
}
/**
* By default, we assume that this function works both for TIMESTAMP and DATE
*/
protected String serializeMonth(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return String.format("EXTRACT(MONTH FROM %s)", termConverter.apply(terms.get(0)));
}
@Override
protected String serializeDayFromDatetime(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return serializeDay(terms, termConverter, termFactory);
}
@Override
protected String serializeDayFromDate(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return serializeDay(terms, termConverter, termFactory);
}
/**
* By default, we assume that this function works both for TIMESTAMP and DATE
*/
protected String serializeDay(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return String.format("EXTRACT(DAY FROM %s)", termConverter.apply(terms.get(0)));
}
@Override
protected String serializeHours(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return String.format("EXTRACT(HOUR FROM %s)", termConverter.apply(terms.get(0)));
}
@Override
protected String serializeMinutes(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return String.format("EXTRACT(MINUTE FROM %s)", termConverter.apply(terms.get(0)));
}
/**
* TODO: is it returning an integer or a decimal?
*/
@Override
protected String serializeSeconds(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory) {
return String.format("EXTRACT(SECOND FROM %s)", termConverter.apply(terms.get(0)));
}
@Override
protected DBTypeConversionFunctionSymbol createDateTimeNormFunctionSymbol(DBTermType dbDateTimestampType) {
return new DefaultSQLTimestampISONormFunctionSymbol(
dbDateTimestampType,
dbStringType,
this::serializeDateTimeNorm);
}
protected abstract String serializeDateTimeNorm(ImmutableList<? extends ImmutableTerm> terms,
Function<ImmutableTerm, String> termConverter, TermFactory termFactory);
@Override
protected DBTypeConversionFunctionSymbol createBooleanNormFunctionSymbol(DBTermType booleanType) {
return new DefaultBooleanNormFunctionSymbol(booleanType, dbStringType);
}
@Override
protected DBTypeConversionFunctionSymbol createDateTimeDenormFunctionSymbol(DBTermType timestampType) {
return new DefaultSQLTimestampISODenormFunctionSymbol(timestampType, dbStringType);
}
@Override
protected DBTypeConversionFunctionSymbol createBooleanDenormFunctionSymbol() {
return new DefaultBooleanDenormFunctionSymbol(dbBooleanType, dbStringType);
}
@Override
protected DBMathBinaryOperator createMultiplyOperator(DBTermType dbNumericType) {
return new DefaultTypedDBMathBinaryOperator(MULTIPLY_STR, dbNumericType);
}
@Override
protected DBMathBinaryOperator createDivideOperator(DBTermType dbNumericType) {
return new DefaultTypedDBMathBinaryOperator(DIVIDE_STR, dbNumericType);
}
@Override
protected DBMathBinaryOperator createAddOperator(DBTermType dbNumericType) {
return new DefaultTypedDBMathBinaryOperator(ADD_STR, dbNumericType);
}
@Override
protected DBMathBinaryOperator createSubstractOperator(DBTermType dbNumericType) {
return new DefaultTypedDBMathBinaryOperator(SUBSTRACT_STR, dbNumericType);
}
@Override
protected DBMathBinaryOperator createUntypedMultiplyOperator() {
return new DefaultUntypedDBMathBinaryOperator(MULTIPLY_STR, abstractRootDBType);
}
@Override
protected DBMathBinaryOperator createUntypedDivideOperator() {
return new DefaultUntypedDBMathBinaryOperator(DIVIDE_STR, abstractRootDBType);
}
@Override
protected DBMathBinaryOperator createUntypedAddOperator() {
return new DefaultUntypedDBMathBinaryOperator(ADD_STR, abstractRootDBType);
}
@Override
protected DBMathBinaryOperator createUntypedSubstractOperator() {
return new DefaultUntypedDBMathBinaryOperator(SUBSTRACT_STR, abstractRootDBType);
}
@Override
protected DBBooleanFunctionSymbol createNonStrictNumericEquality() {
return new DefaultDBNonStrictNumericEqOperator(abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createNonStrictStringEquality() {
return new DefaultDBNonStrictStringEqOperator(abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createNonStrictDatetimeEquality() {
return new DefaultDBNonStrictDatetimeEqOperator(abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createNonStrictDateEquality() {
return new DefaultDBNonStrictDateEqOperator(abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createNonStrictDefaultEquality() {
return new DefaultDBNonStrictDefaultEqOperator(abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createNumericInequality(InequalityLabel inequalityLabel) {
return new DefaultDBNumericInequalityOperator(inequalityLabel, abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createBooleanInequality(InequalityLabel inequalityLabel) {
return new DefaultDBBooleanInequalityOperator(inequalityLabel, abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createStringInequality(InequalityLabel inequalityLabel) {
return new DefaultDBStringInequalityOperator(inequalityLabel, abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createDatetimeInequality(InequalityLabel inequalityLabel) {
return new DefaultDBDatetimeInequalityOperator(inequalityLabel, abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createDateInequality(InequalityLabel inequalityLabel) {
return new DefaultDBDateInequalityOperator(inequalityLabel, abstractRootDBType, dbBooleanType);
}
@Override
protected DBBooleanFunctionSymbol createDefaultInequality(InequalityLabel inequalityLabel) {
return new DefaultDBDefaultInequalityOperator(inequalityLabel, abstractRootDBType, dbBooleanType);
}
@Override
public DBFunctionSymbol getDBIfThenElse() {
return ifThenElse;
}
@Override
public DBFunctionSymbol getDBUpper() {
return getRegularDBFunctionSymbol(UPPER_STR, 1);
}
@Override
public DBFunctionSymbol getDBLower() {
return getRegularDBFunctionSymbol(LOWER_STR, 1);
}
@Override
public DBFunctionSymbol getDBReplace() {
return getRegularDBFunctionSymbol(REPLACE_STR, 3);
}
@Override
public DBFunctionSymbol getDBRegexpReplace3() {
return getRegularDBFunctionSymbol(REGEXP_REPLACE_STR, 3);
}
@Override
public DBFunctionSymbol getDBRegexpReplace4() {
return getRegularDBFunctionSymbol(REGEXP_REPLACE_STR, 4);
}
@Override
public DBFunctionSymbol getDBSubString2() {
return getRegularDBFunctionSymbol(SUBSTRING_STR, 2);
}
@Override
public DBFunctionSymbol getDBSubString3() {
return getRegularDBFunctionSymbol(SUBSTRING_STR, 3);
}
@Override
public DBFunctionSymbol getDBRight() {
return getRegularDBFunctionSymbol(RIGHT_STR, 2);
}
@Override
public DBFunctionSymbol getDBCharLength() {
return getRegularDBFunctionSymbol(CHAR_LENGTH_STR, 1);
}
@Override
public DBAndFunctionSymbol getDBAnd(int arity) {
if (arity < 2)
throw new IllegalArgumentException("Arity of AND must be >= 2");
return (DBAndFunctionSymbol) getRegularDBFunctionSymbol(AND_STR, arity);
}
@Override
public DBOrFunctionSymbol getDBOr(int arity) {
if (arity < 2)
throw new IllegalArgumentException("Arity of OR must be >= 2");
return (DBOrFunctionSymbol) getRegularDBFunctionSymbol(OR_STR, arity);
}
@Override
public DBIsNullOrNotFunctionSymbol getDBIsNull() {
return isNull;
}
@Override
public DBIsNullOrNotFunctionSymbol getDBIsNotNull() {
return isNotNull;
}
@Override
public DBBooleanFunctionSymbol getDBIsStringEmpty() {
return isStringEmpty;
}
@Override
public DBIsTrueFunctionSymbol getIsTrue() {
return isTrue;
}
@Override
public NonDeterministicDBFunctionSymbol getDBRand(UUID uuid) {
return new DefaultNonDeterministicNullaryFunctionSymbol(getRandNameInDialect(), uuid, dbDoubleType);
}
@Override
public NonDeterministicDBFunctionSymbol getDBUUID(UUID uuid) {
return new DefaultNonDeterministicNullaryFunctionSymbol(getUUIDNameInDialect(), uuid, dbStringType);
}
@Override
public DBFunctionSymbol getDBNow() {
return getRegularDBFunctionSymbol(CURRENT_TIMESTAMP_STR, 0);
}
@Override
public DBBooleanFunctionSymbol getDBRegexpMatches2() {
return (DBBooleanFunctionSymbol) getRegularDBFunctionSymbol(REGEXP_LIKE_STR, 2);
}
@Override
public DBBooleanFunctionSymbol getDBRegexpMatches3() {
return (DBBooleanFunctionSymbol) getRegularDBFunctionSymbol(REGEXP_LIKE_STR, 3);
}
/**
* Can be overridden.
*
* Not an official SQL function
*/
protected String getRandNameInDialect() {
return RAND_STR;
}
protected abstract String getUUIDNameInDialect();
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE506_Embedded_Malicious_Code__base64_encoded_payload_05.java
Label Definition File: CWE506_Embedded_Malicious_Code.label.xml
Template File: point-flaw-05.tmpl.java
*/
/*
* @description
* CWE: 506 Embedded Malicious Code
* Sinks: base64_encoded_payload
* GoodSink: Use a plaintext command
* BadSink : Use a base64 encoded payload in an attempt to hide the command
* Flow Variant: 05 Control flow: if(privateTrue) and if(privateFalse)
*
* */
import org.apache.commons.codec.binary.Base64;
import java.io.IOException;
import java.util.logging.Level;
public class CWE506_Embedded_Malicious_Code__base64_encoded_payload_05 extends AbstractTestCase
{
/* The two variables below are not defined as "final", but are never
* assigned any other value, so a tool should be able to identify that
* reads of these will always return their initialized values.
*/
private boolean privateTrue = true;
private boolean privateFalse = false;
public void bad() throws Throwable
{
if (privateTrue)
{
/* FLAW: encoded "calc.exe" */
String encodedPayload = "Y2FsYy5leGU=";
try
{
Runtime.getRuntime().exec(new String(Base64.decodeBase64(encodedPayload), "UTF-8"));
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error executing command", exceptIO);
}
}
}
/* good1() changes privateTrue to privateFalse */
private void good1() throws Throwable
{
if (privateFalse)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
IO.writeLine("Benign, fixed string");
}
else
{
/* FIX: plaintext command */
String decodedPayload = "calc.exe";
try
{
Runtime.getRuntime().exec(decodedPayload);
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error executing command", exceptIO);
}
}
}
/* good2() reverses the bodies in the if statement */
private void good2() throws Throwable
{
if (privateTrue)
{
/* FIX: plaintext command */
String decodedPayload = "calc.exe";
try
{
Runtime.getRuntime().exec(decodedPayload);
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error executing command", exceptIO);
}
}
}
public void good() throws Throwable
{
good1();
good2();
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
/*
* Copyright 2010 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.service.data.impl;
import java.math.BigInteger;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentData;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentData_;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentStatusContainer;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentStatusContainer_;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommittee;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommittee_;
import com.hack23.cia.model.internal.application.data.document.impl.RiksdagenDocumentPersonSummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.document.impl.RiksdagenDocumentPersonSummaryEmbeddedId_;
import com.hack23.cia.model.internal.application.data.document.impl.ViewRiksdagenPoliticianDocumentDailySummary;
import com.hack23.cia.model.internal.application.data.document.impl.ViewRiksdagenPoliticianDocumentDailySummary_;
import com.hack23.cia.model.internal.application.data.ministry.impl.ViewRiksdagenMinistry;
import com.hack23.cia.model.internal.application.data.ministry.impl.ViewRiksdagenMinistry_;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenParty;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenPartyBallotSupportAnnualSummary;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenPartyCoalationAgainstAnnualSummary;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenPartySummary;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenPartySummary_;
import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenParty_;
import com.hack23.cia.model.internal.application.data.politician.impl.ViewRiksdagenPolitician;
import com.hack23.cia.model.internal.application.data.politician.impl.ViewRiksdagenPolitician_;
import com.hack23.cia.service.data.api.DataViewer;
/**
* The Class DataViewerITest.
*/
public final class DataViewerITest extends
AbstractServiceDataFunctionalIntegrationTest {
/** The Constant EXPECT_VALUE_IN_DATABASE. */
private static final String EXPECT_VALUE_IN_DATABASE = "Expect value in database";
/** The Constant SHOULD_ALWAYS_BE_349_IN_PARLIAMENT. */
private static final String SHOULD_ALWAYS_BE_349_IN_PARLIAMENT = "Should always be 349 in parliament";
/** The Constant EXPECT_SAME_OBJECT_LOADED. */
private static final String EXPECT_SAME_OBJECT_LOADED = "Expect same object loaded";
/** The data viewer. */
@Autowired
private DataViewer dataViewer;
/**
* View riksdagen committee.
*
* @throws Exception
* the exception
*/
@Test
public void viewRiksdagenCommittee() throws Exception {
final List<ViewRiksdagenCommittee> committees = dataViewer
.getAll(ViewRiksdagenCommittee.class);
assertNotNull(EXPECT_VALUE_IN_DATABASE,committees);
if (committees.size() > 0) {
final ViewRiksdagenCommittee viewRiksdagenCommittee = committees
.get(0);
final ViewRiksdagenCommittee viewRiksdagenCommitteeLoaded = dataViewer
.load(ViewRiksdagenCommittee.class,
viewRiksdagenCommittee.getEmbeddedId());
assertNotNull(EXPECT_VALUE_IN_DATABASE,viewRiksdagenCommitteeLoaded);
final ViewRiksdagenCommittee viewRiksdagenCommitteeFound = dataViewer
.findFirstByProperty(ViewRiksdagenCommittee.class,
ViewRiksdagenCommittee_.embeddedId,
viewRiksdagenCommitteeLoaded.getEmbeddedId());
assertEquals(EXPECT_SAME_OBJECT_LOADED,viewRiksdagenCommitteeLoaded,
viewRiksdagenCommitteeFound);
}
}
/**
* View riksdagen party ballot support annual summary.
*
* @throws Exception the exception
*/
@Test
public void viewRiksdagenPartyBallotSupportAnnualSummary() throws Exception {
final List<ViewRiksdagenPartyBallotSupportAnnualSummary> list = dataViewer
.getAll(ViewRiksdagenPartyBallotSupportAnnualSummary.class);
assertNotNull(EXPECT_VALUE_IN_DATABASE,list);
}
/**
* View riksdagen party coalation against annual summary.
*
* @throws Exception the exception
*/
@Test
public void viewRiksdagenPartyCoalationAgainstAnnualSummary() throws Exception {
final List<ViewRiksdagenPartyCoalationAgainstAnnualSummary> list = dataViewer
.getAll(ViewRiksdagenPartyCoalationAgainstAnnualSummary.class);
assertNotNull(EXPECT_VALUE_IN_DATABASE,list);
}
/**
* View riksdagen ministry.
*
* @throws Exception
* the exception
*/
@Test
public void viewRiksdagenMinistry() throws Exception {
final List<ViewRiksdagenMinistry> ministries = dataViewer
.getAll(ViewRiksdagenMinistry.class);
assertNotNull(EXPECT_VALUE_IN_DATABASE,ministries);
if (ministries.size() > 0) {
final ViewRiksdagenMinistry viewRiksdagenMinistry = ministries
.get(0);
final ViewRiksdagenMinistry viewRiksdagenMinistryLoaded = dataViewer
.load(ViewRiksdagenMinistry.class,
viewRiksdagenMinistry.getNameId());
assertNotNull(EXPECT_VALUE_IN_DATABASE,viewRiksdagenMinistryLoaded);
final ViewRiksdagenMinistry viewRiksdagenMinistryFound = dataViewer
.findFirstByProperty(ViewRiksdagenMinistry.class,
ViewRiksdagenMinistry_.nameId,
viewRiksdagenMinistryLoaded.getNameId());
assertEquals(EXPECT_SAME_OBJECT_LOADED,viewRiksdagenMinistryLoaded,
viewRiksdagenMinistryFound);
}
}
/**
* View riksdagen party.
*
* @throws Exception
* the exception
*/
@Test
public void viewRiksdagenParty() throws Exception {
final List<ViewRiksdagenParty> parties = dataViewer
.getAll(ViewRiksdagenParty.class);
assertNotNull(EXPECT_VALUE_IN_DATABASE,parties);
if (parties.size() > 0) {
final ViewRiksdagenParty viewRiksdagenParty = parties.get(0);
final ViewRiksdagenParty viewRiksdagenPartyLoaded = dataViewer
.load(ViewRiksdagenParty.class,
viewRiksdagenParty.getPartyId());
assertNotNull(EXPECT_VALUE_IN_DATABASE,viewRiksdagenPartyLoaded);
final ViewRiksdagenParty viewRiksdagenPartyFound = dataViewer
.findFirstByProperty(ViewRiksdagenParty.class,
ViewRiksdagenParty_.partyName,
viewRiksdagenPartyLoaded.getPartyName());
assertEquals(EXPECT_SAME_OBJECT_LOADED,viewRiksdagenPartyLoaded, viewRiksdagenPartyFound);
}
}
/**
* View riksdagen party summary.
*
* @throws Exception
* the exception
*/
@Test
public void viewRiksdagenPartySummary() throws Exception {
final List<ViewRiksdagenPartySummary> committees = dataViewer
.getAll(ViewRiksdagenPartySummary.class);
assertNotNull(EXPECT_VALUE_IN_DATABASE,committees);
if (committees.size() > 0) {
final ViewRiksdagenPartySummary viewRiksdagenPartySummary = committees
.get(4);
final ViewRiksdagenPartySummary viewRiksdagenPartySummaryLoaded = dataViewer
.load(ViewRiksdagenPartySummary.class,
viewRiksdagenPartySummary.getParty());
assertNotNull(EXPECT_VALUE_IN_DATABASE,viewRiksdagenPartySummaryLoaded);
final ViewRiksdagenPartySummary viewRiksdagenPartySummaryFound = dataViewer
.findFirstByProperty(ViewRiksdagenPartySummary.class,
ViewRiksdagenPartySummary_.party,
viewRiksdagenPartySummaryLoaded.getParty());
assertEquals(EXPECT_SAME_OBJECT_LOADED,viewRiksdagenPartySummaryLoaded,
viewRiksdagenPartySummaryFound);
}
long parliamentSum = 0;
long euSum = 0;
long governmentSum = 0;
for (final ViewRiksdagenPartySummary viewRiksdagenPartySummary : committees) {
if (viewRiksdagenPartySummary != null) {
parliamentSum = parliamentSum
+ viewRiksdagenPartySummary.getTotalActiveParliament();
euSum = euSum + viewRiksdagenPartySummary.getTotalActiveEu();
governmentSum = governmentSum
+ viewRiksdagenPartySummary.getTotalActiveGovernment();
}
}
final List<ViewRiksdagenPolitician> activeWithNoParty = dataViewer.findOrderedListByProperty(ViewRiksdagenPolitician.class,ViewRiksdagenPolitician_.firstAssignmentDate, new Object[] {true,null},ViewRiksdagenPolitician_.activeParliament,ViewRiksdagenPolitician_.party);
assertEquals(SHOULD_ALWAYS_BE_349_IN_PARLIAMENT, 349, parliamentSum + activeWithNoParty.size());
// assertEquals(
// "Should always be 20 in eu, but riksdagen data contains only 15",
// 15, euSum);
// assertEquals("Should always be 23 in current government", 23,
// governmentSum);
}
/**
* View riksdagen politician.
*
* @throws Exception
* the exception
*/
@Test
public void viewRiksdagenPolitician() throws Exception {
final List<ViewRiksdagenPolitician> politicians = dataViewer
.getAll(ViewRiksdagenPolitician.class);
assertNotNull(EXPECT_VALUE_IN_DATABASE,politicians);
if (politicians.size() > 0) {
final ViewRiksdagenPolitician viewRiksdagenPolitician = politicians
.get(4);
final ViewRiksdagenPolitician viewRiksdagenPoliticianLoaded = dataViewer
.load(ViewRiksdagenPolitician.class,
viewRiksdagenPolitician.getPersonId());
assertNotNull(EXPECT_VALUE_IN_DATABASE,viewRiksdagenPoliticianLoaded);
final ViewRiksdagenPolitician viewRiksdagenPoliticianFound = dataViewer
.findFirstByProperty(ViewRiksdagenPolitician.class,
ViewRiksdagenPolitician_.personId,
viewRiksdagenPoliticianLoaded.getPersonId());
assertEquals(EXPECT_SAME_OBJECT_LOADED,viewRiksdagenPoliticianLoaded,
viewRiksdagenPoliticianFound);
assertEquals(SHOULD_ALWAYS_BE_349_IN_PARLIAMENT,349,dataViewer
.findListByProperty(ViewRiksdagenPolitician.class,
ViewRiksdagenPolitician_.activeParliament,
true).size());
}
}
/**
* Find by query property test.
*/
@Test
public void findByQueryPropertyTest() {
final DocumentStatusContainer findByQueryProperty = dataViewer.findByQueryProperty(DocumentStatusContainer.class, DocumentStatusContainer_.document,
DocumentData.class, DocumentData_.id, "H501NU6");
assertNotNull(findByQueryProperty);
}
/**
* Find by query property failure test.
*/
@Test
public void findByQueryPropertyFailureTest() {
final DocumentStatusContainer findByQueryProperty = dataViewer.findByQueryProperty(DocumentStatusContainer.class, DocumentStatusContainer_.document,
DocumentData.class, DocumentData_.id, "NONEXISTING");
assertNull(findByQueryProperty);
}
/**
* Find by query property non string failure test.
*/
@Test
public void findByQueryPropertyNonStringFailureTest() {
final DocumentStatusContainer findByQueryProperty = dataViewer.findByQueryProperty(DocumentStatusContainer.class, DocumentStatusContainer_.document,
DocumentData.class, DocumentData_.numberValue, BigInteger.valueOf(-1L));
assertNull(findByQueryProperty);
}
/**
* Find list by embedded property test.
*/
@Test
public void findListByEmbeddedPropertyTest() {
final List<ViewRiksdagenPoliticianDocumentDailySummary> findListByEmbeddedProperty = dataViewer.findListByEmbeddedProperty(ViewRiksdagenPoliticianDocumentDailySummary.class, ViewRiksdagenPoliticianDocumentDailySummary_.embeddedId, RiksdagenDocumentPersonSummaryEmbeddedId.class, RiksdagenDocumentPersonSummaryEmbeddedId_.documentType, "mot");
assertNotNull(findListByEmbeddedProperty);
assertFalse(findListByEmbeddedProperty.isEmpty());
}
/**
* Find ordered by property list by embedded property test.
*/
@Test
public void findOrderedByPropertyListByEmbeddedPropertyTest() {
final List<ViewRiksdagenPoliticianDocumentDailySummary> findListByEmbeddedProperty = dataViewer.findOrderedByPropertyListByEmbeddedProperty(ViewRiksdagenPoliticianDocumentDailySummary.class, ViewRiksdagenPoliticianDocumentDailySummary_.embeddedId, RiksdagenDocumentPersonSummaryEmbeddedId.class, RiksdagenDocumentPersonSummaryEmbeddedId_.documentType, "mot",ViewRiksdagenPoliticianDocumentDailySummary_.total);
assertNotNull(findListByEmbeddedProperty);
assertFalse(findListByEmbeddedProperty.isEmpty());
}
/**
* Find ordered list by embedded property test.
*/
@Test
public void findOrderedListByEmbeddedPropertyTest() {
final List<ViewRiksdagenPoliticianDocumentDailySummary> findListByEmbeddedProperty = dataViewer.findOrderedListByEmbeddedProperty(ViewRiksdagenPoliticianDocumentDailySummary.class, ViewRiksdagenPoliticianDocumentDailySummary_.embeddedId, RiksdagenDocumentPersonSummaryEmbeddedId.class, RiksdagenDocumentPersonSummaryEmbeddedId_.documentType, "mot",RiksdagenDocumentPersonSummaryEmbeddedId_.personId);
assertNotNull(findListByEmbeddedProperty);
assertFalse(findListByEmbeddedProperty.isEmpty());
}
/**
* Gets the page test.
*
* @return the page test
*/
@Test
public void getPageTest() {
final int resultPerPage = 10;
final List<ViewRiksdagenPolitician> pageOrderBy = dataViewer.getPage(ViewRiksdagenPolitician.class, 1, resultPerPage);
assertNotNull(pageOrderBy);
assertFalse(pageOrderBy.isEmpty());
assertEquals(resultPerPage,pageOrderBy.size());
}
/**
* Gets the page order by test.
*
* @return the page order by test
*/
@Test
public void getPageOrderByTest() {
final int resultPerPage = 10;
final List<ViewRiksdagenPolitician> pageOrderBy = dataViewer.getPageOrderBy(ViewRiksdagenPolitician.class, 1, resultPerPage, ViewRiksdagenPolitician_.bornYear);
assertNotNull(pageOrderBy);
assertFalse(pageOrderBy.isEmpty());
assertEquals(resultPerPage,pageOrderBy.size());
}
/**
* Gets the size test.
*
* @return the size test
*/
@Test
public void getSizeTest() {
assertNotNull(dataViewer.getSize(ViewRiksdagenPolitician.class));
}
}
|
package org.ovirt.engine.core.bll;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.common.action.SetVmTicketParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.GraphicsInfo;
import org.ovirt.engine.core.common.businessentities.GraphicsType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.console.ConsoleOptions;
import org.ovirt.engine.core.common.queries.ConfigureConsoleOptionsParams;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class ConfigureConsoleOptionsQueryTest {
@Mock
BackendInternal backend;
@Test
public void shouldFailtWhenNoId() {
ConsoleOptions options = new ConsoleOptions(GraphicsType.SPICE);
ConfigureConsoleOptionsQuery query =
new ConfigureConsoleOptionsQuery(new ConfigureConsoleOptionsParams(options, false));
assertFalse(query.validateInputs());
}
@Test
public void shouldFailtWhenNoGraphicsType() {
ConsoleOptions options = new ConsoleOptions();
ConfigureConsoleOptionsQuery query =
new ConfigureConsoleOptionsQuery(new ConfigureConsoleOptionsParams(options, false));
assertFalse(query.validateInputs());
}
@Test
public void testInputDataOk() {
ConfigureConsoleOptionsQuery query = spy(new ConfigureConsoleOptionsQuery(new ConfigureConsoleOptionsParams(getValidOptions(GraphicsType.SPICE), false)));
doReturn(mockVm(GraphicsType.SPICE)).when(query).getCachedVm();
assertTrue(query.validateInputs());
}
@Test
public void failOnStoppedVm() {
ConfigureConsoleOptionsParams params = new ConfigureConsoleOptionsParams(getValidOptions(GraphicsType.SPICE), false);
ConfigureConsoleOptionsQuery query = spy(new ConfigureConsoleOptionsQuery(params));
VM mockVm = mockVm(GraphicsType.SPICE);
mockVm.setStatus(VMStatus.Down);
doReturn(mockVm).when(query).getCachedVm();
query.validateInputs();
assertFalse(query.getQueryReturnValue().getSucceeded());
}
@Test
public void failGetSpiceOnVncVm() {
ConfigureConsoleOptionsParams params = new ConfigureConsoleOptionsParams(getValidOptions(GraphicsType.SPICE), false);
ConfigureConsoleOptionsQuery query = spy(new ConfigureConsoleOptionsQuery(params));
VM mockVm = mockVm(GraphicsType.VNC);
doReturn(mockVm).when(query).getCachedVm();
query.validateInputs();
assertFalse(query.getQueryReturnValue().getSucceeded());
}
private ConsoleOptions getValidOptions(GraphicsType graphicsType) {
ConsoleOptions options = new ConsoleOptions(graphicsType);
options.setVmId(Guid.Empty);
return options;
}
@Test
public void shouldCallSetTicket() {
ConfigureConsoleOptionsParams params = new ConfigureConsoleOptionsParams(getValidOptions(GraphicsType.VNC), true);
ConfigureConsoleOptionsQuery query = spy(new ConfigureConsoleOptionsQuery(params));
doReturn(mockVm(GraphicsType.VNC)).when(query).getCachedVm();
doReturn(null).when(query).getConfigValue(any(ConfigValues.class));
doReturn(true).when(query).getConfigValue(ConfigValues.RemapCtrlAltDelDefault);
VdcReturnValueBase result = new VdcReturnValueBase();
result.setSucceeded(true);
result.setActionReturnValue("nbusr123");
doReturn(result).when(backend).runInternalAction(eq(VdcActionType.SetVmTicket), any(SetVmTicketParameters.class));
doReturn(backend).when(query).getBackend();
query.getQueryReturnValue().setSucceeded(true);
query.executeQueryCommand();
verify(backend, times(1)).runInternalAction(eq(VdcActionType.SetVmTicket), any(SetVmTicketParameters.class));
}
@Test
public void failWhenCertEnforcedAndCANotFound() {
ConfigureConsoleOptionsParams params = new ConfigureConsoleOptionsParams(getValidOptions(GraphicsType.SPICE), false);
ConfigureConsoleOptionsQuery query = spy(new ConfigureConsoleOptionsQuery(params));
doReturn(mockVm(GraphicsType.SPICE)).when(query).getCachedVm();
mockSpiceRelatedConfig(query);
doReturn(true).when(query).getConfigValue(ConfigValues.EnableSpiceRootCertificateValidation);
doReturn(true).when(query).getConfigValue(ConfigValues.RemapCtrlAltDelDefault);
VdcQueryReturnValue caResult = new VdcQueryReturnValue();
caResult.setSucceeded(false);
doReturn(caResult).when(backend).runInternalQuery(eq(VdcQueryType.GetCACertificate), any(VdcQueryParametersBase.class));
doReturn(backend).when(query).getBackend();
query.getQueryReturnValue().setSucceeded(true);
query.executeQueryCommand();
assertFalse(query.getQueryReturnValue().getSucceeded());
}
@Test
public void passWhenCertNotEnforcedAndCANotFound() {
ConfigureConsoleOptionsParams params = new ConfigureConsoleOptionsParams(getValidOptions(GraphicsType.SPICE), false);
ConfigureConsoleOptionsQuery query = spy(new ConfigureConsoleOptionsQuery(params));
doReturn(mockVm(GraphicsType.SPICE)).when(query).getCachedVm();
mockSpiceRelatedConfig(query);
doReturn(false).when(query).getConfigValue(ConfigValues.EnableSpiceRootCertificateValidation);
doReturn(true).when(query).getConfigValue(ConfigValues.RemapCtrlAltDelDefault);
doReturn(null).when(backend).runInternalQuery(eq(VdcQueryType.GetCACertificate), any(VdcQueryParametersBase.class));
doReturn(backend).when(query).getBackend();
query.getQueryReturnValue().setSucceeded(true);
query.executeQueryCommand();
assertTrue(query.getQueryReturnValue().getSucceeded());
}
private void mockSpiceRelatedConfig(ConfigureConsoleOptionsQuery query) {
doReturn(null).when(query).getConfigValue(any(ConfigValues.class));
doReturn(false).when(query).getConfigValue(ConfigValues.SSLEnabled);
doReturn(false).when(query).getConfigValue(ConfigValues.EnableUSBAsDefault);
}
private VM mockVm(GraphicsType graphicsType) {
VM vm = new VM();
vm.setId(Guid.Empty);
vm.getGraphicsInfos().put(graphicsType, new GraphicsInfo().setIp("host").setPort(5901));
vm.setStatus(VMStatus.Up);
return vm;
}
}
|
package cn.demonk.test3;
import android.util.Log;
import java.math.BigInteger;
/**
* 大数进制转换
* Created by guosen.lgs@alibaba-inc.com on 6/20/18.
*/
public class MultiNumberation2 {
//符号集,最大可转换进制为表的大小
private final static char[] SYMBOLS_MAP = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
// '!', '#', '%', '&', '$', '*', '(', ')', '[', ']', '{', '}', '^', '~', '?', '@', '>',
// '<', '=' };
public static String radixConvert(BigInteger decimal, int deep) {
if (deep < 1 || deep > SYMBOLS_MAP.length || deep == 10) {
return "";
}
// 余数
BigInteger d = BigInteger.valueOf(deep);
BigInteger[] bigDivide = decimal.divideAndRemainder(d);
int remainder = bigDivide[1].intValue();
String result = "" + SYMBOLS_MAP[remainder];
// 商
BigInteger quotient = bigDivide[0];
if (quotient.compareTo(d) >= 0) {
result = radixConvert(quotient, deep) + result;
} else {
result = "" + SYMBOLS_MAP[quotient.intValue()] + result;
}
return result;
}
public static void test() {
int radix = 62;
String num = "1fffffffffffff";
BigInteger big = new BigInteger(num, 16);
String ret = radixConvert(big, radix);
Log.e("demonk", num + ">>" + ret);
}
}
|
package com.stackroute.datacollectorservice.model;
import org.springframework.stereotype.Component;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
@Component
public class DataCollectorModel {
public String getMetrics(String inputUrl){
String inline = "";
try {
URL url = new URL (inputUrl);
//Parse URL into HttpURLConnection in order to open the connection in order to get the JSON data
HttpURLConnection conn = (HttpURLConnection) url.openConnection ();
//Set the request to GET or POST as per the requirements
conn.setRequestMethod ("GET");
//Use the connect method to create the connection bridge
conn.connect();
//Get the response status of the Rest API
int responsecode = conn.getResponseCode ();
//Iterating condition to if response code is not 200 then throw a runtime exception
//else continue the actual process of getting the JSON data
if (responsecode != 200)
throw new RuntimeException ("HttpResponseCode: " + responsecode);
else {
//Scanner functionality will read the JSON data from the stream
Scanner sc = new Scanner (url.openStream ());
while (sc.hasNext ()) {
inline += "\n"+sc.nextLine ();
}
sc.close ();
}
conn.disconnect ();
}
//Disconnect the HttpURLConnection stream
catch (Exception e) {
e.printStackTrace ();
}
return inline;
}
}
|
package org.practice.arrays;
public class q334 {
/*
Time Complexity: O(N)
Space Complexity: O(1)
*/
class Solution {
public boolean increasingTriplet(int[] nums) {
int min = Integer.MAX_VALUE;
int secondMin = Integer.MAX_VALUE;
for (int num : nums) {
if (num <= min) {
min = num;
} else if (num <= secondMin) {
secondMin = num;
} else {
return true;
}
}
return false;
}
}
}
|
/**
* @author dex
*
*/
public class First_0109 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hi World!!!");
System.out.println("Command Line Program Imported to Eclipse!!");
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice.FreshJuiceSize.MEDIUM;
System.out.println("Size : " + juice.size);
}
}
class FreshJuice {
enum FreshJuiceSize { SMALL, MEDIUM, LARGE }
FreshJuiceSize size;
}
|
package masecla.reddit4j.objects.preferences;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import masecla.reddit4j.client.Reddit4J;
import masecla.reddit4j.objects.RedditObject;
import masecla.reddit4j.objects.preferences.enums.BadCommentAutocollapse;
import masecla.reddit4j.objects.preferences.enums.CountryCode;
import masecla.reddit4j.objects.preferences.enums.DefaultCommentSort;
import masecla.reddit4j.objects.preferences.enums.Language;
import masecla.reddit4j.objects.preferences.enums.MediaStyle;
import masecla.reddit4j.objects.preferences.enums.PrivateMessagePolicy;
public class RedditPreferences extends RedditObject {
private PrivateMessagePolicy accept_pms;
private boolean activity_relevant_ads;
private boolean allow_clicktracking;
private BadCommentAutocollapse bad_comment_autocollapse;
private boolean beta;
private boolean clickgadget;
private boolean collapse_left_bar;
private boolean collapse_read_messages;
private boolean compress;
private CountryCode country_code;
private DefaultCommentSort default_comment_sort;
private boolean design_beta;
private boolean domain_details;
private boolean email_chat_request;
private boolean email_comment_reply;
private boolean email_community_discovery;
private boolean email_digests;
private boolean email_messages;
private boolean email_post_reply;
private boolean email_private_message;
private boolean email_unsubscribe_all;
private boolean email_upvote_comment;
private boolean email_upvote_post;
private boolean email_username_mention;
private boolean email_user_new_follower;
private boolean enable_default_themes;
private boolean enable_followers;
private boolean feed_recommendations_enabled;
private boolean hide_ads;
private boolean hide_downs;
private boolean hide_from_robots;
private boolean hide_ups;
private boolean highlight_controversial;
private boolean highlight_new_comments;
private boolean ignore_suggested_sort;
private boolean label_nsfw;
private Language lang;
private boolean legacy_search;
private boolean live_orangereds;
private boolean mark_messages_read;
private MediaStyle media;
private MediaStyle media_preview;
private int min_comment_score;
private int min_link_score;
private boolean monitor_mentions;
private boolean newwindow;
private boolean nightmode;
private boolean no_profanity;
private int numsites;
private int num_comments;
private boolean over_18;
private boolean private_feeds;
private boolean profile_opt_out;
private boolean public_server_seconds;
private boolean public_votes;
private boolean research;
private boolean search_include_over_18;
private boolean send_crosspost_messages;
private boolean send_welcome_messages;
private boolean show_flair;
private boolean show_gold_expiration;
private boolean show_link_flair;
private boolean show_location_based_recommendations;
private boolean show_presence;
private boolean show_snoovatar;
private boolean show_stylesheets;
private boolean show_trending;
private boolean show_twitter;
private boolean store_visits;
private long survey_last_seen_time;
private boolean third_party_data_personalized_ads;
private boolean third_party_personalized_ads;
private boolean third_party_site_data_personalized_ads;
private boolean third_party_site_data_personalized_content;
private boolean threaded_messages;
private boolean threaded_modmail;
private boolean top_karma_subreddits;
private boolean use_global_defaults;
private boolean video_autoplay;
private transient Reddit4J client;
public PrivateMessagePolicy getPrivateMessagePolicy() {
return accept_pms;
}
public PrivateMessagePolicy getAcceptMessages() {
return accept_pms;
}
public boolean hasActivityRelevantAds() {
return activity_relevant_ads;
}
public boolean doesAllowClickTracking() {
return allow_clicktracking;
}
public BadCommentAutocollapse getBadCommentAutocollapse() {
return bad_comment_autocollapse;
}
public boolean isBeta() {
return beta;
}
public boolean isClickgadget() {
return clickgadget;
}
public boolean doesCollapseLeftBar() {
return collapse_left_bar;
}
public boolean doesCollapseReadMessages() {
return collapse_read_messages;
}
public boolean isCompress() {
return compress;
}
public CountryCode getCountryCode() {
return country_code;
}
public DefaultCommentSort getDefaultCommentSort() {
return default_comment_sort;
}
public boolean isDesignBeta() {
return design_beta;
}
public boolean isDomainDetails() {
return domain_details;
}
public boolean isEmailChatRequest() {
return email_chat_request;
}
public boolean isEmailCommentReply() {
return email_comment_reply;
}
public boolean isEmailCommunityDiscovery() {
return email_community_discovery;
}
public boolean isEmailDigests() {
return email_digests;
}
public boolean isEmailMessages() {
return email_messages;
}
public boolean isEmailPostReply() {
return email_post_reply;
}
public boolean isEmailPrivateMessage() {
return email_private_message;
}
public boolean isEmailUnsubscribeAll() {
return email_unsubscribe_all;
}
public boolean isEmailUpvoteComment() {
return email_upvote_comment;
}
public boolean isEmailUpvotePost() {
return email_upvote_post;
}
public boolean isEmailUsernameMention() {
return email_username_mention;
}
public boolean isEmailUserNewFollower() {
return email_user_new_follower;
}
public boolean hasEnableDefaultThemes() {
return enable_default_themes;
}
public boolean hasEnableFollowers() {
return enable_followers;
}
public boolean hasFeedRecommendationsEnabled() {
return feed_recommendations_enabled;
}
public boolean doesHideAds() {
return hide_ads;
}
public boolean doesHideDowns() {
return hide_downs;
}
public boolean doesHideFromRobots() {
return hide_from_robots;
}
public boolean doesHideUps() {
return hide_ups;
}
public boolean doesHighlightControversial() {
return highlight_controversial;
}
public boolean doesHighlightNewComments() {
return highlight_new_comments;
}
public boolean doesIgnoreSuggestedSort() {
return ignore_suggested_sort;
}
public boolean doesLabelNSFW() {
return label_nsfw;
}
public Language getLanguage() {
return lang;
}
public boolean usesLegacySearch() {
return legacy_search;
}
public boolean isLiveOrangereds() {
return live_orangereds;
}
public boolean doesMarkMessagesRead() {
return mark_messages_read;
}
public MediaStyle getMediaStyle() {
return media;
}
public MediaStyle getMediaPreviewStyle() {
return media_preview;
}
public int getMinimumCommentScore() {
return min_comment_score;
}
public int getMinimumLinkScore() {
return min_link_score;
}
public boolean doesMonitorMentions() {
return monitor_mentions;
}
public boolean isNewWindow() {
return newwindow;
}
public boolean isNightMode() {
return nightmode;
}
public boolean isNoProfanity() {
return no_profanity;
}
public int getNumberOfSites() {
return numsites;
}
public int getNumberOfComments() {
return num_comments;
}
public boolean isOver18() {
return over_18;
}
public boolean hasPrivateFeeds() {
return private_feeds;
}
public boolean isProfileOptOut() {
return profile_opt_out;
}
public boolean isPublicServerSeconds() {
return public_server_seconds;
}
public boolean hasPublicVotes() {
return public_votes;
}
public boolean doesResearch() {
return research;
}
public boolean hasSearchIncludeOver18() {
return search_include_over_18;
}
public boolean doesSendCrosspostMessages() {
return send_crosspost_messages;
}
public boolean doesSendWelcomeMessages() {
return send_welcome_messages;
}
public boolean doesShowFlair() {
return show_flair;
}
public boolean doesShowGoldExpiration() {
return show_gold_expiration;
}
public boolean doesShowLinkFlair() {
return show_link_flair;
}
public boolean doesShowLocationBasedRecommendations() {
return show_location_based_recommendations;
}
public boolean doesShowPresence() {
return show_presence;
}
public boolean doesShowSnoovatar() {
return show_snoovatar;
}
public boolean doesShowStylesheets() {
return show_stylesheets;
}
public boolean doesShowTrending() {
return show_trending;
}
public boolean doesShowTwitter() {
return show_twitter;
}
public boolean hasStoreVisits() {
return store_visits;
}
public long getSurveyLastSeenTime() {
return survey_last_seen_time;
}
public boolean isThirdPartyDataPersonalizedAds() {
return third_party_data_personalized_ads;
}
public boolean isThirdPartyPersonalizedAds() {
return third_party_personalized_ads;
}
public boolean isThirdPartySiteDataPersonalizedAds() {
return third_party_site_data_personalized_ads;
}
public boolean hasThirdPartySiteDataPersonalizedContent() {
return third_party_site_data_personalized_content;
}
public boolean hasThreadedMessages() {
return threaded_messages;
}
public boolean hasThreaded_modmail() {
return threaded_modmail;
}
public boolean hasTopKarmaSubreddits() {
return top_karma_subreddits;
}
public boolean doesUseGlobalDefaults() {
return use_global_defaults;
}
public boolean doesVideoAutoplay() {
return video_autoplay;
}
public Reddit4J getClient() {
return client;
}
public void setClient(Reddit4J client) {
this.client = client;
}
public Gson getGson() {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(MediaStyle.class, MediaStyle.getAdapter());
builder.registerTypeAdapter(PrivateMessagePolicy.class, PrivateMessagePolicy.getAdapter());
builder.registerTypeAdapter(CountryCode.class, CountryCode.getAdapter());
builder.registerTypeAdapter(Language.class, Language.getAdapter());
builder.registerTypeAdapter(DefaultCommentSort.class, DefaultCommentSort.getAdapter());
builder.registerTypeAdapter(BadCommentAutocollapse.class, BadCommentAutocollapse.getAdapter());
Gson gson = builder.create();
return gson;
}
}
|
package com.temple.web.rest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithUnauthenticatedMockUser.Factory.class)
public @interface WithUnauthenticatedMockUser {
class Factory implements WithSecurityContextFactory<WithUnauthenticatedMockUser> {
@Override
public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) {
return SecurityContextHolder.createEmptyContext();
}
}
}
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.java.stubs.index;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.impl.search.JavaSourceFilterScope;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.stubs.StringStubIndexExtension;
import com.intellij.psi.stubs.StubIndex;
import com.intellij.psi.stubs.StubIndexKey;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public class JavaAnnotationIndex extends StringStubIndexExtension<PsiAnnotation> {
private static final JavaAnnotationIndex ourInstance = new JavaAnnotationIndex();
public static JavaAnnotationIndex getInstance() {
return ourInstance;
}
@NotNull
@Override
public StubIndexKey<String, PsiAnnotation> getKey() {
return JavaStubIndexKeys.ANNOTATIONS;
}
@Override
public Collection<PsiAnnotation> get(@NotNull final String s, @NotNull final Project project, @NotNull final GlobalSearchScope scope) {
return StubIndex.getElements(getKey(), s, project, new JavaSourceFilterScope(scope), PsiAnnotation.class);
}
}
|
//
// Copyright 2009 Robin Komiwes, Bruno Verachten, Christophe Cordenier
//
// 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.wooki.services;
import javax.sql.DataSource;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.springframework.context.ApplicationContext;
import com.wooki.Draft;
import com.wooki.domain.biz.BookManager;
import com.wooki.domain.biz.ChapterManager;
import com.wooki.domain.biz.UserManager;
import com.wooki.domain.dao.UserDAO;
import com.wooki.domain.exception.AuthorizationException;
import com.wooki.domain.exception.UserAlreadyException;
import com.wooki.domain.model.Book;
import com.wooki.domain.model.Chapter;
import com.wooki.domain.model.Publication;
import com.wooki.domain.model.User;
import com.wooki.services.security.WookiSecurityContext;
public class StartupServiceImpl implements StartupService
{
public StartupServiceImpl(ApplicationContext applicationContext,
@Inject @Symbol(SymbolConstants.PRODUCTION_MODE) boolean productionMode,
BookManager bookManager, ChapterManager chapterManager, UserManager userManager,
UserDAO userDao, DataSource datasource) throws UserAlreadyException,
AuthorizationException
{
// enabled headless mode
System.setProperty("java.awt.headless", "true");
WookiSecurityContext securityCtx = (WookiSecurityContext) applicationContext
.getBean("wookiSecurityContext");
// Bypass creation if already done
if (userManager.findByUsername("ccordenier") != null) { return; }
User ccordenier = new User();
ccordenier.setEmail("christophe@gmail.com");
ccordenier.setUsername("ccordenier");
ccordenier.setPassword("password");
ccordenier.setFullname("Christophe C.");
userManager.registerUser(ccordenier);
User gounthar = new User();
gounthar.setEmail("bruno@gmail.com");
gounthar.setUsername("bverachten");
gounthar.setPassword("password");
gounthar.setFullname("Bruno V.");
userManager.registerUser(gounthar);
User robink = new User();
robink.setEmail("robin@gmail.com");
robink.setUsername("robink");
robink.setPassword("password");
robink.setFullname("Robin K.");
userManager.registerUser(robink);
securityCtx.log(robink);
// Create books
Book bookOfWooki = bookManager.create("The book of Wooki");
// publish Abstract
Chapter bookAbstract = chapterManager.listChaptersInfo(bookOfWooki.getId()).get(0);
Draft draft = new Draft();
draft.setTimestamp(bookAbstract.getLastModified());
draft
.setData("<p>What would you need if you had to write something and share it with someone else? We think you would be looking for Wooki : a <strong>publish platform</strong> offering the possibility to have <strong>direct feedback</strong> on what you have written.</p>");
chapterManager.updateAndPublishContent(bookAbstract.getId(), draft); // Create
// new chapters and modify its content
Chapter chapterOne = bookManager.addChapter(
bookOfWooki,
"Collaborative document publishing");
draft.setTimestamp(chapterOne.getLastModified());
draft
.setData("<p>The desire to make Wooki came from a finding: we noticed that the documentation we wrote every days at work did not provide the expected result.</p>"
+ "<p>We used to produce lots of documents on multiples formats: Word, PDF, Powerpoint and of course on our intranet knowledge base."
+ "Each format used to have its inconvenient:</p>"
+ "<ul>"
+ "<li>Intranet knowledge base wasn't enough corporate</li>"
+ "<li>Word and PDF contents were not indexed by our intranet crawlers.</li>"
+ "</ul>"
+ "<p>And the worst was that we almost never had feedback on these documents. We did not knew if the produced documentation was good enough."
+ " Why? <strong>Because we did not proposed an easy way to collaborate with people</strong>.</p>"
+ "<p>Wooki's goal is to suggest a solution to all theses problems. Of course, Wooki is not finished, that is just the beginning of the story.</p>");
chapterManager.updateAndPublishContent(chapterOne.getId(), draft); // Add
// robin to author's list
try
{
bookManager.addAuthor(bookOfWooki, "ccordenier");
bookManager.addAuthor(bookOfWooki, "bverachten");
}
catch (Exception e)
{
e.printStackTrace();
}
Publication publication = chapterManager.getLastPublishedPublication(chapterOne.getId());
chapterManager.addComment(publication.getId(), "This is a good starting point", "b20");
Chapter chapterTwo = bookManager.addChapter(bookOfWooki, "Open source contribution");
draft.setTimestamp(chapterTwo.getLastModified());
draft
.setData("<p>We are working since many months (...years?) on the web framework Tapestry 5. In some way, we always wanted to contribute to it as some kind of \"<quote>thank you</quote>\".</p>"
+ "<p>Doing a project like Wooki was perfect to show the possibilities of this framework: technologies integration, ease of development. </p>");
chapterManager.updateAndPublishContent(chapterTwo.getId(), draft);
Chapter chapterTree = bookManager.addChapter(bookOfWooki, "Get started");
draft.setTimestamp(chapterTree.getLastModified());
draft
.setData("<h3>Try the demo</h3>"
+ "<p>If you are reading that, you must already know that we host a demo website. You can freely:</p>"
+ "<ul>"
+ "<li>create accounts</li>"
+ "<li>create books</li>"
+ "<li>export them as PDF</li>"
+ "</ul>"
+ "<h3>Build Wooki directly from the source code</h3>"
+ "<p>Considering that you have already manipulated Tapestry 5 and maven, you can build the application directly from the source code.</p>"
+ "<p>Go on <a href=\"http://github.com/robink/wooki\">Github</a>, download the sources and run jetty executing this command:</p>"
+ "<pre>" + "mvn jetty:run" + "</pre>"
+ "<p>Launch your browser and that's it!</p>");
chapterManager.updateAndPublishContent(chapterTree.getId(), draft);
// Do an update for testing purpose on book Abstract
bookAbstract = chapterManager.findById(bookAbstract.getId());
draft.setTimestamp(bookAbstract.getLastModified());
draft
.setData("<p>What would you need if you had to write something and share it with someone else? We think you would be looking for Wooki : a <strong>publish platform</strong> offering the possibility to have <strong>direct feedback</strong> on what you have written.</p>");
chapterManager.updateContent(bookAbstract.getId(), draft); // Add
// a comment
securityCtx.log(ccordenier);
publication = chapterManager.getLastPublishedPublication(bookAbstract.getId());
chapterManager.addComment(publication.getId(), "Wooki is really cool !", "b10");
}
}
|
/*
* Decompiled with CFR 0_132.
*/
package com.enjoytheban.module.modules.combat;
import com.enjoytheban.Client;
import com.enjoytheban.api.EventHandler;
import com.enjoytheban.api.events.world.EventPacketSend;
import com.enjoytheban.api.events.world.EventPostUpdate;
import com.enjoytheban.api.events.world.EventPreUpdate;
import com.enjoytheban.api.value.Mode;
import com.enjoytheban.api.value.Numbers;
import com.enjoytheban.api.value.Option;
import com.enjoytheban.api.value.Value;
import com.enjoytheban.management.FriendManager;
import com.enjoytheban.management.ModuleManager;
import com.enjoytheban.module.Module;
import com.enjoytheban.module.ModuleType;
import com.enjoytheban.module.modules.combat.AntiBot;
import com.enjoytheban.module.modules.combat.AutoHeal;
import com.enjoytheban.module.modules.combat.Criticals;
import com.enjoytheban.module.modules.movement.Speed;
import com.enjoytheban.module.modules.player.Teams;
import com.enjoytheban.utils.Helper;
import com.enjoytheban.utils.TimerUtil;
import com.enjoytheban.utils.math.MathUtil;
import com.enjoytheban.utils.math.RotationUtil;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.EnumCreatureAttribute;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C02PacketUseEntity;
import net.minecraft.network.play.client.C07PacketPlayerDigging;
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
import net.minecraft.network.play.client.C0APacketAnimation;
import net.minecraft.potion.Potion;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public class Killaura
extends Module {
private TimerUtil timer = new TimerUtil();
private Entity target;
private List targets = new ArrayList(0);
private int index;
private int xd;
private int tpdelay;
private Numbers<Double> aps = new Numbers<Double>("APS", "APS", 10.0, 1.0, 20.0, 0.5);
private Numbers<Double> reach = new Numbers<Double>("Reach", "reach", 4.5, 1.0, 6.0, 0.1);
private Option<Boolean> blocking = new Option<Boolean>("Autoblock", "autoblock", true);
private Option<Boolean> players = new Option<Boolean>("Players", "players", true);
private Option<Boolean> animals = new Option<Boolean>("Animals", "animals", true);
private Option<Boolean> mobs = new Option<Boolean>("Mobs", "mobs", false);
private Option<Boolean> invis = new Option<Boolean>("Invisibles", "invisibles", false);
private Option<Boolean> god = new Option<Boolean>("Velt God Mode", "Velt God Mode", false);
private Mode<Enum> mode = new Mode("Mode", "mode", (Enum[])AuraMode.values(), (Enum)AuraMode.Switch);
private boolean isBlocking;
private Comparator<Entity> angleComparator = Comparator.comparingDouble(e2 -> RotationUtil.getRotations(e2)[0]);
public Killaura() {
super("KillAura", new String[]{"ka", "aura", "killa"}, ModuleType.Combat);
this.setColor(new Color(226, 54, 30).getRGB());
this.addValues(this.aps, this.reach, this.blocking, this.players, this.animals, this.mobs, this.invis, this.god, this.mode);
}
@Override
public void onDisable() {
this.targets.clear();
if (this.blocking.getValue().booleanValue() && this.canBlock() && this.mc.thePlayer.isBlocking()) {
this.stopAutoBlockHypixel();
}
}
@Override
public void onEnable() {
this.target = null;
this.index = 0;
this.xd = 0;
}
private boolean canBlock() {
if (this.mc.thePlayer.getCurrentEquippedItem() != null && this.mc.thePlayer.inventory.getCurrentItem().getItem() instanceof ItemSword) {
return true;
}
return false;
}
private void startAutoBlockHypixel() {
if (Helper.onServer("hypixel")) {
KeyBinding.setKeyBindState(this.mc.gameSettings.keyBindUseItem.getKeyCode(), true);
if (this.mc.playerController.sendUseItem(this.mc.thePlayer, this.mc.theWorld, this.mc.thePlayer.inventory.getCurrentItem())) {
this.mc.getItemRenderer().resetEquippedProgress2();
}
}
}
private void stopAutoBlockHypixel() {
if (Helper.onServer("hypixel")) {
KeyBinding.setKeyBindState(this.mc.gameSettings.keyBindUseItem.getKeyCode(), false);
this.mc.playerController.onStoppedUsingItem(this.mc.thePlayer);
}
}
private void startAutoBlock() {
if (!Helper.onServer("hypixel")) {
this.mc.playerController.sendUseItem(this.mc.thePlayer, this.mc.theWorld, this.mc.thePlayer.getCurrentEquippedItem());
}
}
private void stopAutoBlock() {
if (!Helper.onServer("hypixel")) {
this.mc.thePlayer.sendQueue.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
}
}
private boolean shouldAttack() {
return this.timer.hasReached(1000.0 / (this.aps.getValue() + MathUtil.randomDouble(0.0, 5.0)));
}
@EventHandler
private void onUpdate(EventPreUpdate event) {
this.setSuffix(this.mode.getValue());
this.targets = this.loadTargets();
this.targets.sort(this.angleComparator);
if (this.target != null && this.target instanceof EntityPlayer || this.target instanceof EntityMob || this.target instanceof EntityAnimal) {
this.target = null;
}
if (this.mc.thePlayer.ticksExisted % 50 == 0 && this.targets.size() > 1) {
++this.index;
}
if (!this.targets.isEmpty()) {
if (this.index >= this.targets.size()) {
this.index = 0;
}
this.target = (Entity)this.targets.get(this.index);
if (!(Helper.onServer("invaded") || Helper.onServer("minemen") || Helper.onServer("faithful"))) {
event.setYaw(RotationUtil.faceTarget(this.target, 1000.0f, 1000.0f, false)[0]);
if (!AutoHeal.currentlyPotting) {
event.setPitch(RotationUtil.faceTarget(this.target, 1000.0f, 1000.0f, false)[1]);
}
}
if (this.blocking.getValue().booleanValue() && this.canBlock() && this.isBlocking) {
this.stopAutoBlock();
if (this.god.getValue().booleanValue()) {
event.y += 13.8;
}
} else if (this.god.getValue().booleanValue()) {
event.y += 4.5;
event.setOnground(true);
}
} else if (this.blocking.getValue().booleanValue() && this.canBlock() && this.mc.thePlayer.isBlocking()) {
this.stopAutoBlockHypixel();
}
}
private void swap(int slot, int hotbarNum) {
this.mc.playerController.windowClick(this.mc.thePlayer.inventoryContainer.windowId, slot, hotbarNum, 2, this.mc.thePlayer);
}
@EventHandler
private void onUpdatePost(EventPostUpdate e) {
if (Helper.onServer("enjoytheban")) {
this.reach.setValue(4.0);
this.aps.setValue(12.0);
this.god.setValue(false);
}
if (!Helper.onServer("faithful")) {
Speed speed;
if (this.god.getValue().booleanValue() && (speed = (Speed)Client.instance.getModuleManager().getModuleByClass(Speed.class)).isEnabled()) {
speed.setEnabled(false);
}
if (this.target != null) {
double angle = Math.toRadians(this.target.rotationYaw - 90.0f + 360.0f) % 360.0;
if (this.shouldAttack()) {
Criticals crits = (Criticals)Client.instance.getModuleManager().getModuleByClass(Criticals.class);
if (crits.isEnabled()) {
crits.hypixelCrit();
}
if (crits.isEnabled()) {
crits.packetCrit();
}
if (this.mode.getValue() == AuraMode.Switch) {
this.attack();
} else {
this.swap(9, this.mc.thePlayer.inventory.currentItem);
this.attack();
this.attack();
this.attack();
crits.offsetCrit();
this.swap(9, this.mc.thePlayer.inventory.currentItem);
this.attack();
this.attack();
crits.offsetCrit();
}
if (!this.mc.thePlayer.isBlocking() && this.canBlock() && this.blocking.getValue().booleanValue()) {
this.startAutoBlockHypixel();
}
this.timer.reset();
}
if (this.canBlock() && this.blocking.getValue().booleanValue() && !this.mc.thePlayer.isBlocking()) {
this.startAutoBlock();
}
}
}
}
private List<Entity> loadTargets() {
return this.mc.theWorld.loadedEntityList.stream().filter(e -> (double)this.mc.thePlayer.getDistanceToEntity((Entity)e) <= this.reach.getValue() && this.qualifies((Entity)e)).collect(Collectors.toList());
}
private boolean qualifies(Entity e) {
if (e == this.mc.thePlayer) {
return false;
}
AntiBot ab = (AntiBot)Client.instance.getModuleManager().getModuleByClass(AntiBot.class);
if (ab.isServerBot(e)) {
return false;
}
if (!e.isEntityAlive()) {
return false;
}
if (FriendManager.isFriend(e.getName())) {
return false;
}
if (e instanceof EntityPlayer && this.players.getValue().booleanValue() && !Teams.isOnSameTeam(e)) {
return true;
}
if (e instanceof EntityMob && this.mobs.getValue().booleanValue()) {
return true;
}
if (e instanceof EntityAnimal && this.animals.getValue().booleanValue()) {
return true;
}
if (e.isInvisible() && !this.invis.getValue().booleanValue()) {
return true;
}
return false;
}
private void attack() {
if (this.blocking.getValue().booleanValue() && this.canBlock() && this.mc.thePlayer.isBlocking() && this.qualifies(this.target)) {
this.stopAutoBlockHypixel();
}
if (Helper.onServer("invaded")) {
this.mc.thePlayer.sendQueue.addToSendQueue(new C0APacketAnimation());
} else {
this.mc.thePlayer.swingItem();
}
this.mc.thePlayer.sendQueue.addToSendQueue(new C02PacketUseEntity(this.target, C02PacketUseEntity.Action.ATTACK));
}
@EventHandler
private void blockinglistener(EventPacketSend packet) {
C07PacketPlayerDigging packetPlayerDigging;
C08PacketPlayerBlockPlacement blockPlacement;
if (packet.getPacket() instanceof C07PacketPlayerDigging && (packetPlayerDigging = (C07PacketPlayerDigging)packet.getPacket()).getStatus().equals((Object)C07PacketPlayerDigging.Action.RELEASE_USE_ITEM)) {
this.isBlocking = false;
}
if (packet.getPacket() instanceof C08PacketPlayerBlockPlacement && (blockPlacement = (C08PacketPlayerBlockPlacement)packet.getPacket()).getStack() != null && blockPlacement.getStack().getItem() instanceof ItemSword && blockPlacement.getPosition().equals(new BlockPos(-1, -1, -1))) {
this.isBlocking = true;
}
}
public void mmcAttack(EntityLivingBase entity) {
this.mmcAttack(entity, false);
}
public void mmcAttack(EntityLivingBase entity, boolean crit) {
this.mc.thePlayer.swingItem();
float sharpLevel = EnchantmentHelper.getModifierForCreature(this.mc.thePlayer.getHeldItem(), entity.getCreatureAttribute());
boolean vanillaCrit = this.mc.thePlayer.fallDistance > 0.0f && !this.mc.thePlayer.onGround && !this.mc.thePlayer.isOnLadder() && !this.mc.thePlayer.isInWater() && !this.mc.thePlayer.isPotionActive(Potion.blindness) && this.mc.thePlayer.ridingEntity == null;
this.mc.thePlayer.sendQueue.addToSendQueue(new C02PacketUseEntity((Entity)entity, C02PacketUseEntity.Action.ATTACK));
if (crit || vanillaCrit) {
this.mc.thePlayer.onCriticalHit(entity);
}
if (sharpLevel > 0.0f) {
this.mc.thePlayer.onEnchantmentCritical(entity);
}
}
static enum AuraMode {
Switch,
Tick;
}
}
|
/*
* MIT License
*
* Copyright (c) 2021 cybo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.cybooo.creativehousing.Manager;
import com.github.cybooo.creativehousing.Plugin;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class AutoReconect {
public static void Check() {
Plugin.getInstance().getProxy().getScheduler().schedule(Plugin.getInstance(), () -> {
if (!(Plugin.srv.testCon())) {
System.out.println("Pripojeni k GZNode bylo ztraceno pokus");
Plugin.srv.kill();
try {
Plugin.srv.init();
} catch (IOException e) {
e.printStackTrace();
}
}
}, 1, 5, TimeUnit.SECONDS);
}
}
|
package com.oembedler.moon.graphql.boot;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ClasspathResourceSchemaStringProvider implements SchemaStringProvider {
@Autowired
private ApplicationContext applicationContext;
@Value("${graphql.tools.schemaLocationPattern:**/*.graphqls}")
private String schemaLocationPattern;
@Override
public List<String> schemaStrings() throws IOException {
Resource[] resources = applicationContext.getResources("classpath*:" + schemaLocationPattern);
if (resources.length <= 0) {
throw new IllegalStateException(
"No graphql schema files found on classpath with location pattern '"
+ schemaLocationPattern
+ "'. Please add a graphql schema to the classpath or add a SchemaParser bean to your application context.");
}
return Arrays.stream(resources)
.map(this::readSchema)
.collect(Collectors.toList());
}
private String readSchema(Resource resource) {
StringWriter writer = new StringWriter();
try (InputStream inputStream = resource.getInputStream()) {
IOUtils.copy(inputStream, writer);
} catch (IOException e) {
throw new IllegalStateException("Cannot read graphql schema from resource " + resource, e);
}
return writer.toString();
}
}
|
/*
* Copyright 2012-2017 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.rds.model;
import javax.annotation.Generated;
/**
* <p>
* You have reached the maximum number of event subscriptions.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EventSubscriptionQuotaExceededException extends com.amazonaws.services.rds.model.AmazonRDSException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new EventSubscriptionQuotaExceededException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public EventSubscriptionQuotaExceededException(String message) {
super(message);
}
}
|
package java.io;
public class File
{
public File( File parent, String name ) {}
public boolean exists()
{
return false;
}
}
|
/*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package de.hybris.platform.integrationservices.model.impl;
import de.hybris.platform.integrationservices.model.AttributeSettableChecker;
import de.hybris.platform.integrationservices.model.AttributeSettableCheckerFactory;
import de.hybris.platform.integrationservices.model.TypeAttributeDescriptor;
import javax.validation.constraints.NotNull;
/**
* Default implementation of {@link AttributeSettableCheckerFactory}.
*/
public class DefaultAttributeSettableCheckerFactory implements AttributeSettableCheckerFactory
{
private static final AttributeSettableChecker DEFAULT_CHECKER = new NullAttributeSettableChecker();
private AttributeSettableChecker standardAttributeSettableChecker;
private AttributeSettableChecker classificationAttributeSettableChecker;
@Override
public AttributeSettableChecker create(@NotNull final TypeAttributeDescriptor descriptor)
{
return descriptor instanceof DefaultTypeAttributeDescriptor ?
getStandardAttributeSettableChecker() :
getClassificationAttributeSettableChecker();
}
public AttributeSettableChecker getStandardAttributeSettableChecker()
{
return standardAttributeSettableChecker != null ?
standardAttributeSettableChecker :
DEFAULT_CHECKER;
}
public AttributeSettableChecker getClassificationAttributeSettableChecker()
{
return classificationAttributeSettableChecker != null ?
classificationAttributeSettableChecker :
DEFAULT_CHECKER;
}
public void setStandardAttributeSettableChecker(
final AttributeSettableChecker standardAttributeSettableChecker)
{
this.standardAttributeSettableChecker = standardAttributeSettableChecker;
}
public void setClassificationAttributeSettableChecker(
final AttributeSettableChecker classificationAttributeSettableChecker)
{
this.classificationAttributeSettableChecker = classificationAttributeSettableChecker;
}
}
|
package net.zhuoweizhang.mcpelauncher.texture;
import org.json.*;
import android.graphics.Bitmap;
public final class TexturePackDescription {
public String type;
public String path;
public Bitmap img = null;
public String description = "";
public TexturePackDescription(String type, String path) {
this.type = type;
this.path = path;
}
// Schema for texture packs:
// JSON; "t": type, "p": path
// we expect scripts to be added to this, eventually
// not sure about addons?
public JSONObject toJson() throws JSONException {
return new JSONObject().put("t", type).put("p", path);
}
public String toString() {
return type + ":" + path;
}
public static TexturePackDescription fromJson(JSONObject obj) throws JSONException {
return new TexturePackDescription(obj.getString("t"), obj.getString("p"));
}
}
|
package de.bug0r.protocol.irc.parser.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.bug0r.message.irc.IIrcMessage;
import de.bug0r.message.irc.impl.ServlistMessage;
import de.bug0r.message.irc.utils.IrcMessageUtils;
import de.bug0r.protocol.irc.parser.message.IMessageParser;
public class ServlistParser implements IMessageParser {
@Override
public IIrcMessage parse(String rawMessage) {
List<String> targetList = Arrays.asList(rawMessage.split(IrcMessageUtils.SPACE));
List<String> messageTargetList = new ArrayList<String>();
if ( targetList.size() > 1 ) {
messageTargetList = targetList.subList(1, targetList.size());
}
return new ServlistMessage(messageTargetList);
}
}
|
package com.blankj.utilcode.util;
import android.os.Build;
import android.support.v4.util.LongSparseArray;
import android.support.v4.util.SimpleArrayMap;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.util.SparseLongArray;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/12/24
* desc : utils about object
* </pre>
*/
public final class ObjectUtils {
private ObjectUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Return whether object is empty.
*
* @param obj The object.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isEmpty(final Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof CharSequence && obj.toString().length() == 0) {
return true;
}
if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
return true;
}
if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
return true;
}
if (obj instanceof Map && ((Map) obj).isEmpty()) {
return true;
}
if (obj instanceof SimpleArrayMap && ((SimpleArrayMap) obj).isEmpty()) {
return true;
}
if (obj instanceof SparseArray && ((SparseArray) obj).size() == 0) {
return true;
}
if (obj instanceof SparseBooleanArray && ((SparseBooleanArray) obj).size() == 0) {
return true;
}
if (obj instanceof SparseIntArray && ((SparseIntArray) obj).size() == 0) {
return true;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
if (obj instanceof SparseLongArray && ((SparseLongArray) obj).size() == 0) {
return true;
}
}
if (obj instanceof LongSparseArray && ((LongSparseArray) obj).size() == 0) {
return true;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (obj instanceof android.util.LongSparseArray
&& ((android.util.LongSparseArray) obj).size() == 0) {
return true;
}
}
return false;
}
/**
* Return whether object is not empty.
*
* @param obj The object.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isNotEmpty(final Object obj) {
return !isEmpty(obj);
}
/**
* Return whether object1 is equals to object2.
*
* @param o1 The first object.
* @param o2 The second object.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean equals(final Object o1, final Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
/**
* Require the object is not null.
*
* @param object The object.
* @param message The message to use with the NullPointerException.
* @param <T> The value type.
* @return the object
* @throws NullPointerException if object is null
*/
public static <T> T requireNonNull(final T object, final String message) {
if (object == null) {
throw new NullPointerException(message);
}
return object;
}
/**
* Return the nonnull object or default object.
*
* @param object The object.
* @param defaultObject The default object to use with the object is null.
* @param <T> The value type.
* @return the nonnull object or default object
*/
public static <T> T getOrDefault(final T object, final T defaultObject) {
if (object == null) {
return defaultObject;
}
return object;
}
/**
* Return the hash code of object.
*
* @param o The object.
* @return the hash code of object
*/
public static int hashCode(final Object o) {
return o != null ? o.hashCode() : 0;
}
}
|
package com.sensordroid.flow.Bluetooth;
import android.content.Intent;
public interface BluetoothCallback {
void onDataReceived(Intent data);
}
|
package uk.gov.hmcts.reform.divorce.orchestration.service.bulk.print.helper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.Map;
import static com.google.common.base.Strings.nullToEmpty;
import static java.lang.String.format;
import static uk.gov.hmcts.reform.divorce.orchestration.domain.model.OrchestrationConstants.DOCUMENT_FILENAME_FMT;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StringHelper {
public static String formatFilename(String caseId, String filename) {
return format(DOCUMENT_FILENAME_FMT, notNull(filename), notNull(caseId));
}
public static String buildFullName(Map<String, Object> caseData, String firstName, String lastName) {
return (
nullToEmpty((String) (caseData.get(firstName))).trim()
+ " "
+ nullToEmpty((String) (caseData.get(lastName))).trim()
).trim();
}
public static String notNull(String value) {
if (value == null) {
throw new IllegalArgumentException("Value must not be null");
}
return value;
}
}
|
package mezz.jei.recipes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import mezz.jei.api.ingredients.subtypes.UidContext;
import net.minecraft.util.ResourceLocation;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import mezz.jei.api.ingredients.IIngredientHelper;
import mezz.jei.api.recipe.IFocus;
import mezz.jei.api.recipe.advanced.IRecipeManagerPlugin;
import mezz.jei.api.recipe.category.IRecipeCategory;
import mezz.jei.api.runtime.IIngredientManager;
import mezz.jei.gui.Focus;
import mezz.jei.ingredients.IngredientInformation;
public class InternalRecipeManagerPlugin implements IRecipeManagerPlugin {
private final RecipeManager recipeManager;
private final ImmutableMultimap<String, ResourceLocation> categoriesForRecipeCatalystKeys;
private final IIngredientManager ingredientManager;
private final RecipeCategoryDataMap recipeCategoriesMap;
private final RecipeMap recipeInputMap;
private final RecipeMap recipeOutputMap;
public InternalRecipeManagerPlugin(
RecipeManager recipeManager,
ImmutableMultimap<String, ResourceLocation> categoriesForRecipeCatalystKeys,
IIngredientManager ingredientManager,
RecipeCategoryDataMap recipeCategoriesMap,
RecipeMap recipeInputMap,
RecipeMap recipeOutputMap
) {
this.recipeManager = recipeManager;
this.categoriesForRecipeCatalystKeys = categoriesForRecipeCatalystKeys;
this.ingredientManager = ingredientManager;
this.recipeCategoriesMap = recipeCategoriesMap;
this.recipeInputMap = recipeInputMap;
this.recipeOutputMap = recipeOutputMap;
}
@Override
public <V> List<ResourceLocation> getRecipeCategoryUids(IFocus<V> focus) {
focus = Focus.check(focus);
V ingredient = focus.getValue();
switch (focus.getMode()) {
case INPUT:
return recipeInputMap.getRecipeCategories(ingredient);
case OUTPUT:
return recipeOutputMap.getRecipeCategories(ingredient);
default:
return getRecipeCategories();
}
}
private ImmutableList<ResourceLocation> getRecipeCategories() {
ImmutableList.Builder<ResourceLocation> builder = ImmutableList.builder();
for (IRecipeCategory<?> recipeCategory : recipeManager.getRecipeCategories()) {
builder.add(recipeCategory.getUid());
}
return builder.build();
}
@Override
public <T, V> List<T> getRecipes(IRecipeCategory<T> recipeCategory, IFocus<V> focus) {
focus = Focus.check(focus);
V ingredient = focus.getValue();
IIngredientHelper<V> ingredientHelper = ingredientManager.getIngredientHelper(ingredient);
if (focus.getMode() == IFocus.Mode.INPUT) {
final ImmutableList<T> recipes = recipeInputMap.getRecipes(recipeCategory, ingredient);
ResourceLocation recipeCategoryUid = recipeCategory.getUid();
for (String inputKey : IngredientInformation.getUniqueIdsWithWildcard(ingredientHelper, ingredient, UidContext.Recipe)) {
if (categoriesForRecipeCatalystKeys.get(inputKey).contains(recipeCategoryUid)) {
ImmutableSet<T> specificRecipes = ImmutableSet.copyOf(recipes);
RecipeCategoryData<T> recipeCategoryData = recipeCategoriesMap.get(recipeCategory);
List<T> recipesForCategory = recipeCategoryData.getRecipes();
List<T> allRecipes = new ArrayList<>(recipes);
for (T recipe : recipesForCategory) {
if (!specificRecipes.contains(recipe)) {
allRecipes.add(recipe);
}
}
return allRecipes;
}
}
return recipes;
} else {
return recipeOutputMap.getRecipes(recipeCategory, ingredient);
}
}
@Override
public <T> List<T> getRecipes(IRecipeCategory<T> recipeCategory) {
RecipeCategoryData<T> recipeCategoryData = recipeCategoriesMap.get(recipeCategory);
List<T> recipes = recipeCategoryData.getRecipes();
return Collections.unmodifiableList(recipes);
}
}
|
package com.javainuse.model;
public class Product {
private String type;
private int discount;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
}
|
package com.honeyewll.lbstest;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
import java.util.Timer;
import java.util.TimerTask;
/**
* 使用 java.util.Timer 来执行定时任务
*/
public class TimeRunner {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask timerTask = new SimpleTimerTask();
// 延迟 1 秒之后,开始每隔 5 秒钟之后再执行任务
timer.schedule(timerTask, 1000L, 5000L);
}
}
|
/*
* Copyright (c) 2010-2018 Osman Shoukry
*
* 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.openpojo.reflection.java.version;
import com.openpojo.reflection.java.version.impl.VersionImp;
/**
* @author oshoukry
*/
public class VersionFactory {
public static Version getImplementationVersion(Class clazz) {
if (clazz != null)
return getVersion(clazz.getPackage().getImplementationVersion());
return new VersionImp(null);
}
public static Version getVersion(String version) {
return new VersionImp(version);
}
private VersionFactory() {
throw new UnsupportedOperationException(VersionFactory.class.getName() + " should not be constructed!");
}
}
|
/*
* Copyright 2010-2012 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.elasticmapreduce.util;
import java.util.ArrayList;
import java.util.List;
import com.amazonaws.services.elasticmapreduce.model.HadoopJarStepConfig;
import com.amazonaws.util.StringUtils;
/**
* This class provides helper methods for creating common Elastic MapReduce step
* types. To use StepFactory, you should construct it with the appropriate
* bucket for your region. The official bucket format is
* "<region>.elasticmapreduce", so us-east-1 would use the bucket
* "us-east-1.elasticmapreduce".
* <p>
* Example usage, create an interactive Hive job flow with debugging enabled:
* <pre>
* AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
* AmazonElasticMapReduce emr = new AmazonElasticMapReduceClient(credentials);
*
* StepFactory stepFactory = new StepFactory();
*
* StepConfig enableDebugging = new StepConfig()
* .withName("Enable Debugging")
* .withActionOnFailure("TERMINATE_JOB_FLOW")
* .withHadoopJarStep(stepFactory.newEnableDebuggingStep());
*
* StepConfig installHive = new StepConfig()
* .withName("Install Hive")
* .withActionOnFailure("TERMINATE_JOB_FLOW")
* .withHadoopJarStep(stepFactory.newInstallHiveStep());
*
* RunJobFlowRequest request = new RunJobFlowRequest()
* .withName("Hive Interactive")
* .withSteps(enableDebugging, installHive)
* .withLogUri("s3://log-bucket/")
* .withInstances(new JobFlowInstancesConfig()
* .withEc2KeyName("keypair")
* .withHadoopVersion("0.20")
* .withInstanceCount(5)
* .withKeepJobFlowAliveWhenNoSteps(true)
* .withMasterInstanceType("m1.small")
* .withSlaveInstanceType("m1.small"));
*
* RunJobFlowResult result = emr.runJobFlow(request);
* </pre>
*/
public class StepFactory {
private final String bucket;
/**
* The available Hive versions. These are only available on Hadoop 0.20
* Hive_0_5 Hive 0.5
* Hive_0_7 Hive 0.7
* Hive_0_7_1 Hive 0.7.1
*/
public static enum HiveVersion {
Hive_0_5("0.5"),
Hive_0_7("0.7"),
Hive_0_7_1("0.7.1"),
Hive_Latest("latest");
private String stringVal;
HiveVersion(String str) {
stringVal = str;
}
@Override
public String toString() {
return stringVal;
}
}
/**
* Creates a new StepFactory using the default Elastic Map Reduce bucket
* (us-east-1.elasticmapreduce) for the default (us-east-1) region.
*/
public StepFactory() {
this("us-east-1.elasticmapreduce");
}
/**
* Creates a new StepFactory using the specified Amazon S3 bucket to load
* resources.
* <p>
* The official bucket format is "<region>.elasticmapreduce", so if
* you're using the us-east-1 region, you should use the bucket
* "us-east-1.elasticmapreduce".
*
* @param bucket
* The Amazon S3 bucket from which to load resources.
*/
public StepFactory(String bucket) {
this.bucket = bucket;
}
/**
* Runs a specified script on the master node of your cluster.
*
* @param script
* The script to run.
* @param args
* Arguments that get passed to the script.
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newScriptRunnerStep(String script, String... args) {
List<String> argsList = new ArrayList<String>();
argsList.add(script);
for (String arg : args) {
argsList.add(arg);
}
return new HadoopJarStepConfig()
.withJar("s3://" + bucket + "/libs/script-runner/script-runner.jar")
.withArgs(argsList);
}
/**
* When ran as the first step in your job flow, enables the Hadoop debugging
* UI in the AWS Management Console.
*
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newEnableDebuggingStep() {
return newScriptRunnerStep("s3://" + bucket + "/libs/state-pusher/0.1/fetch");
}
/**
* Step that installs the specified versions of Hive on your job flow.
*
* @param hiveVersions the versions of Hive to install
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newInstallHiveStep(HiveVersion... hiveVersions) {
if (hiveVersions.length > 0) {
String[] versionStrings = new String[hiveVersions.length];
for (int i = 0; i < hiveVersions.length; i++) {
versionStrings[i] = hiveVersions[i].toString();
}
return newInstallHiveStep(versionStrings);
}
return newHivePigStep("hive", "--install-hive", "--hive-versions", "latest");
}
/**
* Step that installs the specified versions of Hive on your job flow.
*
* @param hiveVersions the versions of Hive to install
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newInstallHiveStep(String... hiveVersions) {
if (hiveVersions.length > 0) {
return newHivePigStep("hive", "--install-hive", "--hive-versions",
StringUtils.join(",", hiveVersions));
}
return newHivePigStep("hive", "--install-hive", "--hive-versions", "latest");
}
/**
* Step that installs the default version of Hive on your job flow. This is
* 0.4 for Hadoop 0.18 and 0.5 for Hadoop 0.20.
*
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newInstallHiveStep() {
return newInstallHiveStep(new HiveVersion[0]);
}
/**
* Step that runs a Hive script on your job flow.
*
* @param script
* The script to run.
* @param args
* Arguments that get passed to the script.
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newRunHiveScriptStep(String script, String... args) {
String[] argsArray = new String[args.length + 4];
argsArray[0] = "--run-hive-script";
argsArray[1] = "--args";
argsArray[2] = "-f";
argsArray[3] = script;
System.arraycopy(args, 0, argsArray, 4, args.length);
return newHivePigStep("hive", argsArray);
}
/**
* Step that installs the default version of Pig on your job flow.
*
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newInstallPigStep() {
return newInstallPigStep(new String[0]);
}
/**
* Step that installs Pig on your job flow.
*
* @param pigVersions the versions of Pig to install.
*
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newInstallPigStep(String... pigVersions) {
if (pigVersions != null && pigVersions.length > 0) {
return newHivePigStep("pig", "--install-pig", "--pig-versions",
StringUtils.join(",", pigVersions));
}
return newHivePigStep("pig", "--install-pig", "--pig-versions", "latest");
}
/**
* Step that runs a Pig script on your job flow.
*
* @param script
* The script to run.
* @param args
* Arguments that get passed to the script.
* @return HadoopJarStepConfig that can be passed to your job flow.
*/
public HadoopJarStepConfig newRunPigScriptStep(String script, String... args) {
String[] argsArray = new String[args.length + 4];
argsArray[0] = "--run-pig-script";
argsArray[1] = "--args";
argsArray[2] = "-f";
argsArray[3] = script;
System.arraycopy(args, 0, argsArray, 4, args.length);
return newHivePigStep("pig", argsArray);
}
private HadoopJarStepConfig newHivePigStep(String type, String... args) {
String[] argsArray = new String[args.length + 2];
argsArray[0] = "--base-path";
argsArray[1] = "s3://" + bucket + "/libs/" + type + "/";
System.arraycopy(args, 0, argsArray, 2, args.length);
return newScriptRunnerStep("s3://" + bucket + "/libs/" + type + "/" + type + "-script", argsArray);
}
}
|
/*
* Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* 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 Eclipse Foundation, Inc. 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 org.eclipse.jgit.revwalk;
import java.io.IOException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
abstract class BlockRevQueue extends AbstractRevQueue {
protected BlockFreeList free;
/**
* Create an empty revision queue.
*/
protected BlockRevQueue() {
free = new BlockFreeList();
}
BlockRevQueue(Generator s) throws MissingObjectException,
IncorrectObjectTypeException, IOException {
free = new BlockFreeList();
outputType = s.outputType();
s.shareFreeList(this);
for (;;) {
final RevCommit c = s.next();
if (c == null)
break;
add(c);
}
}
/**
* {@inheritDoc}
* <p>
* Reconfigure this queue to share the same free list as another.
* <p>
* Multiple revision queues can be connected to the same free list, making
* it less expensive for applications to shuttle commits between them. This
* method arranges for the receiver to take from / return to the same free
* list as the supplied queue.
* <p>
* Free lists are not thread-safe. Applications must ensure that all queues
* sharing the same free list are doing so from only a single thread.
*/
@Override
public void shareFreeList(BlockRevQueue q) {
free = q.free;
}
static final class BlockFreeList {
private Block next;
Block newBlock() {
Block b = next;
if (b == null)
return new Block();
next = b.next;
b.clear();
return b;
}
void freeBlock(Block b) {
b.next = next;
next = b;
}
void clear() {
next = null;
}
}
static final class Block {
static final int BLOCK_SIZE = 256;
/** Next block in our chain of blocks; null if we are the last. */
Block next;
/** Our table of queued commits. */
final RevCommit[] commits = new RevCommit[BLOCK_SIZE];
/** Next valid entry in {@link #commits}. */
int headIndex;
/** Next free entry in {@link #commits} for addition at. */
int tailIndex;
boolean isFull() {
return tailIndex == BLOCK_SIZE;
}
boolean isEmpty() {
return headIndex == tailIndex;
}
boolean canUnpop() {
return headIndex > 0;
}
void add(RevCommit c) {
commits[tailIndex++] = c;
}
void unpop(RevCommit c) {
commits[--headIndex] = c;
}
RevCommit pop() {
return commits[headIndex++];
}
RevCommit peek() {
return commits[headIndex];
}
void clear() {
next = null;
headIndex = 0;
tailIndex = 0;
}
void resetToMiddle() {
headIndex = tailIndex = BLOCK_SIZE / 2;
}
void resetToEnd() {
headIndex = tailIndex = BLOCK_SIZE;
}
}
}
|
/*
* Copyright 2015 Rayco Araña
*
* 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.raycoarana.baindo.properties;
import com.raycoarana.baindo.BindableSource;
import com.raycoarana.baindo.WorkDispatcher;
import com.raycoarana.baindo.observables.AbstractProperty;
public class EnabledBind extends BaseObservableBind<Boolean, AbstractProperty<Boolean>> {
public EnabledBind(BindableSource bindableSource, WorkDispatcher workDispatcher) {
super(bindableSource, workDispatcher);
}
@Override
protected void bindView() {
throw new IllegalStateException("Enabled bind doesn't support WRITE or READ_WRITE mode.");
}
@Override
protected void unbindView() {
}
@Override
protected void updateView() {
mView.setEnabled(getValueOrFalse());
}
protected boolean getValueOrFalse() {
Boolean value = mTarget.getValue();
return value != null ? value : false;
}
}
|
package com.xlx.ss.shiro.chapter6.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import com.xlx.ss.shiro.chapter6.entity.User;
import com.xlx.ss.shiro.chapter6.tools.JdbcTemplateUtils;
/**
*
* @author G0009263
* @date 05/17/2019
* @tool Eclipse
*/
public class UserDaoImpl implements UserDao {
private static final Logger logger = Logger.getLogger(UserDaoImpl.class);
private JdbcTemplate jdbcTemplate = JdbcTemplateUtils.jdbcTemplate();
public User createUser(final User user) {// 新增用户
final String sql = "insert into sys_users(username,password,salt,locked) values(?,?,?,?)";
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement psst = connection.prepareStatement(sql, new String[] { "id" });
psst.setString(1, user.getUsername());
psst.setString(2, user.getPassword());
psst.setString(3, user.getSalt());
psst.setBoolean(4, user.getLocked());
return psst;
}
},keyHolder);
user.setId(keyHolder.getKey().longValue());
return user;
}
@Override
public void updateUser(User user) { //更新用户
String sql = "update sys_users set username=?,password=?,salt=?,locked=? where id=?";
jdbcTemplate.update(sql, user.getUsername(),user.getPassword(),user.getSalt(),user.getLocked(),user.getId());
}
@Override
public void deleteUser(Long id) {// 删除用户
String sql = "delete from sys_users where id =?";
jdbcTemplate.update(sql, id);
}
@Override
public User findOne(Long userId) { //查找用户 by id
String sql = "select id,username,password,salt,locked from sys_users where id =?";
List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class),userId);
if(userList.size() == 0) {
return null;
}
logger.info("userList[0]--------->" + userList.get(0));
return userList.get(0);
}
@Override
public User findByUserName(String username) { // 查找用户by username
String sql = "select id,username,password,salt,locked from sys_users where username =?";
List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class), username);
if (userList.size() == 0) {
return null;
}
return userList.get(0);
}
/*
* 新增用户-角色(sys_users_roles)
* insert前检验能否执行insert
*/
@Override
public void correlationRoles(Long userId, Long... roleIds) { //新增用户-角色
if(userId == null || roleIds.length == 0) {
return;
}
String sql = "insert into sys_users_roles(user_id,role_id) values(?,?)";
//校验是否可以insert操作
for(Long roleId : roleIds) {
if(!exists(userId,roleId)) {// 不存在,才能insert操作
jdbcTemplate.update(sql, userId,roleId);
}
}
}
/**
* sys_users_roles表插入前验证
* @param userId
* @param roleId
* @return true 存在
*/
private boolean exists(Long userId,Long roleId) {
String sql = "select count(1) from sys_users_roles where user_id =? and role_id =?";
return jdbcTemplate.queryForObject(sql, Integer.class, userId,roleId) != 0;
}
@Override
public void uncorrelationRoles(Long userId, Long... roleIds) { // 删除用户-角色
if(userId == null || roleIds.length == 0) {
return;
}
String sql = "delete from sys_users_roles where user_id =? and role_id =?";
// 校验是否可以delete操作
for(Long roleId : roleIds) {
if(exists(userId, roleId)) {// 存在,执行delete操作
jdbcTemplate.update(sql, userId,roleId);
}
}
}
@Override
public Set<String> findRoles(String username) { // 查找用户所有的角色
String sql = "select role from sys_users u,sys_roles r,sys_users_roles ur where username =? and u.id=ur.user_id and r.id=ur.role_id";
return new HashSet(jdbcTemplate.queryForList(sql, String.class,username));
}
@Override
public Set<String> findPermissions(String username) {// 查找用户所有权限
StringBuilder sb = new StringBuilder();
sb.append("SELECT")
.append(" p.permission")
.append(" FROM")
.append(" sys_users u,")
.append(" sys_users_roles ur,")
.append(" sys_roles_permissions rp,")
.append(" sys_permissions p")
.append(" WHERE")
.append(" u.username =?")
.append(" AND u.id = ur.user_id")
.append(" AND ur.role_id = rp.role_id")
.append(" AND rp.permission_id = p.id");
return new HashSet(jdbcTemplate.queryForList(sb.toString(), String.class, username));
}
}
|
package com.github.lassana.adaptable_layout;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.github.lassana.adaptable_layout.sample.R;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public static class PlaceholderFragment extends Fragment {
private static char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
private Random mRandom = new Random();
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
AdaptableLayout layout = (AdaptableLayout) view.findViewById(R.id.layout);
for (int i = 0; i < 100; ++i) {
Button button = new Button(getActivity());
int length = 5 + mRandom.nextInt(10);
button.setText(randomString(CHARSET_AZ_09, length));
layout.addView(button);
}
}
public String randomString(char[] characterSet, int length) {
char[] result = new char[length];
for (int i = 0; i < result.length; i++) {
result[i] = characterSet[mRandom.nextInt(characterSet.length)];
}
return new String(result);
}
}
}
|
package audioanalyzer.logic.helpers;
import java.util.ArrayList;
import java.util.List;
/**
* Informations about audio stream
*/
public class AudioStreamInfo {
private int m_streamIndex;
private int m_channelsCount;
private int m_sampleRate;
private int m_bitRate;
private String m_codecName;
private String m_channelLayout;
private double m_duration;
private ArrayList<String> m_rawFilePaths;
public AudioStreamInfo(int streamIndex, int channelsCount, int sampleRate, int bitRate, String codecName, String channelLayout, double duration) {
m_streamIndex = streamIndex;
m_channelsCount = channelsCount;
m_sampleRate = sampleRate;
m_bitRate = bitRate;
m_codecName = codecName;
m_channelLayout = channelLayout;
m_duration = duration;
m_rawFilePaths = new ArrayList<String>();
}
public int getStreamIndex() {
return m_streamIndex;
}
public int getChannelsCount() {
return m_channelsCount;
}
public int getSampleRate() {
return m_sampleRate;
}
public int getBitRate() {
return m_bitRate;
}
public String getCodecName() {
return m_codecName;
}
public String getChannelLayout() {
return m_channelLayout;
}
public double getDuration() {
return m_duration;
}
public void setDuration(double value) {
m_duration = value;
}
public long getTotalSamplesCount() {
return (long)Math.round(m_sampleRate * m_duration);
}
public List<String> getRawFilePaths() {
return m_rawFilePaths;
}
public void addRawFilePath(String value) {
m_rawFilePaths.add(value);
}
}
|
package ay2122s1_cs2103t_w16_2.btbb.testutil;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import ay2122s1_cs2103t_w16_2.btbb.model.predicate.StringContainsKeywordsPredicate;
import ay2122s1_cs2103t_w16_2.btbb.model.predicate.ValueInListPredicate;
import ay2122s1_cs2103t_w16_2.btbb.model.predicate.ValueWithinRangePredicate;
import ay2122s1_cs2103t_w16_2.btbb.model.shared.Quantity;
/**
* A utility class for predicates.
*/
public class PredicateUtil {
/**
* Takes a variable number of objects, converts them to string and combines them to one space separated String.
*
* @param objects Objects to be converted to string.
* @return String separating each object's string representation by a space.
*/
public static String makeSpaceSeparatedStringKeywords(Object... objects) {
StringBuilder sb = new StringBuilder();
Arrays.stream(objects).forEach(keyword -> {
sb.append(keyword.toString());
sb.append(" ");
});
return sb.toString().trim();
}
/**
* Makes a {@code ValueInListPredicate} for {@code LocalDate} values.
*
* @param input String input to get keywords from.
* @param getter Getter to get item to test predicate with.
* @param <T> Type of predicate.
* @return {@code ValueInListPredicate} for {@code LocalDate} values.
*/
public static <T> ValueInListPredicate<T, LocalDate> makeLocalDateInListPredicate(String input,
Function<T, LocalDate> getter) {
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("dd-MM-uuuu").withResolverStyle(ResolverStyle.STRICT);
List<String> keywords = List.of(input.split("\\s+"));
List<LocalDate> dates = new ArrayList<>();
for (String keyword : keywords) {
dates.add(LocalDate.parse(keyword, dateTimeFormatter));
}
return new ValueInListPredicate<>(getter, dates);
}
/**
* Makes a {@code ValueInListPredicate} for quantity values.
*
* @param input String input to get keywords from.
* @param getter Getter to get item to test predicate with.
* @param <T> Type of predicate.
* @return {@code ValueInListPredicate} for quantity values.
*/
public static <T> ValueInListPredicate<T, Quantity> makeQuantityInListPredicate(String input,
Function<T, Quantity> getter) {
List<String> keywords = List.of(input.split("\\s+"));
List<Quantity> quantities = new ArrayList<>();
for (String keyword : keywords) {
quantities.add(new Quantity(keyword));
}
return new ValueInListPredicate<>(getter, quantities);
}
/**
* Makes a {@code ValueWithinRangePredicate} for quantity values.
*
* @param minQuantity Minimum quantity to form the lower bound of the range.
* @param maxQuantity Maximum quantity to form the upper bound of the range.
* @param getter Getter to get item to test predicate with.
* @param <T> Type of predicate.
* @return {@code ValueWithinRangePredicate} for quantity values.
*/
public static <T> ValueWithinRangePredicate<T, Quantity> makeQuantityWithinRangePredicate(
String minQuantity,
String maxQuantity,
Function<T, Quantity> getter) {
return new ValueWithinRangePredicate<>(getter,
new Quantity(minQuantity),
new Quantity(maxQuantity));
}
/**
* Parses {@code userInput} into a {@code StringContainsKeywordsPredicate<T>}.
*/
public static <T> StringContainsKeywordsPredicate<T> makeStringContainsKeywordsPredicate(String input,
Function<T, ?> getter) {
List<String> keywords = List.of(input.split("\\s+"));
return new StringContainsKeywordsPredicate<>(getter, keywords);
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.management.resources.models;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.Post;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in Features. */
public final class FeaturesInner {
private final ClientLogger logger = new ClientLogger(FeaturesInner.class);
/** The proxy service used to perform REST calls. */
private final FeaturesService service;
/** The service client containing this operation class. */
private final FeatureClientImpl client;
/**
* Initializes an instance of FeaturesInner.
*
* @param client the instance of the service client containing this operation class.
*/
FeaturesInner(FeatureClientImpl client) {
this.service = RestProxy.create(FeaturesService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for FeatureClientFeatures to be used by the proxy service to perform REST
* calls.
*/
@Host("{$host}")
@ServiceInterface(name = "FeatureClientFeature")
private interface FeaturesService {
@Headers({"Accept: application/json,text/json", "Content-Type: application/json"})
@Get("/subscriptions/{subscriptionId}/providers/Microsoft.Features/features")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<SimpleResponse<FeatureOperationsListResultInner>> listAll(
@HostParam("$host") String host,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json,text/json", "Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers"
+ "/{resourceProviderNamespace}/features")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<SimpleResponse<FeatureOperationsListResultInner>> list(
@HostParam("$host") String host,
@PathParam("resourceProviderNamespace") String resourceProviderNamespace,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json,text/json", "Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers"
+ "/{resourceProviderNamespace}/features/{featureName}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<SimpleResponse<FeatureResultInner>> get(
@HostParam("$host") String host,
@PathParam("resourceProviderNamespace") String resourceProviderNamespace,
@PathParam("featureName") String featureName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json,text/json", "Content-Type: application/json"})
@Post(
"/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers"
+ "/{resourceProviderNamespace}/features/{featureName}/register")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<SimpleResponse<FeatureResultInner>> register(
@HostParam("$host") String host,
@PathParam("resourceProviderNamespace") String resourceProviderNamespace,
@PathParam("featureName") String featureName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json,text/json", "Content-Type: application/json"})
@Post(
"/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers"
+ "/{resourceProviderNamespace}/features/{featureName}/unregister")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<SimpleResponse<FeatureResultInner>> unregister(
@HostParam("$host") String host,
@PathParam("resourceProviderNamespace") String resourceProviderNamespace,
@PathParam("featureName") String featureName,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
Context context);
@Headers({"Accept: application/json,text/json", "Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<SimpleResponse<FeatureOperationsListResultInner>> listAllNext(
@PathParam(value = "nextLink", encoded = true) String nextLink, Context context);
@Headers({"Accept: application/json,text/json", "Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<SimpleResponse<FeatureOperationsListResultInner>> listNext(
@PathParam(value = "nextLink", encoded = true) String nextLink, Context context);
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PagedResponse<FeatureResultInner>> listAllSinglePageAsync() {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return FluxUtil
.withContext(
context ->
service
.listAll(
this.client.getHost(),
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context))
.<PagedResponse<FeatureResultInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PagedResponse<FeatureResultInner>> listAllSinglePageAsync(Context context) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return service
.listAll(this.client.getHost(), this.client.getApiVersion(), this.client.getSubscriptionId(), context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FeatureResultInner> listAllAsync() {
return new PagedFlux<>(() -> listAllSinglePageAsync(), nextLink -> listAllNextSinglePageAsync(nextLink));
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FeatureResultInner> listAllAsync(Context context) {
return new PagedFlux<>(() -> listAllSinglePageAsync(context), nextLink -> listAllNextSinglePageAsync(nextLink));
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<FeatureResultInner> listAll() {
return new PagedIterable<>(listAllAsync());
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features in a provider namespace that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PagedResponse<FeatureResultInner>> listSinglePageAsync(String resourceProviderNamespace) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (resourceProviderNamespace == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter resourceProviderNamespace is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return FluxUtil
.withContext(
context ->
service
.list(
this.client.getHost(),
resourceProviderNamespace,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context))
.<PagedResponse<FeatureResultInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features in a provider namespace that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PagedResponse<FeatureResultInner>> listSinglePageAsync(
String resourceProviderNamespace, Context context) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (resourceProviderNamespace == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter resourceProviderNamespace is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return service
.list(
this.client.getHost(),
resourceProviderNamespace,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features in a provider namespace that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FeatureResultInner> listAsync(String resourceProviderNamespace) {
return new PagedFlux<>(
() -> listSinglePageAsync(resourceProviderNamespace), nextLink -> listNextSinglePageAsync(nextLink));
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features in a provider namespace that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<FeatureResultInner> listAsync(String resourceProviderNamespace, Context context) {
return new PagedFlux<>(
() -> listSinglePageAsync(resourceProviderNamespace, context),
nextLink -> listNextSinglePageAsync(nextLink));
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the preview features in a provider namespace that are available through AFEC for the subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<FeatureResultInner> list(String resourceProviderNamespace) {
return new PagedIterable<>(listAsync(resourceProviderNamespace));
}
/**
* Gets the preview feature with the specified name.
*
* @param resourceProviderNamespace The resource provider namespace for the feature.
* @param featureName The name of the feature to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the preview feature with the specified name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SimpleResponse<FeatureResultInner>> getWithResponseAsync(
String resourceProviderNamespace, String featureName) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (resourceProviderNamespace == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter resourceProviderNamespace is required and cannot be null."));
}
if (featureName == null) {
return Mono.error(new IllegalArgumentException("Parameter featureName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return FluxUtil
.withContext(
context ->
service
.get(
this.client.getHost(),
resourceProviderNamespace,
featureName,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets the preview feature with the specified name.
*
* @param resourceProviderNamespace The resource provider namespace for the feature.
* @param featureName The name of the feature to get.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the preview feature with the specified name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SimpleResponse<FeatureResultInner>> getWithResponseAsync(
String resourceProviderNamespace, String featureName, Context context) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (resourceProviderNamespace == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter resourceProviderNamespace is required and cannot be null."));
}
if (featureName == null) {
return Mono.error(new IllegalArgumentException("Parameter featureName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return service
.get(
this.client.getHost(),
resourceProviderNamespace,
featureName,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context);
}
/**
* Gets the preview feature with the specified name.
*
* @param resourceProviderNamespace The resource provider namespace for the feature.
* @param featureName The name of the feature to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the preview feature with the specified name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<FeatureResultInner> getAsync(String resourceProviderNamespace, String featureName) {
return getWithResponseAsync(resourceProviderNamespace, featureName)
.flatMap(
(SimpleResponse<FeatureResultInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Gets the preview feature with the specified name.
*
* @param resourceProviderNamespace The resource provider namespace for the feature.
* @param featureName The name of the feature to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the preview feature with the specified name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public FeatureResultInner get(String resourceProviderNamespace, String featureName) {
return getAsync(resourceProviderNamespace, featureName).block();
}
/**
* Registers the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to register.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return previewed feature information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SimpleResponse<FeatureResultInner>> registerWithResponseAsync(
String resourceProviderNamespace, String featureName) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (resourceProviderNamespace == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter resourceProviderNamespace is required and cannot be null."));
}
if (featureName == null) {
return Mono.error(new IllegalArgumentException("Parameter featureName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return FluxUtil
.withContext(
context ->
service
.register(
this.client.getHost(),
resourceProviderNamespace,
featureName,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Registers the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to register.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return previewed feature information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SimpleResponse<FeatureResultInner>> registerWithResponseAsync(
String resourceProviderNamespace, String featureName, Context context) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (resourceProviderNamespace == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter resourceProviderNamespace is required and cannot be null."));
}
if (featureName == null) {
return Mono.error(new IllegalArgumentException("Parameter featureName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return service
.register(
this.client.getHost(),
resourceProviderNamespace,
featureName,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context);
}
/**
* Registers the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to register.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return previewed feature information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<FeatureResultInner> registerAsync(String resourceProviderNamespace, String featureName) {
return registerWithResponseAsync(resourceProviderNamespace, featureName)
.flatMap(
(SimpleResponse<FeatureResultInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Registers the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to register.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return previewed feature information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public FeatureResultInner register(String resourceProviderNamespace, String featureName) {
return registerAsync(resourceProviderNamespace, featureName).block();
}
/**
* Unregisters the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to unregister.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return previewed feature information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SimpleResponse<FeatureResultInner>> unregisterWithResponseAsync(
String resourceProviderNamespace, String featureName) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (resourceProviderNamespace == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter resourceProviderNamespace is required and cannot be null."));
}
if (featureName == null) {
return Mono.error(new IllegalArgumentException("Parameter featureName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return FluxUtil
.withContext(
context ->
service
.unregister(
this.client.getHost(),
resourceProviderNamespace,
featureName,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Unregisters the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to unregister.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return previewed feature information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SimpleResponse<FeatureResultInner>> unregisterWithResponseAsync(
String resourceProviderNamespace, String featureName, Context context) {
if (this.client.getHost() == null) {
return Mono
.error(new IllegalArgumentException("Parameter this.client.getHost() is required and cannot be null."));
}
if (resourceProviderNamespace == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter resourceProviderNamespace is required and cannot be null."));
}
if (featureName == null) {
return Mono.error(new IllegalArgumentException("Parameter featureName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
return service
.unregister(
this.client.getHost(),
resourceProviderNamespace,
featureName,
this.client.getApiVersion(),
this.client.getSubscriptionId(),
context);
}
/**
* Unregisters the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to unregister.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return previewed feature information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<FeatureResultInner> unregisterAsync(String resourceProviderNamespace, String featureName) {
return unregisterWithResponseAsync(resourceProviderNamespace, featureName)
.flatMap(
(SimpleResponse<FeatureResultInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Unregisters the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to unregister.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return previewed feature information.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public FeatureResultInner unregister(String resourceProviderNamespace, String featureName) {
return unregisterAsync(resourceProviderNamespace, featureName).block();
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of previewed features.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PagedResponse<FeatureResultInner>> listAllNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
return FluxUtil
.withContext(context -> service.listAllNext(nextLink, context))
.<PagedResponse<FeatureResultInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of previewed features.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PagedResponse<FeatureResultInner>> listAllNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
return service
.listAllNext(nextLink, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of previewed features.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PagedResponse<FeatureResultInner>> listNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
return FluxUtil
.withContext(context -> service.listNext(nextLink, context))
.<PagedResponse<FeatureResultInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of previewed features.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<PagedResponse<FeatureResultInner>> listNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
return service
.listNext(nextLink, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
}
|
package io.seata.sample.controller;
import io.seata.sample.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author dinghuang123@gmail.com
* @date 2019/06/14
*/
@RestController
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/reduce")
public Boolean debit(String userId, int money) {
accountService.reduce(userId, money);
return true;
}
}
|
package com.otaliastudios.cameraview;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.location.Location;
import android.media.MediaActionSound;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Control;
import com.otaliastudios.cameraview.controls.ControlParser;
import com.otaliastudios.cameraview.controls.Engine;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Grid;
import com.otaliastudios.cameraview.controls.Hdr;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.controls.PictureFormat;
import com.otaliastudios.cameraview.controls.Preview;
import com.otaliastudios.cameraview.controls.VideoCodec;
import com.otaliastudios.cameraview.controls.WhiteBalance;
import com.otaliastudios.cameraview.engine.Camera1Engine;
import com.otaliastudios.cameraview.engine.Camera2Engine;
import com.otaliastudios.cameraview.engine.CameraBaseEngine;
import com.otaliastudios.cameraview.engine.CameraEngine;
import com.otaliastudios.cameraview.engine.offset.Reference;
import com.otaliastudios.cameraview.engine.orchestrator.CameraState;
import com.otaliastudios.cameraview.filter.Filter;
import com.otaliastudios.cameraview.filter.FilterParser;
import com.otaliastudios.cameraview.filter.Filters;
import com.otaliastudios.cameraview.filter.NoFilter;
import com.otaliastudios.cameraview.filter.OneParameterFilter;
import com.otaliastudios.cameraview.filter.TwoParameterFilter;
import com.otaliastudios.cameraview.frame.Frame;
import com.otaliastudios.cameraview.frame.FrameProcessor;
import com.otaliastudios.cameraview.gesture.Gesture;
import com.otaliastudios.cameraview.gesture.GestureAction;
import com.otaliastudios.cameraview.gesture.GestureFinder;
import com.otaliastudios.cameraview.gesture.GestureParser;
import com.otaliastudios.cameraview.gesture.PinchGestureFinder;
import com.otaliastudios.cameraview.gesture.ScrollGestureFinder;
import com.otaliastudios.cameraview.gesture.TapGestureFinder;
import com.otaliastudios.cameraview.internal.GridLinesLayout;
import com.otaliastudios.cameraview.internal.CropHelper;
import com.otaliastudios.cameraview.internal.OrientationHelper;
import com.otaliastudios.cameraview.markers.AutoFocusMarker;
import com.otaliastudios.cameraview.markers.AutoFocusTrigger;
import com.otaliastudios.cameraview.markers.MarkerLayout;
import com.otaliastudios.cameraview.markers.MarkerParser;
import com.otaliastudios.cameraview.metering.MeteringRegions;
import com.otaliastudios.cameraview.overlay.OverlayLayout;
import com.otaliastudios.cameraview.preview.CameraPreview;
import com.otaliastudios.cameraview.preview.FilterCameraPreview;
import com.otaliastudios.cameraview.preview.GlCameraPreview;
import com.otaliastudios.cameraview.preview.SurfaceCameraPreview;
import com.otaliastudios.cameraview.preview.TextureCameraPreview;
import com.otaliastudios.cameraview.size.AspectRatio;
import com.otaliastudios.cameraview.size.Size;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectorParser;
import com.otaliastudios.cameraview.size.SizeSelectors;
import java.io.File;
import java.io.FileDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static android.view.View.MeasureSpec.AT_MOST;
import static android.view.View.MeasureSpec.EXACTLY;
import static android.view.View.MeasureSpec.UNSPECIFIED;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
/**
* Entry point for the whole library.
* Please read documentation for usage and full set of features.
*/
public class CameraView extends FrameLayout implements LifecycleObserver {
private final static String TAG = CameraView.class.getSimpleName();
private static final CameraLogger LOG = CameraLogger.create(TAG);
public final static int PERMISSION_REQUEST_CODE = 16;
final static long DEFAULT_AUTOFOCUS_RESET_DELAY_MILLIS = 3000;
final static boolean DEFAULT_PLAY_SOUNDS = true;
final static boolean DEFAULT_USE_DEVICE_ORIENTATION = true;
final static boolean DEFAULT_PICTURE_METERING = true;
final static boolean DEFAULT_PICTURE_SNAPSHOT_METERING = false;
final static boolean DEFAULT_REQUEST_PERMISSIONS = true;
final static int DEFAULT_FRAME_PROCESSING_POOL_SIZE = 2;
final static int DEFAULT_FRAME_PROCESSING_EXECUTORS = 1;
private DisplayOrientationDetector mDisplayOrientationDetector;
// Self managed parameters
private boolean mPlaySounds;
private boolean mUseDeviceOrientation;
private boolean mRequestPermissions;
private HashMap<Gesture, GestureAction> mGestureMap = new HashMap<>(4);
private Preview mPreview;
private Engine mEngine;
private Filter mPendingFilter;
private int mFrameProcessingExecutors;
// Components
private Handler mUiHandler;
private Executor mFrameProcessingExecutor;
@VisibleForTesting CameraCallbacks mCameraCallbacks;
private CameraPreview mCameraPreview;
private OrientationHelper mOrientationHelper;
private CameraEngine mCameraEngine;
private Size mLastPreviewStreamSize;
private MediaActionSound mSound;
private AutoFocusMarker mAutoFocusMarker;
@VisibleForTesting List<CameraListener> mListeners = new CopyOnWriteArrayList<>();
@VisibleForTesting List<FrameProcessor> mFrameProcessors = new CopyOnWriteArrayList<>();
private Lifecycle mLifecycle;
// Gestures
@VisibleForTesting PinchGestureFinder mPinchGestureFinder;
@VisibleForTesting TapGestureFinder mTapGestureFinder;
@VisibleForTesting ScrollGestureFinder mScrollGestureFinder;
// Views
@VisibleForTesting GridLinesLayout mGridLinesLayout;
@VisibleForTesting MarkerLayout mMarkerLayout;
private boolean mKeepScreenOn;
@SuppressWarnings({"FieldCanBeLocal", "unused"})
private boolean mExperimental;
private boolean mInEditor;
private int dispOrientation = 0;
private int devOrientation = 0;
// Overlays
@VisibleForTesting OverlayLayout mOverlayLayout;
public CameraView(@NonNull Context context) {
super(context, null);
initialize(context, null);
}
public CameraView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initialize(context, attrs);
}
//region Init
@SuppressWarnings("WrongConstant")
private void initialize(@NonNull Context context, @Nullable AttributeSet attrs) {
mInEditor = isInEditMode();
if (mInEditor) return;
setWillNotDraw(false);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CameraView,
0, 0);
ControlParser controls = new ControlParser(context, a);
// Self managed
boolean playSounds = a.getBoolean(R.styleable.CameraView_cameraPlaySounds,
DEFAULT_PLAY_SOUNDS);
boolean useDeviceOrientation = a.getBoolean(
R.styleable.CameraView_cameraUseDeviceOrientation, DEFAULT_USE_DEVICE_ORIENTATION);
mExperimental = a.getBoolean(R.styleable.CameraView_cameraExperimental, false);
mRequestPermissions = a.getBoolean(R.styleable.CameraView_cameraRequestPermissions,
DEFAULT_REQUEST_PERMISSIONS);
mPreview = controls.getPreview();
mEngine = controls.getEngine();
// Camera engine params
int gridColor = a.getColor(R.styleable.CameraView_cameraGridColor,
GridLinesLayout.DEFAULT_COLOR);
long videoMaxSize = (long) a.getFloat(R.styleable.CameraView_cameraVideoMaxSize,
0);
int videoMaxDuration = a.getInteger(R.styleable.CameraView_cameraVideoMaxDuration,
0);
int videoBitRate = a.getInteger(R.styleable.CameraView_cameraVideoBitRate, 0);
int audioBitRate = a.getInteger(R.styleable.CameraView_cameraAudioBitRate, 0);
float videoFrameRate = a.getFloat(R.styleable.CameraView_cameraPreviewFrameRate, 0);
boolean videoFrameRateExact = a.getBoolean(R.styleable.CameraView_cameraPreviewFrameRateExact, false);
long autoFocusResetDelay = (long) a.getInteger(
R.styleable.CameraView_cameraAutoFocusResetDelay,
(int) DEFAULT_AUTOFOCUS_RESET_DELAY_MILLIS);
boolean pictureMetering = a.getBoolean(R.styleable.CameraView_cameraPictureMetering,
DEFAULT_PICTURE_METERING);
boolean pictureSnapshotMetering = a.getBoolean(
R.styleable.CameraView_cameraPictureSnapshotMetering,
DEFAULT_PICTURE_SNAPSHOT_METERING);
int snapshotMaxWidth = a.getInteger(R.styleable.CameraView_cameraSnapshotMaxWidth, 0);
int snapshotMaxHeight = a.getInteger(R.styleable.CameraView_cameraSnapshotMaxHeight, 0);
int frameMaxWidth = a.getInteger(R.styleable.CameraView_cameraFrameProcessingMaxWidth, 0);
int frameMaxHeight = a.getInteger(R.styleable.CameraView_cameraFrameProcessingMaxHeight, 0);
int frameFormat = a.getInteger(R.styleable.CameraView_cameraFrameProcessingFormat, 0);
int framePoolSize = a.getInteger(R.styleable.CameraView_cameraFrameProcessingPoolSize,
DEFAULT_FRAME_PROCESSING_POOL_SIZE);
int frameExecutors = a.getInteger(R.styleable.CameraView_cameraFrameProcessingExecutors,
DEFAULT_FRAME_PROCESSING_EXECUTORS);
// Size selectors and gestures
SizeSelectorParser sizeSelectors = new SizeSelectorParser(a);
GestureParser gestures = new GestureParser(a);
MarkerParser markers = new MarkerParser(a);
FilterParser filters = new FilterParser(a);
a.recycle();
// Components
mCameraCallbacks = new CameraCallbacks();
mUiHandler = new Handler(Looper.getMainLooper());
// Gestures
mPinchGestureFinder = new PinchGestureFinder(mCameraCallbacks);
mTapGestureFinder = new TapGestureFinder(mCameraCallbacks);
mScrollGestureFinder = new ScrollGestureFinder(mCameraCallbacks);
// Views
mGridLinesLayout = new GridLinesLayout(context);
mOverlayLayout = new OverlayLayout(context);
mMarkerLayout = new MarkerLayout(context);
addView(mGridLinesLayout);
addView(mMarkerLayout);
addView(mOverlayLayout);
// Create the engine
doInstantiateEngine();
// Apply self managed
setPlaySounds(playSounds);
setUseDeviceOrientation(useDeviceOrientation);
setGrid(controls.getGrid());
setGridColor(gridColor);
// Apply camera engine params
// Adding new ones? See setEngine().
setFacing(controls.getFacing());
setFlash(controls.getFlash());
setMode(controls.getMode());
setWhiteBalance(controls.getWhiteBalance());
setHdr(controls.getHdr());
setAudio(controls.getAudio());
setAudioBitRate(audioBitRate);
setPictureSize(sizeSelectors.getPictureSizeSelector());
setPictureMetering(pictureMetering);
setPictureSnapshotMetering(pictureSnapshotMetering);
setPictureFormat(controls.getPictureFormat());
setVideoSize(sizeSelectors.getVideoSizeSelector());
setVideoCodec(controls.getVideoCodec());
setVideoMaxSize(videoMaxSize);
setVideoMaxDuration(videoMaxDuration);
setVideoBitRate(videoBitRate);
setAutoFocusResetDelay(autoFocusResetDelay);
setPreviewFrameRateExact(videoFrameRateExact);
setPreviewFrameRate(videoFrameRate);
setSnapshotMaxWidth(snapshotMaxWidth);
setSnapshotMaxHeight(snapshotMaxHeight);
setFrameProcessingMaxWidth(frameMaxWidth);
setFrameProcessingMaxHeight(frameMaxHeight);
setFrameProcessingFormat(frameFormat);
setFrameProcessingPoolSize(framePoolSize);
setFrameProcessingExecutors(frameExecutors);
// Apply gestures
mapGesture(Gesture.TAP, gestures.getTapAction());
mapGesture(Gesture.LONG_TAP, gestures.getLongTapAction());
mapGesture(Gesture.PINCH, gestures.getPinchAction());
mapGesture(Gesture.SCROLL_HORIZONTAL, gestures.getHorizontalScrollAction());
mapGesture(Gesture.SCROLL_VERTICAL, gestures.getVerticalScrollAction());
// Apply markers
setAutoFocusMarker(markers.getAutoFocusMarker());
// Apply filters
setFilter(filters.getFilter());
// Create the orientation helper
mOrientationHelper = new OrientationHelper(context, mCameraCallbacks);
mDisplayOrientationDetector = new DisplayOrientationDetector(context) {
@Override
public void onDisplayOrDeviceOrientationChanged(int displayOrientation, int deviceOrientation) {
CameraView.this.dispOrientation = displayOrientation;
CameraView.this.devOrientation = devOrientation;
}
};
}
/**
* Engine is instantiated on creation and anytime
* {@link #setEngine(Engine)} is called.
*/
private void doInstantiateEngine() {
LOG.w("doInstantiateEngine:", "instantiating. engine:", mEngine);
mCameraEngine = instantiateCameraEngine(mEngine, mCameraCallbacks);
LOG.w("doInstantiateEngine:", "instantiated. engine:",
mCameraEngine.getClass().getSimpleName());
mCameraEngine.setOverlay(mOverlayLayout);
}
/**
* Preview is instantiated {@link #onAttachedToWindow()}, because
* we want to know if we're hardware accelerated or not.
* However, in tests, we might want to create the preview right after constructor.
*/
@VisibleForTesting
void doInstantiatePreview() {
LOG.w("doInstantiateEngine:", "instantiating. preview:", mPreview);
mCameraPreview = instantiatePreview(mPreview, getContext(), this);
LOG.w("doInstantiateEngine:", "instantiated. preview:",
mCameraPreview.getClass().getSimpleName());
mCameraEngine.setPreview(mCameraPreview);
if (mPendingFilter != null) {
setFilter(mPendingFilter);
mPendingFilter = null;
}
}
/**
* Instantiates the camera engine.
*
* @param engine the engine preference
* @param callback the engine callback
* @return the engine
*/
@NonNull
protected CameraEngine instantiateCameraEngine(@NonNull Engine engine,
@NonNull CameraEngine.Callback callback) {
if (mExperimental
&& engine == Engine.CAMERA2
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new Camera2Engine(callback, new CameraBaseEngine.OrientationProvider() {
@Override public int deviceOrientation() {
return devOrientation;
}
@Override public int displayOrientaion() {
return dispOrientation;
}
});
} else {
mEngine = Engine.CAMERA1;
return new Camera1Engine(callback, new CameraBaseEngine.OrientationProvider() {
@Override public int deviceOrientation() {
return devOrientation;
}
@Override public int displayOrientaion() {
return dispOrientation;
}
});
}
}
public void setDispOrientation(int dispOrientation) {
this.dispOrientation = dispOrientation;
}
public void setDevOrientation(int devOrientation) {
this.devOrientation = devOrientation;
}
/**
* Instantiates the camera preview.
*
* @param preview current preview value
* @param context a context
* @param container the container
* @return the preview
*/
@NonNull
protected CameraPreview instantiatePreview(@NonNull Preview preview,
@NonNull Context context,
@NonNull ViewGroup container) {
switch (preview) {
case SURFACE:
return new SurfaceCameraPreview(context, container);
case TEXTURE: {
if (isHardwareAccelerated()) {
// TextureView is not supported without hardware acceleration.
return new TextureCameraPreview(context, container);
}
}
case GL_SURFACE: default: {
mPreview = Preview.GL_SURFACE;
return new GlCameraPreview(context, container);
}
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mInEditor) return;
if (mCameraPreview == null) {
// isHardwareAccelerated will return the real value only after we are
// attached. That's why we instantiate the preview here.
doInstantiatePreview();
}
mOrientationHelper.enable();
}
@Override
protected void onDetachedFromWindow() {
if (!mInEditor) mOrientationHelper.disable();
mLastPreviewStreamSize = null;
super.onDetachedFromWindow();
}
//endregion
//region Measuring behavior
private String ms(int mode) {
switch (mode) {
case AT_MOST: return "AT_MOST";
case EXACTLY: return "EXACTLY";
case UNSPECIFIED: return "UNSPECIFIED";
}
return null;
}
/**
* Measuring is basically controlled by layout params width and height.
* The basic semantics are:
*
* - MATCH_PARENT: CameraView should completely fill this dimension, even if this might mean
* not respecting the preview aspect ratio.
* - WRAP_CONTENT: CameraView should try to adapt this dimension to respect the preview
* aspect ratio.
*
* When both dimensions are MATCH_PARENT, CameraView will fill its
* parent no matter the preview. Thanks to what happens in {@link CameraPreview}, this acts like
* a CENTER CROP scale type.
*
* When both dimensions are WRAP_CONTENT, CameraView will take the biggest dimensions that
* fit the preview aspect ratio. This acts like a CENTER INSIDE scale type.
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mInEditor) {
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int height = MeasureSpec.getSize(heightMeasureSpec);
super.onMeasure(MeasureSpec.makeMeasureSpec(width, EXACTLY),
MeasureSpec.makeMeasureSpec(height, EXACTLY));
return;
}
mLastPreviewStreamSize = mCameraEngine.getPreviewStreamSize(Reference.VIEW);
if (mLastPreviewStreamSize == null) {
LOG.w("onMeasure:", "surface is not ready. Calling default behavior.");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// Let's which dimensions need to be adapted.
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int widthValue = MeasureSpec.getSize(widthMeasureSpec);
final int heightValue = MeasureSpec.getSize(heightMeasureSpec);
final float previewWidth = mLastPreviewStreamSize.getWidth();
final float previewHeight = mLastPreviewStreamSize.getHeight();
// Pre-process specs
final ViewGroup.LayoutParams lp = getLayoutParams();
if (!mCameraPreview.supportsCropping()) {
// We can't allow EXACTLY constraints in this case.
if (widthMode == EXACTLY) widthMode = AT_MOST;
if (heightMode == EXACTLY) heightMode = AT_MOST;
} else {
// If MATCH_PARENT is interpreted as AT_MOST, transform to EXACTLY
// to be consistent with our semantics (and our docs).
if (widthMode == AT_MOST && lp.width == MATCH_PARENT) widthMode = EXACTLY;
if (heightMode == AT_MOST && lp.height == MATCH_PARENT) heightMode = EXACTLY;
}
LOG.i("onMeasure:", "requested dimensions are ("
+ widthValue + "[" + ms(widthMode) + "]x"
+ heightValue + "[" + ms(heightMode) + "])");
LOG.i("onMeasure:", "previewSize is", "("
+ previewWidth + "x" + previewHeight + ")");
// (1) If we have fixed dimensions (either 300dp or MATCH_PARENT), there's nothing we
// should do, other than respect it. The preview will eventually be cropped at the sides
// (by Preview scaling) except the case in which these fixed dimensions manage to fit
// exactly the preview aspect ratio.
if (widthMode == EXACTLY && heightMode == EXACTLY) {
LOG.i("onMeasure:", "both are MATCH_PARENT or fixed value. We adapt.",
"This means CROP_CENTER.", "(" + widthValue + "x" + heightValue + ")");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// (2) If both dimensions are free, with no limits, then our size will be exactly the
// preview size. This can happen rarely, for example in 2d scrollable containers.
if (widthMode == UNSPECIFIED && heightMode == UNSPECIFIED) {
LOG.i("onMeasure:", "both are completely free.",
"We respect that and extend to the whole preview size.",
"(" + previewWidth + "x" + previewHeight + ")");
super.onMeasure(
MeasureSpec.makeMeasureSpec((int) previewWidth, EXACTLY),
MeasureSpec.makeMeasureSpec((int) previewHeight, EXACTLY));
return;
}
// It's sure now that at least one dimension can be determined (either because EXACTLY
// or AT_MOST). This starts to seem a pleasant situation.
// (3) If one of the dimension is completely free (e.g. in a scrollable container),
// take the other and fit the ratio.
// One of the two might be AT_MOST, but we use the value anyway.
float ratio = previewHeight / previewWidth;
if (widthMode == UNSPECIFIED || heightMode == UNSPECIFIED) {
boolean freeWidth = widthMode == UNSPECIFIED;
int height, width;
if (freeWidth) {
height = heightValue;
width = Math.round(height / ratio);
} else {
width = widthValue;
height = Math.round(width * ratio);
}
LOG.i("onMeasure:", "one dimension was free, we adapted it to fit the ratio.",
"(" + width + "x" + height + ")");
super.onMeasure(MeasureSpec.makeMeasureSpec(width, EXACTLY),
MeasureSpec.makeMeasureSpec(height, EXACTLY));
return;
}
// (4) At this point both dimensions are either AT_MOST-AT_MOST, EXACTLY-AT_MOST or
// AT_MOST-EXACTLY. Let's manage this sanely. If only one is EXACTLY, we can TRY to fit
// the aspect ratio, but it is not guaranteed to succeed. It depends on the AT_MOST
// value of the other dimensions.
if (widthMode == EXACTLY || heightMode == EXACTLY) {
boolean freeWidth = widthMode == AT_MOST;
int height, width;
if (freeWidth) {
height = heightValue;
width = Math.min(Math.round(height / ratio), widthValue);
} else {
width = widthValue;
height = Math.min(Math.round(width * ratio), heightValue);
}
LOG.i("onMeasure:", "one dimension was EXACTLY, another AT_MOST.",
"We have TRIED to fit the aspect ratio, but it's not guaranteed.",
"(" + width + "x" + height + ")");
super.onMeasure(MeasureSpec.makeMeasureSpec(width, EXACTLY),
MeasureSpec.makeMeasureSpec(height, EXACTLY));
return;
}
// (5) Last case, AT_MOST and AT_MOST. Here we can SURELY fit the aspect ratio by
// filling one dimension and adapting the other.
int height, width;
float atMostRatio = (float) heightValue / (float) widthValue;
if (atMostRatio >= ratio) {
// We must reduce height.
width = widthValue;
height = Math.round(width * ratio);
} else {
height = heightValue;
width = Math.round(height / ratio);
}
LOG.i("onMeasure:", "both dimension were AT_MOST.",
"We fit the preview aspect ratio.",
"(" + width + "x" + height + ")");
super.onMeasure(MeasureSpec.makeMeasureSpec(width, EXACTLY),
MeasureSpec.makeMeasureSpec(height, EXACTLY));
}
//endregion
//region Gesture APIs
/**
* Maps a {@link Gesture} to a certain gesture action.
* For example, you can assign zoom control to the pinch gesture by just calling:
* <code>
* cameraView.mapGesture(Gesture.PINCH, GestureAction.ZOOM);
* </code>
*
* Not all actions can be assigned to a certain gesture. For example, zoom control can't be
* assigned to the Gesture.TAP gesture. Look at {@link Gesture} to know more.
* This method returns false if they are not assignable.
*
* @param gesture which gesture to map
* @param action which action should be assigned
* @return true if this action could be assigned to this gesture
*/
public boolean mapGesture(@NonNull Gesture gesture, @NonNull GestureAction action) {
GestureAction none = GestureAction.NONE;
if (gesture.isAssignableTo(action)) {
mGestureMap.put(gesture, action);
switch (gesture) {
case PINCH:
mPinchGestureFinder.setActive(mGestureMap.get(Gesture.PINCH) != none);
break;
case TAP:
// case DOUBLE_TAP:
case LONG_TAP:
mTapGestureFinder.setActive(
mGestureMap.get(Gesture.TAP) != none ||
// mGestureMap.get(Gesture.DOUBLE_TAP) != none ||
mGestureMap.get(Gesture.LONG_TAP) != none);
break;
case SCROLL_HORIZONTAL:
case SCROLL_VERTICAL:
mScrollGestureFinder.setActive(
mGestureMap.get(Gesture.SCROLL_HORIZONTAL) != none ||
mGestureMap.get(Gesture.SCROLL_VERTICAL) != none);
break;
}
return true;
}
mapGesture(gesture, none);
return false;
}
/**
* Clears any action mapped to the given gesture.
* @param gesture which gesture to clear
*/
public void clearGesture(@NonNull Gesture gesture) {
mapGesture(gesture, GestureAction.NONE);
}
/**
* Returns the action currently mapped to the given gesture.
*
* @param gesture which gesture to inspect
* @return mapped action
*/
@NonNull
public GestureAction getGestureAction(@NonNull Gesture gesture) {
//noinspection ConstantConditions
return mGestureMap.get(gesture);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true; // Steal our own events.
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isOpened()) return true;
// Pass to our own GestureLayouts
CameraOptions options = mCameraEngine.getCameraOptions(); // Non null
if (options == null) throw new IllegalStateException("Options should not be null here.");
if (mPinchGestureFinder.onTouchEvent(event)) {
LOG.i("onTouchEvent", "pinch!");
onGesture(mPinchGestureFinder, options);
} else if (mScrollGestureFinder.onTouchEvent(event)) {
LOG.i("onTouchEvent", "scroll!");
onGesture(mScrollGestureFinder, options);
} else if (mTapGestureFinder.onTouchEvent(event)) {
LOG.i("onTouchEvent", "tap!");
onGesture(mTapGestureFinder, options);
}
return true;
}
// Some gesture layout detected a gesture. It's not known at this moment:
// (1) if it was mapped to some action (we check here)
// (2) if it's supported by the camera (CameraEngine checks)
private void onGesture(@NonNull GestureFinder source, @NonNull CameraOptions options) {
Gesture gesture = source.getGesture();
GestureAction action = mGestureMap.get(gesture);
PointF[] points = source.getPoints();
float oldValue, newValue;
//noinspection ConstantConditions
switch (action) {
case TAKE_PICTURE:
takePicture();
break;
case AUTO_FOCUS:
Size size = new Size(getWidth(), getHeight());
MeteringRegions regions = MeteringRegions.fromPoint(size, points[0]);
mCameraEngine.startAutoFocus(gesture, regions, points[0]);
break;
case ZOOM:
oldValue = mCameraEngine.getZoomValue();
newValue = source.computeValue(oldValue, 0, 1);
if (newValue != oldValue) {
mCameraEngine.setZoom(newValue, points, true);
}
break;
case EXPOSURE_CORRECTION:
oldValue = mCameraEngine.getExposureCorrectionValue();
float minValue = options.getExposureCorrectionMinValue();
float maxValue = options.getExposureCorrectionMaxValue();
newValue = source.computeValue(oldValue, minValue, maxValue);
if (newValue != oldValue) {
float[] bounds = new float[]{minValue, maxValue};
mCameraEngine.setExposureCorrection(newValue, bounds, points, true);
}
break;
case FILTER_CONTROL_1:
if (getFilter() instanceof OneParameterFilter) {
OneParameterFilter filter = (OneParameterFilter) getFilter();
oldValue = filter.getParameter1();
newValue = source.computeValue(oldValue, 0, 1);
if (newValue != oldValue) {
filter.setParameter1(newValue);
}
}
break;
case FILTER_CONTROL_2:
if (getFilter() instanceof TwoParameterFilter) {
TwoParameterFilter filter = (TwoParameterFilter) getFilter();
oldValue = filter.getParameter2();
newValue = source.computeValue(oldValue, 0, 1);
if (newValue != oldValue) {
filter.setParameter2(newValue);
}
}
break;
}
}
//endregion
//region Lifecycle APIs
/**
* Returns whether the camera engine has started.
* @return whether the camera has started
*/
public boolean isOpened() {
return mCameraEngine.getState().isAtLeast(CameraState.ENGINE)
&& mCameraEngine.getTargetState().isAtLeast(CameraState.ENGINE);
}
private boolean isClosed() {
return mCameraEngine.getState() == CameraState.OFF
&& !mCameraEngine.isChangingState();
}
/**
* Sets the lifecycle owner for this view. This means you don't need
* to call {@link #open()}, {@link #close()} or {@link #destroy()} at all.
*
* @param owner the owner activity or fragment
*/
public void setLifecycleOwner(@NonNull LifecycleOwner owner) {
if (mLifecycle != null) mLifecycle.removeObserver(this);
mLifecycle = owner.getLifecycle();
mLifecycle.addObserver(this);
}
/**
* Starts the camera preview, if not started already.
* This should be called onResume(), or when you are ready with permissions.
*/
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void open() {
if (mInEditor) return;
if (mCameraPreview != null) mCameraPreview.onResume();
if (checkPermissions(getAudio())) {
// Update display orientation for current CameraEngine
mOrientationHelper.enable();
mCameraEngine.getAngles().setDisplayOffset(mOrientationHelper.getLastDisplayOffset());
mCameraEngine.start();
}
}
/**
* Checks that we have appropriate permissions.
* This means checking that we have audio permissions if audio = Audio.ON.
* @param audio the audio setting to be checked
* @return true if we can go on, false otherwise.
*/
@SuppressWarnings("ConstantConditions")
@SuppressLint("NewApi")
protected boolean checkPermissions(@NonNull Audio audio) {
checkPermissionsManifestOrThrow(audio);
// Manifest is OK at this point. Let's check runtime permissions.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true;
Context c = getContext();
boolean needsCamera = true;
boolean needsAudio = audio == Audio.ON || audio == Audio.MONO || audio == Audio.STEREO;
needsCamera = needsCamera && c.checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED;
needsAudio = needsAudio && c.checkSelfPermission(Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED;
if (!needsCamera && !needsAudio) {
return true;
} else if (mRequestPermissions) {
requestPermissions(needsCamera, needsAudio);
return false;
} else {
return false;
}
}
/**
* If audio is on we will ask for RECORD_AUDIO permission.
* If the developer did not add this to its manifest, throw and fire warnings.
*/
private void checkPermissionsManifestOrThrow(@NonNull Audio audio) {
if (audio == Audio.ON || audio == Audio.MONO || audio == Audio.STEREO) {
try {
PackageManager manager = getContext().getPackageManager();
PackageInfo info = manager.getPackageInfo(getContext().getPackageName(),
PackageManager.GET_PERMISSIONS);
for (String requestedPermission : info.requestedPermissions) {
if (requestedPermission.equals(Manifest.permission.RECORD_AUDIO)) {
return;
}
}
String message = LOG.e("Permission error: when audio is enabled (Audio.ON)" +
" the RECORD_AUDIO permission should be added to the app manifest file.");
throw new IllegalStateException(message);
} catch (PackageManager.NameNotFoundException e) {
// Not possible.
}
}
}
/**
* Stops the current preview, if any was started.
* This should be called onPause().
*/
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void close() {
if (mInEditor) return;
mCameraEngine.stop(false);
if (mCameraPreview != null) mCameraPreview.onPause();
}
/**
* Destroys this instance, releasing immediately
* the camera resource.
*/
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void destroy() {
if (mInEditor) return;
clearCameraListeners();
clearFrameProcessors();
mCameraEngine.destroy(true);
if (mCameraPreview != null) mCameraPreview.onDestroy();
}
//endregion
//region Public APIs for controls
/**
* Sets the experimental flag which occasionally can enable
* new, unstable beta features.
* @param experimental true to enable new features
*/
public void setExperimental(boolean experimental) {
mExperimental = experimental;
}
/**
* Shorthand for the appropriate set* method.
* For example, if control is a {@link Grid}, this calls {@link #setGrid(Grid)}.
*
* @param control desired value
*/
public void set(@NonNull Control control) {
if (control instanceof Audio) {
setAudio((Audio) control);
} else if (control instanceof Facing) {
setFacing((Facing) control);
} else if (control instanceof Flash) {
setFlash((Flash) control);
} else if (control instanceof Grid) {
setGrid((Grid) control);
} else if (control instanceof Hdr) {
setHdr((Hdr) control);
} else if (control instanceof Mode) {
setMode((Mode) control);
} else if (control instanceof WhiteBalance) {
setWhiteBalance((WhiteBalance) control);
} else if (control instanceof VideoCodec) {
setVideoCodec((VideoCodec) control);
} else if (control instanceof Preview) {
setPreview((Preview) control);
} else if (control instanceof Engine) {
setEngine((Engine) control);
} else if (control instanceof PictureFormat) {
setPictureFormat((PictureFormat) control);
}
}
/**
* Shorthand for the appropriate get* method.
* For example, if control class is a {@link Grid}, this calls {@link #getGrid()}.
*
* @param controlClass desired value class
* @param <T> the class type
* @return the control
*/
@SuppressWarnings("unchecked")
@NonNull
public <T extends Control> T get(@NonNull Class<T> controlClass) {
if (controlClass == Audio.class) {
return (T) getAudio();
} else if (controlClass == Facing.class) {
return (T) getFacing();
} else if (controlClass == Flash.class) {
return (T) getFlash();
} else if (controlClass == Grid.class) {
return (T) getGrid();
} else if (controlClass == Hdr.class) {
return (T) getHdr();
} else if (controlClass == Mode.class) {
return (T) getMode();
} else if (controlClass == WhiteBalance.class) {
return (T) getWhiteBalance();
} else if (controlClass == VideoCodec.class) {
return (T) getVideoCodec();
} else if (controlClass == Preview.class) {
return (T) getPreview();
} else if (controlClass == Engine.class) {
return (T) getEngine();
} else if (controlClass == PictureFormat.class) {
return (T) getPictureFormat();
} else {
throw new IllegalArgumentException("Unknown control class: " + controlClass);
}
}
/**
* Controls the preview engine. Should only be called
* if this CameraView was never added to any window
* (like if you created it programmatically).
* Otherwise, it has no effect.
*
* @see Preview#SURFACE
* @see Preview#TEXTURE
* @see Preview#GL_SURFACE
*
* @param preview desired preview engine
*/
public void setPreview(@NonNull Preview preview) {
boolean isNew = preview != mPreview;
if (isNew) {
mPreview = preview;
boolean isAttachedToWindow = getWindowToken() != null;
if (!isAttachedToWindow && mCameraPreview != null) {
// Null the preview: will create another when re-attaching.
mCameraPreview.onDestroy();
mCameraPreview = null;
}
}
}
/**
* Returns the current preview control.
*
* @see #setPreview(Preview)
* @return the current preview control
*/
@NonNull
public Preview getPreview() {
return mPreview;
}
/**
* Controls the core engine. Should only be called
* if this CameraView is closed (open() was never called).
* Otherwise, it has no effect.
*
* @see Engine#CAMERA1
* @see Engine#CAMERA2
*
* @param engine desired engine
*/
public void setEngine(@NonNull Engine engine) {
if (!isClosed()) return;
mEngine = engine;
CameraEngine oldEngine = mCameraEngine;
doInstantiateEngine();
if (mCameraPreview != null) mCameraEngine.setPreview(mCameraPreview);
// Set again all parameters
setFacing(oldEngine.getFacing());
setFlash(oldEngine.getFlash());
setMode(oldEngine.getMode());
setWhiteBalance(oldEngine.getWhiteBalance());
setHdr(oldEngine.getHdr());
setAudio(oldEngine.getAudio());
setAudioBitRate(oldEngine.getAudioBitRate());
setPictureSize(oldEngine.getPictureSizeSelector());
setPictureFormat(oldEngine.getPictureFormat());
setVideoSize(oldEngine.getVideoSizeSelector());
setVideoCodec(oldEngine.getVideoCodec());
setVideoMaxSize(oldEngine.getVideoMaxSize());
setVideoMaxDuration(oldEngine.getVideoMaxDuration());
setVideoBitRate(oldEngine.getVideoBitRate());
setAutoFocusResetDelay(oldEngine.getAutoFocusResetDelay());
setPreviewFrameRate(oldEngine.getPreviewFrameRate());
setPreviewFrameRateExact(oldEngine.getPreviewFrameRateExact());
setSnapshotMaxWidth(oldEngine.getSnapshotMaxWidth());
setSnapshotMaxHeight(oldEngine.getSnapshotMaxHeight());
setFrameProcessingMaxWidth(oldEngine.getFrameProcessingMaxWidth());
setFrameProcessingMaxHeight(oldEngine.getFrameProcessingMaxHeight());
setFrameProcessingFormat(0 /* this is very engine specific, so do not pass */);
setFrameProcessingPoolSize(oldEngine.getFrameProcessingPoolSize());
mCameraEngine.setHasFrameProcessors(!mFrameProcessors.isEmpty());
}
/**
* Returns the current engine control.
*
* @see #setEngine(Engine)
* @return the current engine control
*/
@NonNull
public Engine getEngine() {
return mEngine;
}
/**
* Returns a {@link CameraOptions} instance holding supported options for this camera
* session. This might change over time. It's better to hold a reference from
* {@link CameraListener#onCameraOpened(CameraOptions)}.
*
* @return an options map, or null if camera was not opened
*/
@Nullable
public CameraOptions getCameraOptions() {
return mCameraEngine.getCameraOptions();
}
/**
* Sets exposure adjustment, in EV stops. A positive value will mean brighter picture.
*
* If camera is not opened, this will have no effect.
* If {@link CameraOptions#isExposureCorrectionSupported()} is false, this will have no effect.
* The provided value should be between the bounds returned by {@link CameraOptions}, or it will
* be capped.
*
* @see CameraOptions#getExposureCorrectionMinValue()
* @see CameraOptions#getExposureCorrectionMaxValue()
*
* @param EVvalue exposure correction value.
*/
public void setExposureCorrection(float EVvalue) {
CameraOptions options = getCameraOptions();
if (options != null) {
float min = options.getExposureCorrectionMinValue();
float max = options.getExposureCorrectionMaxValue();
if (EVvalue < min) EVvalue = min;
if (EVvalue > max) EVvalue = max;
float[] bounds = new float[]{min, max};
mCameraEngine.setExposureCorrection(EVvalue, bounds, null, false);
}
}
/**
* Returns the current exposure correction value, typically 0
* at start-up.
* @return the current exposure correction value
*/
public float getExposureCorrection() {
return mCameraEngine.getExposureCorrectionValue();
}
/**
* Sets a zoom value. This is not guaranteed to be supported by the current device,
* but you can take a look at {@link CameraOptions#isZoomSupported()}.
* This will have no effect if called before the camera is opened.
*
* Zoom value should be between 0 and 1, where 1 will be the maximum available zoom.
* If it's not, it will be capped.
*
* @param zoom value in [0,1]
*/
public void setZoom(float zoom) {
if (zoom < 0) zoom = 0;
if (zoom > 1) zoom = 1;
mCameraEngine.setZoom(zoom, null, false);
}
/**
* Returns the current zoom value, something between 0 and 1.
* @return the current zoom value
*/
public float getZoom() {
return mCameraEngine.getZoomValue();
}
/**
* Controls the grids to be drawn over the current layout.
*
* @see Grid#OFF
* @see Grid#DRAW_3X3
* @see Grid#DRAW_4X4
* @see Grid#DRAW_PHI
*
* @param gridMode desired grid mode
*/
public void setGrid(@NonNull Grid gridMode) {
mGridLinesLayout.setGridMode(gridMode);
}
/**
* Gets the current grid mode.
* @return the current grid mode
*/
@NonNull
public Grid getGrid() {
return mGridLinesLayout.getGridMode();
}
/**
* Controls the color of the grid lines that will be drawn
* over the current layout.
*
* @param color a resolved color
*/
public void setGridColor(@ColorInt int color) {
mGridLinesLayout.setGridColor(color);
}
/**
* Returns the current grid color.
* @return the current grid color
*/
public int getGridColor() {
return mGridLinesLayout.getGridColor();
}
/**
* Controls the grids to be drawn over the current layout.
*
* @see Hdr#OFF
* @see Hdr#ON
*
* @param hdr desired hdr value
*/
public void setHdr(@NonNull Hdr hdr) {
mCameraEngine.setHdr(hdr);
}
/**
* Gets the current hdr value.
* @return the current hdr value
*/
@NonNull
public Hdr getHdr() {
return mCameraEngine.getHdr();
}
/**
* Set location coordinates to be found later in the EXIF header
*
* @param latitude current latitude
* @param longitude current longitude
*/
public void setLocation(double latitude, double longitude) {
Location location = new Location("Unknown");
location.setTime(System.currentTimeMillis());
location.setAltitude(0);
location.setLatitude(latitude);
location.setLongitude(longitude);
mCameraEngine.setLocation(location);
}
/**
* Set location values to be found later in the EXIF header
*
* @param location current location
*/
public void setLocation(@Nullable Location location) {
mCameraEngine.setLocation(location);
}
/**
* Retrieves the location previously applied with setLocation().
*
* @return the current location, if any.
*/
@Nullable
public Location getLocation() {
return mCameraEngine.getLocation();
}
/**
* Sets desired white balance to current camera session.
*
* @see WhiteBalance#AUTO
* @see WhiteBalance#INCANDESCENT
* @see WhiteBalance#FLUORESCENT
* @see WhiteBalance#DAYLIGHT
* @see WhiteBalance#CLOUDY
*
* @param whiteBalance desired white balance behavior.
*/
public void setWhiteBalance(@NonNull WhiteBalance whiteBalance) {
mCameraEngine.setWhiteBalance(whiteBalance);
}
/**
* Returns the current white balance behavior.
* @return white balance value.
*/
@NonNull
public WhiteBalance getWhiteBalance() {
return mCameraEngine.getWhiteBalance();
}
/**
* Sets which camera sensor should be used.
*
* @see Facing#FRONT
* @see Facing#BACK
*
* @param facing a facing value.
*/
public void setFacing(@NonNull Facing facing) {
mCameraEngine.setFacing(facing);
}
/**
* Gets the facing camera currently being used.
* @return a facing value.
*/
@NonNull
public Facing getFacing() {
return mCameraEngine.getFacing();
}
/**
* Toggles the facing value between {@link Facing#BACK}
* and {@link Facing#FRONT}.
*
* @return the new facing value
*/
public Facing toggleFacing() {
Facing facing = mCameraEngine.getFacing();
switch (facing) {
case BACK:
setFacing(Facing.FRONT);
break;
case FRONT:
setFacing(Facing.BACK);
break;
}
return mCameraEngine.getFacing();
}
/**
* Sets the flash mode.
*
* @see Flash#OFF
* @see Flash#ON
* @see Flash#AUTO
* @see Flash#TORCH
* @param flash desired flash mode.
*/
public void setFlash(@NonNull Flash flash) {
mCameraEngine.setFlash(flash);
}
/**
* Gets the current flash mode.
* @return a flash mode
*/
@NonNull
public Flash getFlash() {
return mCameraEngine.getFlash();
}
/**
* Controls the audio mode.
*
* @see Audio#OFF
* @see Audio#ON
* @see Audio#MONO
* @see Audio#STEREO
*
* @param audio desired audio value
*/
public void setAudio(@NonNull Audio audio) {
if (audio == getAudio() || isClosed()) {
// Check did took place, or will happen on start().
mCameraEngine.setAudio(audio);
} else if (checkPermissions(audio)) {
// Camera is running. Pass.
mCameraEngine.setAudio(audio);
} else {
// This means that the audio permission is being asked.
// Stop the camera so it can be restarted by the developer onPermissionResult.
// Developer must also set the audio value again...
// Not ideal but good for now.
close();
}
}
/**
* Gets the current audio value.
* @return the current audio value
*/
@NonNull
public Audio getAudio() {
return mCameraEngine.getAudio();
}
/**
* Sets an {@link AutoFocusMarker} to be notified of metering start, end and fail events
* so that it can draw elements on screen.
*
* @param autoFocusMarker the marker, or null
*/
public void setAutoFocusMarker(@Nullable AutoFocusMarker autoFocusMarker) {
mAutoFocusMarker = autoFocusMarker;
mMarkerLayout.onMarker(MarkerLayout.TYPE_AUTOFOCUS, autoFocusMarker);
}
/**
* Sets the current delay in milliseconds to reset the focus after a metering event.
*
* @param delayMillis desired delay (in milliseconds). If the delay
* is less than or equal to 0 or equal to Long.MAX_VALUE,
* the values will not be reset.
*/
public void setAutoFocusResetDelay(long delayMillis) {
mCameraEngine.setAutoFocusResetDelay(delayMillis);
}
/**
* Returns the current delay in milliseconds to reset the focus after a metering event.
*
* @return the current reset delay in milliseconds
*/
@SuppressWarnings("unused")
public long getAutoFocusResetDelay() { return mCameraEngine.getAutoFocusResetDelay(); }
/**
* Starts a 3A touch metering process at the given coordinates, with respect
* to the view width and height.
*
* @param x should be between 0 and getWidth()
* @param y should be between 0 and getHeight()
*/
public void startAutoFocus(float x, float y) {
if (x < 0 || x > getWidth()) {
throw new IllegalArgumentException("x should be >= 0 and <= getWidth()");
}
if (y < 0 || y > getHeight()) {
throw new IllegalArgumentException("y should be >= 0 and <= getHeight()");
}
Size size = new Size(getWidth(), getHeight());
PointF point = new PointF(x, y);
MeteringRegions regions = MeteringRegions.fromPoint(size, point);
mCameraEngine.startAutoFocus(null, regions, point);
}
/**
* Starts a 3A touch metering process at the given coordinates, with respect
* to the view width and height.
*
* @param region should be between 0 and getWidth() / getHeight()
*/
public void startAutoFocus(@NonNull RectF region) {
RectF full = new RectF(0, 0, getWidth(), getHeight());
if (!full.contains(region)) {
throw new IllegalArgumentException("Region is out of view bounds! " + region);
}
Size size = new Size(getWidth(), getHeight());
MeteringRegions regions = MeteringRegions.fromArea(size, region);
mCameraEngine.startAutoFocus(null, regions,
new PointF(region.centerX(), region.centerY()));
}
/**
* <strong>ADVANCED FEATURE</strong> - sets a size selector for the preview stream.
* The {@link SizeSelector} will be invoked with the list of available sizes, and the first
* acceptable size will be accepted and passed to the internal engine and surface.
*
* This is typically NOT NEEDED. The default size selector is already smart enough to respect
* the picture/video output aspect ratio, and be bigger than the surface so that there is no
* upscaling. If all you want is set an aspect ratio, use {@link #setPictureSize(SizeSelector)}
* and {@link #setVideoSize(SizeSelector)}.
*
* When stream size changes, the {@link CameraView} is remeasured so any WRAP_CONTENT dimension
* is recomputed accordingly.
*
* See the {@link SizeSelectors} class for handy utilities for creating selectors.
*
* @param selector a size selector
*/
public void setPreviewStreamSize(@NonNull SizeSelector selector) {
mCameraEngine.setPreviewStreamSizeSelector(selector);
}
/**
* Set the current session type to either picture or video.
*
* @see Mode#PICTURE
* @see Mode#VIDEO
*
* @param mode desired session type.
*/
public void setMode(@NonNull Mode mode) {
mCameraEngine.setMode(mode);
}
/**
* Gets the current mode.
* @return the current mode
*/
@NonNull
public Mode getMode() {
return mCameraEngine.getMode();
}
/**
* Sets a capture size selector for picture mode.
* The {@link SizeSelector} will be invoked with the list of available sizes, and the first
* acceptable size will be accepted and passed to the internal engine.
* See the {@link SizeSelectors} class for handy utilities for creating selectors.
*
* @param selector a size selector
*/
public void setPictureSize(@NonNull SizeSelector selector) {
mCameraEngine.setPictureSizeSelector(selector);
}
/**
* Whether the engine should perform a metering sequence before taking pictures requested
* with {@link #takePicture()}. A metering sequence includes adjusting focus, exposure
* and white balance to ensure a good quality of the result.
*
* When this parameter is true, the quality of the picture increases, but the latency
* increases as well. Defaults to true.
*
* This is a CAMERA2 only API. On CAMERA1, picture metering is always enabled.
*
* @see #setPictureSnapshotMetering(boolean)
* @param enable true to enable
*/
public void setPictureMetering(boolean enable) {
mCameraEngine.setPictureMetering(enable);
}
/**
* Whether the engine should perform a metering sequence before taking pictures requested
* with {@link #takePicture()}. See {@link #setPictureMetering(boolean)}.
*
* @see #setPictureMetering(boolean)
* @return true if picture metering is enabled
*/
public boolean getPictureMetering() {
return mCameraEngine.getPictureMetering();
}
/**
* Whether the engine should perform a metering sequence before taking pictures requested
* with {@link #takePictureSnapshot()}. A metering sequence includes adjusting focus,
* exposure and white balance to ensure a good quality of the result.
*
* When this parameter is true, the quality of the picture increases, but the latency
* increases as well. To keep snapshots fast, this defaults to false.
*
* This is a CAMERA2 only API. On CAMERA1, picture snapshot metering is always disabled.
*
* @see #setPictureMetering(boolean)
* @param enable true to enable
*/
public void setPictureSnapshotMetering(boolean enable) {
mCameraEngine.setPictureSnapshotMetering(enable);
}
/**
* Whether the engine should perform a metering sequence before taking pictures requested
* with {@link #takePictureSnapshot()}. See {@link #setPictureSnapshotMetering(boolean)}.
*
* @see #setPictureSnapshotMetering(boolean)
* @return true if picture metering is enabled
*/
public boolean getPictureSnapshotMetering() {
return mCameraEngine.getPictureSnapshotMetering();
}
/**
* Sets the format for pictures taken with {@link #takePicture()}. This format does not apply
* to picture snapshots taken with {@link #takePictureSnapshot()}.
* The {@link PictureFormat#JPEG} is always supported - for other values, please check
* the {@link CameraOptions#getSupportedPictureFormats()} value.
*
* @param pictureFormat new format
*/
public void setPictureFormat(@NonNull PictureFormat pictureFormat) {
mCameraEngine.setPictureFormat(pictureFormat);
}
/**
* Returns the current picture format.
* @see #setPictureFormat(PictureFormat)
* @return the picture format
*/
@NonNull
public PictureFormat getPictureFormat() {
return mCameraEngine.getPictureFormat();
}
/**
* Sets a capture size selector for video mode.
* The {@link SizeSelector} will be invoked with the list of available sizes, and the first
* acceptable size will be accepted and passed to the internal engine.
* See the {@link SizeSelectors} class for handy utilities for creating selectors.
*
* @param selector a size selector
*/
public void setVideoSize(@NonNull SizeSelector selector) {
mCameraEngine.setVideoSizeSelector(selector);
}
/**
* Sets the bit rate in bits per second for video capturing.
* Will be used by both {@link #takeVideo(File)} and {@link #takeVideoSnapshot(File)}.
*
* @param bitRate desired bit rate
*/
public void setVideoBitRate(int bitRate) {
mCameraEngine.setVideoBitRate(bitRate);
}
/**
* Returns the current video bit rate.
* @return current bit rate
*/
@SuppressWarnings("unused")
public int getVideoBitRate() {
return mCameraEngine.getVideoBitRate();
}
/**
* A flag to control the behavior when calling {@link #setPreviewFrameRate(float)}.
*
* If the value is set to true, {@link #setPreviewFrameRate(float)} will choose the preview
* frame range as close to the desired new frame rate as possible. Which mean it may choose a
* narrow range around the desired frame rate. Note: This option will give you as exact fps as
* you want but the sensor will have less freedom when adapting the exposure to the environment,
* which may lead to dark preview.
*
* If the value is set to false, {@link #setPreviewFrameRate(float)} will choose as broad range
* as it can.
*
* @param videoFrameRateExact whether want a more exact preview frame range
*
* @see #setPreviewFrameRate(float)
*/
public void setPreviewFrameRateExact(boolean videoFrameRateExact) {
mCameraEngine.setPreviewFrameRateExact(videoFrameRateExact);
}
/**
* Returns whether we want to set preview fps as exact as we set through
* {@link #setPreviewFrameRate(float)}.
*
* @see #setPreviewFrameRateExact(boolean)
* @see #setPreviewFrameRate(float)
* @return current option
*/
public boolean getPreviewFrameRateExact() {
return mCameraEngine.getPreviewFrameRateExact();
}
/**
* Sets the preview frame rate in frames per second.
* This rate will be used, for example, by the frame processor and in video
* snapshot taken through {@link #takeVideo(File)}.
*
* A value of 0F will restore the rate to a default value.
*
* @param frameRate desired frame rate
*/
public void setPreviewFrameRate(float frameRate) {
mCameraEngine.setPreviewFrameRate(frameRate);
}
/**
* Returns the current preview frame rate.
* This can return 0F if no frame rate was set.
*
* @see #setPreviewFrameRate(float)
* @return current frame rate
*/
public float getPreviewFrameRate() {
return mCameraEngine.getPreviewFrameRate();
}
/**
* Sets the bit rate in bits per second for audio capturing.
* Will be used by both {@link #takeVideo(File)} and {@link #takeVideoSnapshot(File)}.
*
* @param bitRate desired bit rate
*/
public void setAudioBitRate(int bitRate) {
mCameraEngine.setAudioBitRate(bitRate);
}
/**
* Returns the current audio bit rate.
* @return current bit rate
*/
@SuppressWarnings("unused")
public int getAudioBitRate() {
return mCameraEngine.getAudioBitRate();
}
/**
* Adds a {@link CameraListener} instance to be notified of all
* interesting events that happen during the camera lifecycle.
*
* @param cameraListener a listener for events.
*/
public void addCameraListener(@NonNull CameraListener cameraListener) {
mListeners.add(cameraListener);
}
/**
* Remove a {@link CameraListener} that was previously registered.
*
* @param cameraListener a listener for events.
*/
public void removeCameraListener(@NonNull CameraListener cameraListener) {
mListeners.remove(cameraListener);
}
/**
* Clears the list of {@link CameraListener} that are registered
* to camera events.
*/
public void clearCameraListeners() {
mListeners.clear();
}
/**
* Asks the camera to capture an image of the current scene.
* This will trigger {@link CameraListener#onPictureTaken(PictureResult)} if a listener
* was registered.
*
* @see #takePictureSnapshot()
*/
public void takePicture() {
PictureResult.Stub stub = new PictureResult.Stub();
mCameraEngine.takePicture(stub);
}
/**
* Asks the camera to capture a snapshot of the current preview.
* This eventually triggers {@link CameraListener#onPictureTaken(PictureResult)} if a listener
* was registered.
*
* The difference with {@link #takePicture()} is that this capture is faster, so it might be
* better on slower cameras, though the result can be generally blurry or low quality.
*
* @see #takePicture()
*/
public void takePictureSnapshot() {
PictureResult.Stub stub = new PictureResult.Stub();
mCameraEngine.takePictureSnapshot(stub);
}
/**
* Starts recording a video. Video will be written to the given file,
* so callers should ensure they have appropriate permissions to write to the file.
*
* @param file a file where the video will be saved
*/
public void takeVideo(@NonNull File file) {
takeVideo(file, null);
}
/**
* Starts recording a video. Video will be written to the given file,
* so callers should ensure they have appropriate permissions to write to the file.
*
* @param fileDescriptor a file descriptor where the video will be saved
*/
public void takeVideo(@NonNull FileDescriptor fileDescriptor) {
takeVideo(null, fileDescriptor);
}
private void takeVideo(@Nullable File file, @Nullable FileDescriptor fileDescriptor) {
VideoResult.Stub stub = new VideoResult.Stub();
if (file != null) {
mCameraEngine.takeVideo(stub, file, null);
} else if (fileDescriptor != null) {
mCameraEngine.takeVideo(stub, null, fileDescriptor);
} else {
throw new IllegalStateException("file and fileDescriptor are both null.");
}
mUiHandler.post(new Runnable() {
@Override
public void run() {
mKeepScreenOn = getKeepScreenOn();
if (!mKeepScreenOn) setKeepScreenOn(true);
}
});
}
/**
* Starts recording a fast, low quality video snapshot. Video will be written to the given file,
* so callers should ensure they have appropriate permissions to write to the file.
*
* Throws an exception if API level is below 18, or if the preview being used is not
* {@link Preview#GL_SURFACE}.
*
* @param file a file where the video will be saved
*/
public void takeVideoSnapshot(@NonNull File file) {
VideoResult.Stub stub = new VideoResult.Stub();
mCameraEngine.takeVideoSnapshot(stub, file);
mUiHandler.post(new Runnable() {
@Override
public void run() {
mKeepScreenOn = getKeepScreenOn();
if (!mKeepScreenOn) setKeepScreenOn(true);
}
});
}
/**
* Starts recording a video. Video will be written to the given file,
* so callers should ensure they have appropriate permissions to write to the file.
* Recording will be automatically stopped after the given duration, overriding
* temporarily any duration limit set by {@link #setVideoMaxDuration(int)}.
*
* @param file a file where the video will be saved
* @param durationMillis recording max duration
*/
public void takeVideo(@NonNull File file, int durationMillis) {
takeVideo(file, null, durationMillis);
}
/**
* Starts recording a video. Video will be written to the given file,
* so callers should ensure they have appropriate permissions to write to the file.
* Recording will be automatically stopped after the given duration, overriding
* temporarily any duration limit set by {@link #setVideoMaxDuration(int)}.
*
* @param fileDescriptor a file descriptor where the video will be saved
* @param durationMillis recording max duration
*/
public void takeVideo(@NonNull FileDescriptor fileDescriptor, int durationMillis) {
takeVideo(null, fileDescriptor, durationMillis);
}
private void takeVideo(@Nullable File file, @Nullable FileDescriptor fileDescriptor,
int durationMillis) {
final int old = getVideoMaxDuration();
addCameraListener(new CameraListener() {
@Override
public void onVideoTaken(@NonNull VideoResult result) {
setVideoMaxDuration(old);
removeCameraListener(this);
}
@Override
public void onCameraError(@NonNull CameraException exception) {
super.onCameraError(exception);
if (exception.getReason() == CameraException.REASON_VIDEO_FAILED) {
setVideoMaxDuration(old);
removeCameraListener(this);
}
}
});
setVideoMaxDuration(durationMillis);
takeVideo(file, fileDescriptor);
}
/**
* Starts recording a fast, low quality video snapshot. Video will be written to the given file,
* so callers should ensure they have appropriate permissions to write to the file.
* Recording will be automatically stopped after the given duration, overriding
* temporarily any duration limit set by {@link #setVideoMaxDuration(int)}.
*
* Throws an exception if API level is below 18, or if the preview being used is not
* {@link Preview#GL_SURFACE}.
*
* @param file a file where the video will be saved
* @param durationMillis recording max duration
*
*/
public void takeVideoSnapshot(@NonNull File file, int durationMillis) {
final int old = getVideoMaxDuration();
addCameraListener(new CameraListener() {
@Override
public void onVideoTaken(@NonNull VideoResult result) {
setVideoMaxDuration(old);
removeCameraListener(this);
}
@Override
public void onCameraError(@NonNull CameraException exception) {
super.onCameraError(exception);
if (exception.getReason() == CameraException.REASON_VIDEO_FAILED) {
setVideoMaxDuration(old);
removeCameraListener(this);
}
}
});
setVideoMaxDuration(durationMillis);
takeVideoSnapshot(file);
}
// TODO: pauseVideo and resumeVideo? There is mediarecorder.pause(), but API 24...
/**
* Stops capturing video or video snapshots being recorded, if there was any.
* This will fire {@link CameraListener#onVideoTaken(VideoResult)}.
*/
public void stopVideo() {
mCameraEngine.stopVideo();
mUiHandler.post(new Runnable() {
@Override
public void run() {
if (getKeepScreenOn() != mKeepScreenOn) setKeepScreenOn(mKeepScreenOn);
}
});
}
/**
* Sets the max width for snapshots taken with {@link #takePictureSnapshot()} or
* {@link #takeVideoSnapshot(File)}. If the snapshot width exceeds this value, the snapshot
* will be scaled down to match this constraint.
*
* @param maxWidth max width for snapshots
*/
public void setSnapshotMaxWidth(int maxWidth) {
mCameraEngine.setSnapshotMaxWidth(maxWidth);
}
/**
* Sets the max height for snapshots taken with {@link #takePictureSnapshot()} or
* {@link #takeVideoSnapshot(File)}. If the snapshot height exceeds this value, the snapshot
* will be scaled down to match this constraint.
*
* @param maxHeight max height for snapshots
*/
public void setSnapshotMaxHeight(int maxHeight) {
mCameraEngine.setSnapshotMaxHeight(maxHeight);
}
/**
* The max width for snapshots.
* @see #setSnapshotMaxWidth(int)
* @return max width
*/
public int getSnapshotMaxWidth() {
return mCameraEngine.getSnapshotMaxWidth();
}
/**
* The max height for snapshots.
* @see #setSnapshotMaxHeight(int)
* @return max height
*/
public int getSnapshotMaxHeight() {
return mCameraEngine.getSnapshotMaxHeight();
}
/**
* Returns the size used for snapshots, or null if it hasn't been computed
* (for example if the surface is not ready). This is the preview size, rotated to match
* the output orientation, and cropped to the visible part.
*
* This also includes the {@link #setSnapshotMaxWidth(int)} and
* {@link #setSnapshotMaxHeight(int)} constraints.
*
* This does NOT include any constraints specific to video encoding, which are
* device specific and depend on the capabilities of the device codec.
*
* @return the size of snapshots
*/
@Nullable
public Size getSnapshotSize() {
if (getWidth() == 0 || getHeight() == 0) return null;
// Get the preview size and crop according to the current view size.
// It's better to do calculations in the REF_VIEW reference, and then flip if needed.
Size preview = mCameraEngine.getUncroppedSnapshotSize(Reference.VIEW);
if (preview == null) return null; // Should never happen.
AspectRatio viewRatio = AspectRatio.of(getWidth(), getHeight());
Rect crop = CropHelper.computeCrop(preview, viewRatio);
Size cropSize = new Size(crop.width(), crop.height());
if (mCameraEngine.getAngles().flip(Reference.VIEW, Reference.OUTPUT)) {
return cropSize.flip();
} else {
return cropSize;
}
}
/**
* Returns the size used for pictures taken with {@link #takePicture()},
* or null if it hasn't been computed (for example if the surface is not ready),
* or null if we are in video mode.
*
* The size is rotated to match the output orientation.
*
* @return the size of pictures
*/
@Nullable
public Size getPictureSize() {
return mCameraEngine.getPictureSize(Reference.OUTPUT);
}
/**
* Returns the size used for videos taken with {@link #takeVideo(File)},
* or null if it hasn't been computed (for example if the surface is not ready),
* or null if we are in picture mode.
*
* The size is rotated to match the output orientation.
*
* @return the size of videos
*/
@Nullable
public Size getVideoSize() {
return mCameraEngine.getVideoSize(Reference.OUTPUT);
}
// If we end up here, we're in M.
@TargetApi(Build.VERSION_CODES.M)
private void requestPermissions(boolean requestCamera, boolean requestAudio) {
Activity activity = null;
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
activity = (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
List<String> permissions = new ArrayList<>();
if (requestCamera) permissions.add(Manifest.permission.CAMERA);
if (requestAudio) permissions.add(Manifest.permission.RECORD_AUDIO);
if (activity != null) {
activity.requestPermissions(permissions.toArray(new String[0]),
PERMISSION_REQUEST_CODE);
}
}
@SuppressLint("NewApi")
private void playSound(int soundType) {
if (mPlaySounds) {
if (mSound == null) mSound = new MediaActionSound();
mSound.play(soundType);
}
}
/**
* Controls whether CameraView should play sound effects on certain
* events (picture taken, focus complete). Note that:
* - On API level {@literal <} 16, this flag is always false
* - Camera1 will always play the shutter sound when taking pictures
*
* @param playSounds whether to play sound effects
*/
public void setPlaySounds(boolean playSounds) {
mPlaySounds = playSounds && Build.VERSION.SDK_INT >= 16;
mCameraEngine.setPlaySounds(playSounds);
}
/**
* Gets the current sound effect behavior.
*
* @see #setPlaySounds(boolean)
* @return whether sound effects are supported
*/
public boolean getPlaySounds() {
return mPlaySounds;
}
/**
* Controls whether picture and video output should consider the current device orientation.
* For example, when true, if the user rotates the device before taking a picture, the picture
* will be rotated as well.
*
* @param useDeviceOrientation true to consider device orientation for outputs
*/
public void setUseDeviceOrientation(boolean useDeviceOrientation) {
mUseDeviceOrientation = useDeviceOrientation;
}
/**
* Gets the current behavior for considering the device orientation when returning picture
* or video outputs.
*
* @see #setUseDeviceOrientation(boolean)
* @return whether we are using the device orientation for outputs
*/
public boolean getUseDeviceOrientation() {
return mUseDeviceOrientation;
}
/**
* Sets the encoder for video recordings.
* Defaults to {@link VideoCodec#DEVICE_DEFAULT}.
*
* @see VideoCodec#DEVICE_DEFAULT
* @see VideoCodec#H_263
* @see VideoCodec#H_264
*
* @param codec requested video codec
*/
public void setVideoCodec(@NonNull VideoCodec codec) {
mCameraEngine.setVideoCodec(codec);
}
/**
* Gets the current encoder for video recordings.
* @return the current video codec
*/
@NonNull
public VideoCodec getVideoCodec() {
return mCameraEngine.getVideoCodec();
}
/**
* Sets the maximum size in bytes for recorded video files.
* Once this size is reached, the recording will automatically stop.
* Defaults to unlimited size. Use 0 or negatives to disable.
*
* @param videoMaxSizeInBytes The maximum video size in bytes
*/
public void setVideoMaxSize(long videoMaxSizeInBytes) {
mCameraEngine.setVideoMaxSize(videoMaxSizeInBytes);
}
/**
* Returns the maximum size in bytes for recorded video files, or 0
* if no size was set.
*
* @see #setVideoMaxSize(long)
* @return the maximum size in bytes
*/
public long getVideoMaxSize() {
return mCameraEngine.getVideoMaxSize();
}
/**
* Sets the maximum duration in milliseconds for video recordings.
* Once this duration is reached, the recording will automatically stop.
* Defaults to unlimited duration. Use 0 or negatives to disable.
*
* @param videoMaxDurationMillis The maximum video duration in milliseconds
*/
public void setVideoMaxDuration(int videoMaxDurationMillis) {
mCameraEngine.setVideoMaxDuration(videoMaxDurationMillis);
}
/**
* Returns the maximum duration in milliseconds for video recordings, or 0
* if no limit was set.
*
* @see #setVideoMaxDuration(int)
* @return the maximum duration in milliseconds
*/
public int getVideoMaxDuration() {
return mCameraEngine.getVideoMaxDuration();
}
/**
* Returns true if the camera is currently recording a video
* @return boolean indicating if the camera is recording a video
*/
public boolean isTakingVideo() {
return mCameraEngine.isTakingVideo();
}
/**
* Returns true if the camera is currently capturing a picture
* @return boolean indicating if the camera is capturing a picture
*/
public boolean isTakingPicture() {
return mCameraEngine.isTakingPicture();
}
//endregion
//region Callbacks and dispatching
@VisibleForTesting
class CameraCallbacks implements
CameraEngine.Callback,
OrientationHelper.Callback,
GestureFinder.Controller {
private final String TAG = CameraCallbacks.class.getSimpleName();
private final CameraLogger LOG = CameraLogger.create(TAG);
@NonNull
@Override
public Context getContext() {
return CameraView.this.getContext();
}
@Override
public int getWidth() {
return CameraView.this.getWidth();
}
@Override
public int getHeight() {
return CameraView.this.getHeight();
}
@Override
public void dispatchOnCameraOpened(@NonNull final CameraOptions options) {
LOG.i("dispatchOnCameraOpened", options);
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (CameraListener listener : mListeners) {
listener.onCameraOpened(options);
}
}
});
}
@Override
public void dispatchOnCameraClosed() {
LOG.i("dispatchOnCameraClosed");
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (CameraListener listener : mListeners) {
listener.onCameraClosed();
}
}
});
}
@Override
public void onCameraPreviewStreamSizeChanged() {
// Camera preview size has changed.
// Request a layout pass for onMeasure() to do its stuff.
// Potentially this will change CameraView size, which changes Surface size,
// which triggers a new Preview size. But hopefully it will converge.
Size previewSize = mCameraEngine.getPreviewStreamSize(Reference.VIEW);
if (previewSize == null) {
throw new RuntimeException("Preview stream size should not be null here.");
} else if (previewSize.equals(mLastPreviewStreamSize)) {
LOG.i("onCameraPreviewStreamSizeChanged:",
"swallowing because the preview size has not changed.", previewSize);
} else {
LOG.i("onCameraPreviewStreamSizeChanged: posting a requestLayout call.",
"Preview stream size:", previewSize);
mUiHandler.post(new Runnable() {
@Override
public void run() {
requestLayout();
}
});
}
}
@Override
public void onShutter(boolean shouldPlaySound) {
if (shouldPlaySound && mPlaySounds) {
playSound(MediaActionSound.SHUTTER_CLICK);
}
}
@Override
public void dispatchOnPictureTaken(@NonNull final PictureResult.Stub stub) {
LOG.i("dispatchOnPictureTaken", stub);
mUiHandler.post(new Runnable() {
@Override
public void run() {
PictureResult result = new PictureResult(stub);
for (CameraListener listener : mListeners) {
listener.onPictureTaken(result);
}
}
});
}
@Override
public void dispatchOnVideoTaken(@NonNull final VideoResult.Stub stub) {
LOG.i("dispatchOnVideoTaken", stub);
mUiHandler.post(new Runnable() {
@Override
public void run() {
VideoResult result = new VideoResult(stub);
for (CameraListener listener : mListeners) {
listener.onVideoTaken(result);
}
}
});
}
@Override
public void dispatchOnFocusStart(@Nullable final Gesture gesture,
@NonNull final PointF point) {
LOG.i("dispatchOnFocusStart", gesture, point);
mUiHandler.post(new Runnable() {
@Override
public void run() {
mMarkerLayout.onEvent(MarkerLayout.TYPE_AUTOFOCUS, new PointF[]{ point });
if (mAutoFocusMarker != null) {
AutoFocusTrigger trigger = gesture != null ?
AutoFocusTrigger.GESTURE : AutoFocusTrigger.METHOD;
mAutoFocusMarker.onAutoFocusStart(trigger, point);
}
for (CameraListener listener : mListeners) {
listener.onAutoFocusStart(point);
}
}
});
}
@Override
public void dispatchOnFocusEnd(@Nullable final Gesture gesture,
final boolean success,
@NonNull final PointF point) {
LOG.i("dispatchOnFocusEnd", gesture, success, point);
mUiHandler.post(new Runnable() {
@Override
public void run() {
if (success && mPlaySounds) {
playSound(MediaActionSound.FOCUS_COMPLETE);
}
if (mAutoFocusMarker != null) {
AutoFocusTrigger trigger = gesture != null ?
AutoFocusTrigger.GESTURE : AutoFocusTrigger.METHOD;
mAutoFocusMarker.onAutoFocusEnd(trigger, success, point);
}
for (CameraListener listener : mListeners) {
listener.onAutoFocusEnd(success, point);
}
}
});
}
@Override
public void onDeviceOrientationChanged(int deviceOrientation) {
LOG.i("onDeviceOrientationChanged", deviceOrientation);
int displayOffset = mOrientationHelper.getLastDisplayOffset();
if (!mUseDeviceOrientation) {
// To fool the engine to return outputs in the VIEW reference system,
// The device orientation should be set to -displayOffset.
int fakeDeviceOrientation = (360 - displayOffset) % 360;
mCameraEngine.getAngles().setDeviceOrientation(fakeDeviceOrientation);
} else {
mCameraEngine.getAngles().setDeviceOrientation(deviceOrientation);
}
final int value = (deviceOrientation + displayOffset) % 360;
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (CameraListener listener : mListeners) {
listener.onOrientationChanged(value);
}
}
});
}
@Override
public void onDisplayOffsetChanged(int displayOffset, boolean willRecreate) {
LOG.i("onDisplayOffsetChanged", displayOffset, "recreate:", willRecreate);
if (isOpened() && !willRecreate) {
// Display offset changes when the device rotation lock is off and the activity
// is free to rotate. However, some changes will NOT recreate the activity, namely
// 180 degrees flips. In this case, we must restart the camera manually.
LOG.w("onDisplayOffsetChanged", "restarting the camera.");
close();
open();
}
}
@Override
public void dispatchOnZoomChanged(final float newValue, @Nullable final PointF[] fingers) {
LOG.i("dispatchOnZoomChanged", newValue);
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (CameraListener listener : mListeners) {
listener.onZoomChanged(newValue, new float[]{0, 1}, fingers);
}
}
});
}
@Override
public void dispatchOnExposureCorrectionChanged(final float newValue,
@NonNull final float[] bounds,
@Nullable final PointF[] fingers) {
LOG.i("dispatchOnExposureCorrectionChanged", newValue);
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (CameraListener listener : mListeners) {
listener.onExposureCorrectionChanged(newValue, bounds, fingers);
}
}
});
}
@Override
public void dispatchFrame(@NonNull final Frame frame) {
// The getTime() below might crash if developers incorrectly release
// frames asynchronously.
LOG.v("dispatchFrame:", frame.getTime(), "processors:", mFrameProcessors.size());
if (mFrameProcessors.isEmpty()) {
// Mark as released. This instance will be reused.
frame.release();
} else {
// Dispatch this frame to frame processors.
mFrameProcessingExecutor.execute(new Runnable() {
@Override
public void run() {
LOG.v("dispatchFrame: executing. Passing", frame.getTime(),
"to processors.");
for (FrameProcessor processor : mFrameProcessors) {
try {
processor.process(frame);
} catch (Exception e) {
LOG.w("Frame processor crashed:", e);
}
}
frame.release();
}
});
}
}
@Override
public void dispatchError(final CameraException exception) {
LOG.i("dispatchError", exception);
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (CameraListener listener : mListeners) {
listener.onCameraError(exception);
}
}
});
}
@Override
public void dispatchOnVideoRecordingStart() {
LOG.i("dispatchOnVideoRecordingStart");
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (CameraListener listener : mListeners) {
listener.onVideoRecordingStart();
}
}
});
}
@Override
public void dispatchOnVideoRecordingEnd() {
LOG.i("dispatchOnVideoRecordingEnd");
mUiHandler.post(new Runnable() {
@Override
public void run() {
for (CameraListener listener : mListeners) {
listener.onVideoRecordingEnd();
}
}
});
}
}
//endregion
//region Frame Processing
/**
* Adds a {@link FrameProcessor} instance to be notified of
* new frames in the preview stream.
*
* @param processor a frame processor.
*/
public void addFrameProcessor(@Nullable FrameProcessor processor) {
if (processor != null) {
mFrameProcessors.add(processor);
if (mFrameProcessors.size() == 1) {
mCameraEngine.setHasFrameProcessors(true);
}
}
}
/**
* Remove a {@link FrameProcessor} that was previously registered.
*
* @param processor a frame processor
*/
public void removeFrameProcessor(@Nullable FrameProcessor processor) {
if (processor != null) {
mFrameProcessors.remove(processor);
if (mFrameProcessors.size() == 0) {
mCameraEngine.setHasFrameProcessors(false);
}
}
}
/**
* Clears the list of {@link FrameProcessor} that have been registered
* to preview frames.
*/
public void clearFrameProcessors() {
boolean had = mFrameProcessors.size() > 0;
mFrameProcessors.clear();
if (had) {
mCameraEngine.setHasFrameProcessors(false);
}
}
/**
* Sets the max width for frame processing {@link Frame}s.
* This option is only supported by {@link Engine#CAMERA2} and will have no effect
* on other engines.
*
* @param maxWidth max width for frames
*/
public void setFrameProcessingMaxWidth(int maxWidth) {
mCameraEngine.setFrameProcessingMaxWidth(maxWidth);
}
/**
* Sets the max height for frame processing {@link Frame}s.
* This option is only supported by {@link Engine#CAMERA2} and will have no effect
* on other engines.
*
* @param maxHeight max height for frames
*/
public void setFrameProcessingMaxHeight(int maxHeight) {
mCameraEngine.setFrameProcessingMaxHeight(maxHeight);
}
/**
* The max width for frame processing frames.
* @see #setFrameProcessingMaxWidth(int)
* @return max width
*/
public int getFrameProcessingMaxWidth() {
return mCameraEngine.getFrameProcessingMaxWidth();
}
/**
* The max height for frame processing frames.
* @see #setFrameProcessingMaxHeight(int)
* @return max height
*/
public int getFrameProcessingMaxHeight() {
return mCameraEngine.getFrameProcessingMaxHeight();
}
/**
* Sets the {@link android.graphics.ImageFormat} for frame processing.
* Before applying you should check {@link CameraOptions#getSupportedFrameProcessingFormats()}.
*
* @param format image format
*/
public void setFrameProcessingFormat(int format) {
mCameraEngine.setFrameProcessingFormat(format);
}
/**
* Returns the current frame processing format.
* @see #setFrameProcessingFormat(int)
* @return image format
*/
public int getFrameProcessingFormat() {
return mCameraEngine.getFrameProcessingFormat();
}
/**
* Sets the frame processing pool size. This is (roughly) the max number of
* {@link Frame} instances that can exist at a given moment in the frame pipeline,
* excluding frozen frames.
*
* Defaults to 2 - higher values will increase the memory usage with little benefit.
* Can be higher than 2 if {@link #setFrameProcessingExecutors(int)} is used.
* These values should be tuned together. We recommend setting a pool size that's equal to
* the number of executors plus 1, so that there's always a free Frame for the camera engine.
*
* Changing this value after camera initialization will have no effect.
* @param poolSize pool size
*/
public void setFrameProcessingPoolSize(int poolSize) {
mCameraEngine.setFrameProcessingPoolSize(poolSize);
}
/**
* Returns the current frame processing pool size.
* @see #setFrameProcessingPoolSize(int)
* @return pool size
*/
public int getFrameProcessingPoolSize() {
return mCameraEngine.getFrameProcessingPoolSize();
}
/**
* Sets the thread pool size for frame processing. This means that if the processing rate
* is slower than the preview rate, you can set this value to something bigger than 1
* to avoid losing frames.
* Defaults to 1 and this should be OK for most applications.
*
* Should be tuned depending on the task, the processor implementation, and along with
* {@link #setFrameProcessingPoolSize(int)}. We recommend choosing a pool size that is
* equal to the executors plus 1.
* @param executors thread count
*/
public void setFrameProcessingExecutors(int executors) {
if (executors < 1) {
throw new IllegalArgumentException("Need at least 1 executor, got " + executors);
}
mFrameProcessingExecutors = executors;
ThreadPoolExecutor executor = new ThreadPoolExecutor(
executors,
executors,
4,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
@Override
public Thread newThread(@NonNull Runnable r) {
return new Thread(r, "FrameExecutor #" + mCount.getAndIncrement());
}
}
);
executor.allowCoreThreadTimeOut(true);
mFrameProcessingExecutor = executor;
}
/**
* Returns the current executors count.
* @see #setFrameProcessingExecutors(int)
* @return thread count
*/
public int getFrameProcessingExecutors() {
return mFrameProcessingExecutors;
}
//endregion
//region Overlays
@Override
public LayoutParams generateLayoutParams(AttributeSet attributeSet) {
if (!mInEditor && mOverlayLayout.isOverlay(attributeSet)) {
return mOverlayLayout.generateLayoutParams(attributeSet);
}
return super.generateLayoutParams(attributeSet);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (!mInEditor && mOverlayLayout.isOverlay(params)) {
mOverlayLayout.addView(child, params);
} else {
super.addView(child, index, params);
}
}
@Override
public void removeView(View view) {
ViewGroup.LayoutParams params = view.getLayoutParams();
if (!mInEditor && params != null && mOverlayLayout.isOverlay(params)) {
mOverlayLayout.removeView(view);
} else {
super.removeView(view);
}
}
//endregion
//region Filters
/**
* Applies a real-time filter to the camera preview, if it supports it.
* The only preview type that does so is currently {@link Preview#GL_SURFACE}.
*
* The filter will be applied to any picture snapshot taken with
* {@link #takePictureSnapshot()} and any video snapshot taken with
* {@link #takeVideoSnapshot(File)}.
*
* Use {@link NoFilter} to clear the existing filter,
* and take a look at the {@link Filters} class for commonly used filters.
*
* This method will throw an exception if the current preview does not support real-time
* filters. Make sure you use {@link Preview#GL_SURFACE} (the default).
*
* @see Filters
* @param filter a new filter
*/
public void setFilter(@NonNull Filter filter) {
if (mCameraPreview == null) {
mPendingFilter = filter;
} else {
boolean isNoFilter = filter instanceof NoFilter;
boolean isFilterPreview = mCameraPreview instanceof FilterCameraPreview;
// If not a filter preview, we only allow NoFilter (called on creation).
if (!isNoFilter && !isFilterPreview) {
throw new RuntimeException("Filters are only supported by the GL_SURFACE preview." +
" Current preview:" + mPreview);
}
// If we have a filter preview, apply.
if (isFilterPreview) {
((FilterCameraPreview) mCameraPreview).setFilter(filter);
}
// No-op: !isFilterPreview && isNoPreview
}
}
/**
* Returns the current real-time filter applied to the camera preview.
*
* This method will throw an exception if the current preview does not support real-time
* filters. Make sure you use {@link Preview#GL_SURFACE} (the default).
*
* @see #setFilter(Filter)
* @return the current filter
*/
@NonNull
public Filter getFilter() {
if (mCameraPreview == null) {
return mPendingFilter;
} else if (mCameraPreview instanceof FilterCameraPreview) {
return ((FilterCameraPreview) mCameraPreview).getCurrentFilter();
} else {
throw new RuntimeException("Filters are only supported by the GL_SURFACE preview. " +
"Current:" + mPreview);
}
}
//endregion
}
|
/*
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.yardstickframework.writers;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import org.yardstickframework.BenchmarkConfiguration;
import org.yardstickframework.BenchmarkDriver;
import org.yardstickframework.BenchmarkProbe;
import org.yardstickframework.BenchmarkProbePoint;
import org.yardstickframework.BenchmarkProbePointWriter;
import org.yardstickframework.BenchmarkUtils;
import static org.yardstickframework.BenchmarkUtils.WEIGHT_DELIMITER;
import static org.yardstickframework.BenchmarkUtils.fixFolderName;
/**
* CSV probe point writer.
*/
public class BenchmarkProbePointCsvWriter implements BenchmarkProbePointWriter {
/** */
private static final String DUPLICATE_TO_OUTPUT = "BENCHMARK_WRITER_DUPLICATE_TO_OUTPUT";
/** */
private static final boolean DEFAULT_DUPLICATE_TO_OUTPUT = false;
/** */
public static final String META_INFO_SEPARATOR = ",";
/** */
public static final String DRV_NAMES_PREFIX = "@@";
/** */
public static final String META_INFO_PREFIX = "**";
/** */
public static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyyMMdd-HHmmss");
/** */
private PrintWriter writer;
/** */
private BenchmarkConfiguration cfg;
/** */
private BenchmarkDriver drv;
/** */
private long startTime;
/** */
private boolean dupToOutput;
/** */
private File outPath;
/** {@inheritDoc} */
@Override public void start(BenchmarkDriver drv, BenchmarkConfiguration cfg, long startTime) {
this.cfg = cfg;
this.drv = drv;
this.startTime = startTime;
dupToOutput = duplicateToOutput(cfg);
String path = cfg.outputFolder();
File folder = null;
if (path != null) {
folder = new File(path);
if (!folder.exists()) {
if (!folder.mkdirs())
throw new IllegalStateException("Can not create folder: " + folder.getAbsolutePath());
}
}
String desc = drv.description() == null ? "" : drv.description();
desc = desc.replaceAll("-+", "-").replaceAll(",|\\\\|/|\\||%|:|<|>|\\*|\\?|\"|\\s", "-");
desc = desc.charAt(0) == '-' ? desc : '-' + desc;
String subFolderName = FORMAT.format(new Date(startTime));
String hostName = cfg.hostName().isEmpty() ? "" : '-' + cfg.hostName();
if (cfg.driverNames().size() > 1) {
StringBuilder sb = new StringBuilder();
for (String drvName : cfg.driverNames())
sb.append(drvName.split(WEIGHT_DELIMITER)[0].trim()).append('-');
if (sb.length() > 0)
sb.delete(sb.length() - 1, sb.length());
subFolderName += '-' + sb.toString();
subFolderName += File.separator + desc.substring(1) + hostName;
}
else
subFolderName += desc + hostName;
subFolderName = fixFolderName(subFolderName);
outPath = folder == null ? new File(subFolderName) : new File(folder, subFolderName);
if (!outPath.exists()) {
if (!outPath.mkdirs())
throw new IllegalStateException("Can not create folder: " + outPath.getAbsolutePath());
}
}
/** {@inheritDoc} */
@Override public void writePoints(BenchmarkProbe probe, Collection<BenchmarkProbePoint> points) throws Exception {
if (writer == null) {
String fileName = probe.getClass().getSimpleName() + ".csv";
File f = outPath == null ? new File(fileName) : new File(outPath, fileName);
writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f)));
String parent;
// Multiple drivers.
if (cfg.driverNames().size() > 1) {
File outPath0 = outPath.getParentFile();
parent = outPath0.getParent() == null ? outPath.getPath() : outPath0.getPath();
}
else
parent = outPath.getParent() == null ? outPath.getPath() : outPath.getParent();
BenchmarkUtils.println(cfg, probe.getClass().getSimpleName() + " results will be saved to: " + parent);
println("--Probe dump file for probe: " + probe + " (" + probe.getClass() + ")");
println("--Created " + new Date(startTime));
println("--Benchmark config: " + removeUnwantedChars(cfg.toString()));
println("--Description: " + removeUnwantedChars(drv.description() == null ? "" : drv.description()));
println(DRV_NAMES_PREFIX + cfg.driverNames().toString().replaceAll("\\[", "").replaceAll("]", ""));
if (probe.metaInfo() != null && !probe.metaInfo().isEmpty()) {
print(META_INFO_PREFIX);
int i = 0;
for (String metaInfo : probe.metaInfo())
print("\"" + metaInfo + "\"" + (++i == probe.metaInfo().size() ? "" : META_INFO_SEPARATOR));
if (i != 0)
println("");
}
}
for (BenchmarkProbePoint pt : points) {
print(String.valueOf(pt.time()));
print(",");
double[] vals = pt.values();
for (int i = 0; i < vals.length; i++) {
print(String.format(Locale.US, "%.3f", vals[i]));
if (i != vals.length - 1)
print(",");
}
println("");
}
writer.flush();
}
/** {@inheritDoc} */
@Override public void close() throws Exception {
if (writer != null)
writer.close();
}
/**
* @param s String to write.
*/
private void print(String s) {
writer.print(s);
if (dupToOutput)
cfg.output().print(s);
}
/**
* @param s String to write.
*/
private void println(String s) {
writer.println(s);
if (dupToOutput)
BenchmarkUtils.println(cfg, s);
}
/**
* @param val String.
* @return String with removed chars.
*/
private String removeUnwantedChars(String val) {
return val.replaceAll("\n|\t|\r|\f", "");
}
/**
* @param cfg Config.
* @return Flat indicating whether to duplicate to output or not.
*/
private boolean duplicateToOutput(BenchmarkConfiguration cfg) {
try {
return Boolean.parseBoolean(cfg.customProperties().get(DUPLICATE_TO_OUTPUT));
}
catch (NumberFormatException | NullPointerException ignored) {
return DEFAULT_DUPLICATE_TO_OUTPUT;
}
}
}
|
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
//----------------------------------------------------
// THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST.
//----------------------------------------------------
package co.elastic.clients.elasticsearch.core;
import co.elastic.clients.elasticsearch._types.ErrorResponse;
import co.elastic.clients.elasticsearch._types.ExpandWildcard;
import co.elastic.clients.elasticsearch._types.RequestBase;
import co.elastic.clients.elasticsearch._types.SearchType;
import co.elastic.clients.elasticsearch.core.msearch.RequestItem;
import co.elastic.clients.json.JsonpDeserializable;
import co.elastic.clients.json.JsonpDeserializer;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.JsonpSerializable;
import co.elastic.clients.json.NdJsonpSerializable;
import co.elastic.clients.json.ObjectBuilderDeserializer;
import co.elastic.clients.json.ObjectDeserializer;
import co.elastic.clients.transport.Endpoint;
import co.elastic.clients.transport.endpoints.SimpleEndpoint;
import co.elastic.clients.util.ListBuilder;
import co.elastic.clients.util.ModelTypeHelper;
import co.elastic.clients.util.ObjectBuilder;
import co.elastic.clients.util.ObjectBuilderBase;
import jakarta.json.stream.JsonGenerator;
import java.lang.Boolean;
import java.lang.Long;
import java.lang.String;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
// typedef: _global.msearch.Request
public class MsearchRequest extends RequestBase implements NdJsonpSerializable, JsonpSerializable {
@Nullable
private final Boolean allowNoIndices;
@Nullable
private final Boolean ccsMinimizeRoundtrips;
private final List<ExpandWildcard> expandWildcards;
@Nullable
private final Boolean ignoreThrottled;
@Nullable
private final Boolean ignoreUnavailable;
private final List<String> index;
@Nullable
private final Long maxConcurrentSearches;
@Nullable
private final Long maxConcurrentShardRequests;
@Nullable
private final Long preFilterShardSize;
@Nullable
private final SearchType searchType;
private final List<RequestItem> searches;
// ---------------------------------------------------------------------------------------------
private MsearchRequest(Builder builder) {
this.allowNoIndices = builder.allowNoIndices;
this.ccsMinimizeRoundtrips = builder.ccsMinimizeRoundtrips;
this.expandWildcards = ModelTypeHelper.unmodifiable(builder.expandWildcards);
this.ignoreThrottled = builder.ignoreThrottled;
this.ignoreUnavailable = builder.ignoreUnavailable;
this.index = ModelTypeHelper.unmodifiable(builder.index);
this.maxConcurrentSearches = builder.maxConcurrentSearches;
this.maxConcurrentShardRequests = builder.maxConcurrentShardRequests;
this.preFilterShardSize = builder.preFilterShardSize;
this.searchType = builder.searchType;
this.searches = ModelTypeHelper.unmodifiableRequired(builder.searches, this, "searches");
}
public static MsearchRequest of(Consumer<Builder> fn) {
Builder builder = new Builder();
fn.accept(builder);
return builder.build();
}
@Override
public Iterator<?> _serializables() {
return this.searches.iterator();
}
/**
* If false, the request returns an error if any wildcard expression, index
* alias, or _all value targets only missing or closed indices. This behavior
* applies even if the request targets other open indices. For example, a
* request targeting foo*,bar* returns an error if an index starts with foo but
* no index starts with bar.
* <p>
* API name: {@code allow_no_indices}
*/
@Nullable
public final Boolean allowNoIndices() {
return this.allowNoIndices;
}
/**
* If true, network roundtrips between the coordinating node and remote clusters
* are minimized for cross-cluster search requests.
* <p>
* API name: {@code ccs_minimize_roundtrips}
*/
@Nullable
public final Boolean ccsMinimizeRoundtrips() {
return this.ccsMinimizeRoundtrips;
}
/**
* Type of index that wildcard expressions can match. If the request can target
* data streams, this argument determines whether wildcard expressions match
* hidden data streams.
* <p>
* API name: {@code expand_wildcards}
*/
public final List<ExpandWildcard> expandWildcards() {
return this.expandWildcards;
}
/**
* If true, concrete, expanded or aliased indices are ignored when frozen.
* <p>
* API name: {@code ignore_throttled}
*/
@Nullable
public final Boolean ignoreThrottled() {
return this.ignoreThrottled;
}
/**
* If true, missing or closed indices are not included in the response.
* <p>
* API name: {@code ignore_unavailable}
*/
@Nullable
public final Boolean ignoreUnavailable() {
return this.ignoreUnavailable;
}
/**
* Comma-separated list of data streams, indices, and index aliases to search.
* <p>
* API name: {@code index}
*/
public final List<String> index() {
return this.index;
}
/**
* Maximum number of concurrent searches the multi search API can execute.
* <p>
* API name: {@code max_concurrent_searches}
*/
@Nullable
public final Long maxConcurrentSearches() {
return this.maxConcurrentSearches;
}
/**
* Maximum number of concurrent shard requests that each sub-search request
* executes per node.
* <p>
* API name: {@code max_concurrent_shard_requests}
*/
@Nullable
public final Long maxConcurrentShardRequests() {
return this.maxConcurrentShardRequests;
}
/**
* Defines a threshold that enforces a pre-filter roundtrip to prefilter search
* shards based on query rewriting if the number of shards the search request
* expands to exceeds the threshold. This filter roundtrip can limit the number
* of shards significantly if for instance a shard can not match any documents
* based on its rewrite method i.e., if date filters are mandatory to match but
* the shard bounds and the query are disjoint.
* <p>
* API name: {@code pre_filter_shard_size}
*/
@Nullable
public final Long preFilterShardSize() {
return this.preFilterShardSize;
}
/**
* Indicates whether global term and document frequencies should be used when
* scoring returned documents.
* <p>
* API name: {@code search_type}
*/
@Nullable
public final SearchType searchType() {
return this.searchType;
}
/**
* Required - Request body.
* <p>
* API name: {@code _value_body}
*/
public final List<RequestItem> searches() {
return this.searches;
}
/**
* Serialize this value to JSON.
*/
public void serialize(JsonGenerator generator, JsonpMapper mapper) {
generator.writeStartArray();
for (RequestItem item0 : this.searches) {
item0.serialize(generator, mapper);
}
generator.writeEnd();
}
// ---------------------------------------------------------------------------------------------
/**
* Builder for {@link MsearchRequest}.
*/
public static class Builder extends ObjectBuilderBase implements ObjectBuilder<MsearchRequest> {
@Nullable
private Boolean allowNoIndices;
@Nullable
private Boolean ccsMinimizeRoundtrips;
@Nullable
private List<ExpandWildcard> expandWildcards;
@Nullable
private Boolean ignoreThrottled;
@Nullable
private Boolean ignoreUnavailable;
@Nullable
private List<String> index;
@Nullable
private Long maxConcurrentSearches;
@Nullable
private Long maxConcurrentShardRequests;
@Nullable
private Long preFilterShardSize;
@Nullable
private SearchType searchType;
private List<RequestItem> searches;
/**
* If false, the request returns an error if any wildcard expression, index
* alias, or _all value targets only missing or closed indices. This behavior
* applies even if the request targets other open indices. For example, a
* request targeting foo*,bar* returns an error if an index starts with foo but
* no index starts with bar.
* <p>
* API name: {@code allow_no_indices}
*/
public final Builder allowNoIndices(@Nullable Boolean value) {
this.allowNoIndices = value;
return this;
}
/**
* If true, network roundtrips between the coordinating node and remote clusters
* are minimized for cross-cluster search requests.
* <p>
* API name: {@code ccs_minimize_roundtrips}
*/
public final Builder ccsMinimizeRoundtrips(@Nullable Boolean value) {
this.ccsMinimizeRoundtrips = value;
return this;
}
/**
* Type of index that wildcard expressions can match. If the request can target
* data streams, this argument determines whether wildcard expressions match
* hidden data streams.
* <p>
* API name: {@code expand_wildcards}
*/
public final Builder expandWildcards(@Nullable List<ExpandWildcard> value) {
this.expandWildcards = value;
return this;
}
/**
* Type of index that wildcard expressions can match. If the request can target
* data streams, this argument determines whether wildcard expressions match
* hidden data streams.
* <p>
* API name: {@code expand_wildcards}
*/
public final Builder expandWildcards(ExpandWildcard... value) {
this.expandWildcards = Arrays.asList(value);
return this;
}
/**
* If true, concrete, expanded or aliased indices are ignored when frozen.
* <p>
* API name: {@code ignore_throttled}
*/
public final Builder ignoreThrottled(@Nullable Boolean value) {
this.ignoreThrottled = value;
return this;
}
/**
* If true, missing or closed indices are not included in the response.
* <p>
* API name: {@code ignore_unavailable}
*/
public final Builder ignoreUnavailable(@Nullable Boolean value) {
this.ignoreUnavailable = value;
return this;
}
/**
* Comma-separated list of data streams, indices, and index aliases to search.
* <p>
* API name: {@code index}
*/
public final Builder index(@Nullable List<String> value) {
this.index = value;
return this;
}
/**
* Comma-separated list of data streams, indices, and index aliases to search.
* <p>
* API name: {@code index}
*/
public final Builder index(String... value) {
this.index = Arrays.asList(value);
return this;
}
/**
* Maximum number of concurrent searches the multi search API can execute.
* <p>
* API name: {@code max_concurrent_searches}
*/
public final Builder maxConcurrentSearches(@Nullable Long value) {
this.maxConcurrentSearches = value;
return this;
}
/**
* Maximum number of concurrent shard requests that each sub-search request
* executes per node.
* <p>
* API name: {@code max_concurrent_shard_requests}
*/
public final Builder maxConcurrentShardRequests(@Nullable Long value) {
this.maxConcurrentShardRequests = value;
return this;
}
/**
* Defines a threshold that enforces a pre-filter roundtrip to prefilter search
* shards based on query rewriting if the number of shards the search request
* expands to exceeds the threshold. This filter roundtrip can limit the number
* of shards significantly if for instance a shard can not match any documents
* based on its rewrite method i.e., if date filters are mandatory to match but
* the shard bounds and the query are disjoint.
* <p>
* API name: {@code pre_filter_shard_size}
*/
public final Builder preFilterShardSize(@Nullable Long value) {
this.preFilterShardSize = value;
return this;
}
/**
* Indicates whether global term and document frequencies should be used when
* scoring returned documents.
* <p>
* API name: {@code search_type}
*/
public final Builder searchType(@Nullable SearchType value) {
this.searchType = value;
return this;
}
/**
* Required - Request body.
* <p>
* API name: {@code _value_body}
*/
public final Builder searches(List<RequestItem> value) {
this.searches = value;
return this;
}
/**
* Required - Request body.
* <p>
* API name: {@code _value_body}
*/
public final Builder searches(RequestItem... value) {
this.searches = Arrays.asList(value);
return this;
}
/**
* Required - Request body.
* <p>
* API name: {@code _value_body}
*/
public final Builder searches(
Function<ListBuilder<RequestItem, RequestItem.Builder>, ObjectBuilder<List<RequestItem>>> fn) {
return searches(fn.apply(new ListBuilder<>(RequestItem.Builder::new)).build());
}
/**
* Builds a {@link MsearchRequest}.
*
* @throws NullPointerException
* if some of the required fields are null.
*/
public MsearchRequest build() {
_checkSingleUse();
return new MsearchRequest(this);
}
}
// ---------------------------------------------------------------------------------------------
/**
* Endpoint "{@code msearch}".
*/
public static final SimpleEndpoint<MsearchRequest, ?> _ENDPOINT = new SimpleEndpoint<>("es/msearch",
// Request method
request -> {
return "POST";
},
// Request path
request -> {
final int _index = 1 << 0;
int propsSet = 0;
if (ModelTypeHelper.isDefined(request.index()))
propsSet |= _index;
if (propsSet == 0) {
StringBuilder buf = new StringBuilder();
buf.append("/_msearch");
return buf.toString();
}
if (propsSet == (_index)) {
StringBuilder buf = new StringBuilder();
buf.append("/");
SimpleEndpoint.pathEncode(request.index.stream().map(v -> v).collect(Collectors.joining(",")), buf);
buf.append("/_msearch");
return buf.toString();
}
throw SimpleEndpoint.noPathTemplateFound("path");
},
// Request parameters
request -> {
Map<String, String> params = new HashMap<>();
params.put("typed_keys", "true");
if (request.preFilterShardSize != null) {
params.put("pre_filter_shard_size", String.valueOf(request.preFilterShardSize));
}
if (request.maxConcurrentShardRequests != null) {
params.put("max_concurrent_shard_requests", String.valueOf(request.maxConcurrentShardRequests));
}
if (ModelTypeHelper.isDefined(request.expandWildcards)) {
params.put("expand_wildcards",
request.expandWildcards.stream().map(v -> v.jsonValue()).collect(Collectors.joining(",")));
}
if (request.ignoreUnavailable != null) {
params.put("ignore_unavailable", String.valueOf(request.ignoreUnavailable));
}
if (request.allowNoIndices != null) {
params.put("allow_no_indices", String.valueOf(request.allowNoIndices));
}
if (request.ignoreThrottled != null) {
params.put("ignore_throttled", String.valueOf(request.ignoreThrottled));
}
if (request.maxConcurrentSearches != null) {
params.put("max_concurrent_searches", String.valueOf(request.maxConcurrentSearches));
}
if (request.searchType != null) {
params.put("search_type", request.searchType.jsonValue());
}
if (request.ccsMinimizeRoundtrips != null) {
params.put("ccs_minimize_roundtrips", String.valueOf(request.ccsMinimizeRoundtrips));
}
return params;
}, SimpleEndpoint.emptyMap(), true, MsearchResponse._DESERIALIZER);
/**
* Create an "{@code msearch}" endpoint.
*/
public static <TDocument> Endpoint<MsearchRequest, MsearchResponse<TDocument>, ErrorResponse> createMsearchEndpoint(
JsonpDeserializer<TDocument> tDocumentDeserializer) {
return _ENDPOINT
.withResponseDeserializer(MsearchResponse.createMsearchResponseDeserializer(tDocumentDeserializer));
}
}
|
package de.karlw.pbac.reservations;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.extension.sdk.api.packets.general.Qos;
import com.hivemq.extension.sdk.api.services.Services;
import com.hivemq.extension.sdk.api.services.builder.Builders;
import com.hivemq.extension.sdk.api.services.subscription.TopicSubscription;
import de.karlw.pbac.PurposeManager;
import de.karlw.pbac.PurposeSettings;
import de.karlw.pbac.purpose.Purpose;
import de.karlw.pbac.purpose.PurposeCombiner;
import de.karlw.pbac.purpose.PurposeSet;
import de.karlw.pbac.purpose.PurposeTopic;
import de.karlw.pbac.subscriptions.SubscriptionAPDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class NaiveReservationDirectory implements ReservationDirectory {
private static final @NotNull Logger log = LoggerFactory.getLogger(NaiveReservationDirectory.class);
private static Counter reservationsCounter = null;
public enum AllowMode {
ANY, ALL, DIRECT, BROADEST, SPECIFIC
}
// create the new metric, that is increased when a client isn't successfully authenticated
Map<String, Reservation> reservations;
public NaiveReservationDirectory() {
this.reservations = new HashMap<>();
log.debug("creating reservation directory");
final MetricRegistry metricRegistry = Services.metricRegistry();
reservationsCounter = metricRegistry.counter("de.karlw.pbac.reservations");
reservationsCounter.dec(reservationsCounter.getCount()); // reset
}
public void addReservation(Reservation reservation) {
String key = reservation.topic;
// log.debug("adding reservation in {}", hashCode());
if (!reservation.hasPurposes()) {
log.debug("removing reservation for {}", key);
if (this.reservations.remove(key) != null) {
reservationsCounter.dec();
}
} else {
log.debug("updating reservation for {}: {}", key, reservation.aip.toString());
if (null == this.reservations.put(key, reservation)) {
reservationsCounter.inc();
}
}
updateSubscriptionsForReservation(reservation);
}
public void clearTopic(String topic) {
this.reservations.remove(topic);
}
public Collection<Reservation> getAllReservations() {
return reservations.values();
}
public Reservation getReservation(String topic) {
Reservation r = this.reservations.get(topic);
// log.debug("checking for reservation: {}, found {}", topic, r);
return r;
}
public PurposeSet getSpecificAipForTopic(String topic) {
Reservation r = getReservation(topic);
if (r != null) {
return r.aip;
} else {
return null;
}
}
public boolean isTopicAllowed(String topic, Purpose ap) {
PurposeSet aip = getAipForTopic(topic);
if (aip == null || aip.isEmpty()) {
log.debug("no reservations for {}", topic);
// Services.metricRegistry().counter("de.karlw.pbac.allowed_no_ap").inc();
return PurposeSettings.getInstance().getSetting("allow_without_reservation", true);
} else {
if (aip.allowsPurpose(ap)) {
log.debug("allowing {} for {}, allowed are {}", topic, ap, aip.toString());
// Services.metricRegistry().counter("de.karlw.pbac.allowed_ap").inc();
return true;
} else {
Services.metricRegistry().counter("de.karlw.pbac.forbidden").inc();
// log.debug("forbidding {} for {}, allowed are {}", topic, ap, aip.toString());
return false;
}
}
}
@Override
public void logTree() {
log.debug(reservationOverview());
}
/**
* this finds specific reservations that might get bypassed
* by a wildcard subscription (affected)
*
* @param topic
* @return
*/
public List<Reservation> getAffectedReservations(String topic) {
List<Reservation> matchingReservations = new ArrayList<>();
log.debug("affected reservations for {}:", topic);
reservations.forEach((rTopic, reservation) -> {
if (PurposeTopic.topicMatches(topic, rTopic) && !topic.equals(rTopic)) {
matchingReservations.add(reservation);
log.debug(" - {}", reservation.toString());
}
});
return matchingReservations;
}
/**
* combined
* @param topic
* @return
*/
public List<Reservation> getCombinedReservations(String topic) {
// String[] nodes = topic.split("/");
List<Reservation> matchingReservations = new ArrayList<>();
// this method is more efficient, but would require a lot of iterations
// when looking for PLUS reservations. could be improved in the future,
// however the tree store is faster anyway
// String nodeBuilt = "";
// for (String nodeI : nodes) {
// String wildcardTopicI = nodeBuilt + "#";
// Reservation nodeIReservation = this.getReservation(wildcardTopicI);
// if (nodeIReservation != null) {
// matchingReservations.add(nodeIReservation);
// }
//
// // node is appended at the END, which is intended:
// // example: my/great/topic
// // - include #
// // - don't include my/great/topic/#
// nodeBuilt += nodeI + "/";
// }
//
// // include exact reservation at the end, because
// Reservation exactReservation = this.getReservation(topic);
// if (exactReservation != null) {
// log.debug("found exact reservation ({})", topic);
// matchingReservations.add(exactReservation);
// }
reservations.forEach((rTopic, reservation) -> {
// log.debug("{} filtered by {} ?", rTopic, topic);
if (PurposeTopic.topicMatches(rTopic, topic)) {
// log.debug("YES!");
matchingReservations.add(reservation);
}
});
log.debug("found {} matching broader reservations for {}", matchingReservations.size(), topic);
matchingReservations.forEach((reservation -> {
log.debug(" - {}", reservation.toString());
}));
return matchingReservations;
}
public PurposeSet getAipForTopic(String topic) {
// todo: combine more freely
PurposeCombiner aipc = new PurposeCombiner();
aipc.combine(getCombinedAIPForTopic(topic));
aipc.combine(getAffectedAIPForTopic(topic), true);
return aipc.getAip();
}
public String reservationOverview() {
String r = "";
for (Reservation reservation : reservations.values()) {
r += reservation.topic + " - " + reservation.aip.toString() + "\n";
}
return r;
}
public static PurposeSet combineReservationAIP(List<Reservation> reservations, boolean restrict) {
PurposeCombiner aipc = new PurposeCombiner();
reservations.forEach((reservation) -> { aipc.combine(reservation.aip, restrict); });
return aipc.getAip();
}
/**
* depending on settings, pause subscriptions or flag them as hybrid
* @param reservation
*/
private void updateSubscriptionsForReservation(Reservation reservation) {
if (!PurposeSettings.get("filter_on_subscribe") && !PurposeSettings.get("filter_hybrid")) {
return;
}
boolean includeAffected = PurposeSettings.get("filter_on_subscribe");
SubscriptionAPDirectory subscriptionAPs = PurposeManager.getInstance().getSubscriptionAPDirectory();
subscriptionAPs.getTopicSubscriptions(reservation.topic, includeAffected).forEach((sub) -> {
log.debug("rechecking {}", sub);
PurposeSet aip = getAipForTopic(sub.topic);
if (Arrays.asList(PurposeTopic.AAA_CLIENTS).contains(sub.clientId)) {
log.debug("keeping subscription for whitelisted client");
} else if (aip == null || aip.allowsPurpose(sub.ap)) {
log.debug("compatible -- will add or keep");
TopicSubscription ts = Builders.topicSubscription()
.topicFilter(sub.topic)
.qos(Qos.valueOf(sub.qos))
.build();
Services.subscriptionStore().addSubscription(sub.clientId, ts);
} else {
log.debug("aip {} is incompatible with ap {}", aip, sub.ap);
log.info("pausing subscription {} for {}", sub.topic, sub.clientId);
Services.subscriptionStore().removeSubscription(sub.clientId, sub.topic);
}
});
}
public void clearAll() {
log.warn("clearing all reservations");
reservationsCounter.dec(reservations.size());
this.reservations = new HashMap<>();
}
@Override
public PurposeSet getCombinedAIPForTopic(String topic) {
return combineReservationAIP(getCombinedReservations(topic), false); // todo
}
@Override
public PurposeSet getAffectedAIPForTopic(String topic) {
return combineReservationAIP(getAffectedReservations(topic), true);
}
}
|
package me.chanjar.weixin.common.util.crypto;
import org.apache.commons.codec.digest.DigestUtils;
import java.util.Arrays;
/**
* Created by Daniel Qian on 14/10/19.
*/
public class SHA1 {
/**
* 串接arr参数,生成sha1 digest
*/
public static String gen(String... arr) {
Arrays.sort(arr);
StringBuilder sb = new StringBuilder();
for (String a : arr) {
sb.append(a);
}
return DigestUtils.sha1Hex(sb.toString());
}
/**
* 用&串接arr参数,生成sha1 digest
*/
public static String genWithAmple(String... arr) {
Arrays.sort(arr);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
String a = arr[i];
sb.append(a);
if (i != arr.length - 1) {
sb.append('&');
}
}
return DigestUtils.sha1Hex(sb.toString());
}
}
|
package io.github.edmm.model.support;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.github.edmm.model.component.RootComponent;
import io.github.edmm.model.relation.DependsOn;
import io.github.edmm.model.relation.RootRelation;
import org.yaml.snakeyaml.Yaml;
public class EdmmYamlBuilder {
private final Map<String, Object> mainMap;
private final Map<String, Object> componentsMap;
private Map<String, Object> componentsTypeMap;
private Map<String, Object> relationsTypeMap;
// this variables are used to record the component that is being modelled
// once another component will be added, they will be used to add the component to the componentsMap
// and will be ready again to accept the new component's information
private Class<? extends RootComponent> currentComponentClass ;
private String currentComponentName;
private List<Map<String, Object>> currentRelations ;
public EdmmYamlBuilder () {
componentsTypeMap = new HashMap<>();
relationsTypeMap = new HashMap<>();
componentsMap = new HashMap<>();
mainMap = new HashMap<>();
currentComponentClass = null;
currentRelations = new ArrayList<>();
}
/**
* Adds a component under the 'components' section
* @param componentName a unique name for the component to avoid duplicates
*/
public EdmmYamlBuilder component(Class<? extends RootComponent> componentClass, String componentName) {
flushCurrentComponent();
currentComponentClass = componentClass;
currentComponentName = componentName;
return this;
}
public EdmmYamlBuilder component(Class<? extends RootComponent> componentClass) {
return component(componentClass, componentClass.getSimpleName());
}
private EdmmYamlBuilder relation(String relationType,Class<? extends RootComponent> componentClass, String componentName) {
Map<String, Object> relationMap = new HashMap<>();
relationMap.put(relationType, componentName);
currentRelations.add(relationMap);
return this;
}
/**
* Adds 'hosted_on' to the previously specified component
* @param componentClass the class hosting the component
* @param componentName the unique name of the hosting component
*/
public EdmmYamlBuilder hostedOn(Class<? extends RootComponent> componentClass, String componentName) {
return relation("hosted_on", componentClass, componentName);
}
public EdmmYamlBuilder hostedOn(Class<? extends RootComponent> componentClass) {
return hostedOn( componentClass, componentClass.getSimpleName());
}
/**
* Adds 'depends_on' to the previously specified component
* @param componentClass the target class of the relation
* @param componentName the unique name of the target component
*/
public EdmmYamlBuilder dependsOn(Class<? extends RootComponent> componentClass, String componentName) {
return relation("depends_on", componentClass, componentName);
}
public EdmmYamlBuilder dependsOn(Class<? extends RootComponent> componentClass) {
return dependsOn( componentClass, componentClass.getSimpleName());
}
/**
* Adds 'connects_to' to the previously specified component
* @param componentClass the target class of the relation
* @param componentName the unique name of the target component
*/
public EdmmYamlBuilder connectsTo(Class<? extends RootComponent> componentClass, String componentName) {
return relation("connects_to", componentClass, componentName);
}
public EdmmYamlBuilder connectsTo(Class<? extends RootComponent> componentClass) {
return connectsTo( componentClass, componentClass.getSimpleName());
}
public String build() {
flushCurrentComponent();
populateTypeMaps();
mainMap.put("components", componentsMap);
mainMap.put("relation_types",relationsTypeMap);
mainMap.put("component_types", componentsTypeMap);
return new Yaml().dumpAsMap(mainMap);
}
public Map<String,Object> getComponentsMap() {
flushCurrentComponent();
return this.componentsMap;
}
/**
* It adds the currentComponent and the currentRelations to the componentsMap.
* This function needs to be called every time a new component is added, so that the currentComponent will be saved
* and there will be room for the new one.
* It is also called at build time, to save the last component added.
*/
private void flushCurrentComponent() {
if (currentComponentClass != null ) {
Map<String, Object> componentMap = new HashMap<>();
if (! currentRelations.isEmpty())
componentMap.put("relations", currentRelations);
// here we can add also operations and properties with the same mechanism
componentMap.put("type", TypeResolver.resolve(currentComponentClass));
componentsMap.put(currentComponentName, componentMap);
}
currentComponentClass = null;
currentRelations = new ArrayList<>();
}
/**
* This functions populates the componentsTypeMap and the relationsTypeMap in order to create the
* 'component_types' and 'relation_types? sections of the yaml in an automatic way
*/
private void populateTypeMaps() {
Set<String> typeSet = TypeResolver.typeSet();
for (String type : typeSet) {
Class<? extends ModelEntity> modelEntity = TypeResolver.resolve(type);
if (RootComponent.class.isAssignableFrom(modelEntity)) {
// type is a component type
Class<? extends RootComponent> rootComponent = modelEntity.asSubclass(RootComponent.class);
Object extendsType = (RootComponent.class == modelEntity) ? null : TypeResolver.resolve((Class<? extends ModelEntity>) rootComponent.getSuperclass());
Map<String, Object> extendsMap = new HashMap<>();
extendsMap.put("extends",extendsType);
componentsTypeMap.put(type,extendsMap);
} else if (RootRelation.class.isAssignableFrom(modelEntity)) {
// type is a relation type
Class<? extends RootRelation> rootRelation = modelEntity.asSubclass(RootRelation.class);
Object extendsType = (DependsOn.class == modelEntity) ? null : TypeResolver.resolve((Class<? extends ModelEntity>) rootRelation.getSuperclass());
Map<String, Object> extendsMap = new HashMap<>();
extendsMap.put("extends",extendsType);
relationsTypeMap.put(type,extendsMap);
}
}
}
}
|
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.method.annotation;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.Assert;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Handler for return values of type {@link ResponseBodyEmitter} (and the
* {@code ResponseEntity<ResponseBodyEmitter>} sub-class) as well as any other
* async type with a {@link #getAdapterMap() registered adapter}.
*
* @author Rossen Stoyanchev
* @since 4.2
*/
public class ResponseBodyEmitterReturnValueHandler implements AsyncHandlerMethodReturnValueHandler {
private static final Log logger = LogFactory.getLog(ResponseBodyEmitterReturnValueHandler.class);
private final List<HttpMessageConverter<?>> messageConverters;
private final Map<Class<?>, ResponseBodyEmitterAdapter> adapterMap;
public ResponseBodyEmitterReturnValueHandler(List<HttpMessageConverter<?>> messageConverters) {
Assert.notEmpty(messageConverters, "'messageConverters' must not be empty");
this.messageConverters = messageConverters;
this.adapterMap = new HashMap<Class<?>, ResponseBodyEmitterAdapter>(3);
this.adapterMap.put(ResponseBodyEmitter.class, new SimpleResponseBodyEmitterAdapter());
}
/**
* Return the map with {@code ResponseBodyEmitter} adapters.
* By default the map contains a single adapter {@code ResponseBodyEmitter}
* that simply downcasts the return value.
* @return the map of adapters
*/
public Map<Class<?>, ResponseBodyEmitterAdapter> getAdapterMap() {
return this.adapterMap;
}
private ResponseBodyEmitterAdapter getAdapterFor(Class<?> type) {
if (type != null) {
for (Class<?> adapteeType : getAdapterMap().keySet()) {
if (adapteeType.isAssignableFrom(type)) {
return getAdapterMap().get(adapteeType);
}
}
}
return null;
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
Class<?> bodyType;
if (ResponseEntity.class.isAssignableFrom(returnType.getParameterType())) {
bodyType = ResolvableType.forMethodParameter(returnType).getGeneric(0).resolve();
}
else {
bodyType = returnType.getParameterType();
}
return (getAdapterFor(bodyType) != null);
}
@Override
public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) {
if (returnValue != null) {
Object adaptFrom = returnValue;
if (returnValue instanceof ResponseEntity) {
adaptFrom = ((ResponseEntity) returnValue).getBody();
}
if (adaptFrom != null) {
return (getAdapterFor(adaptFrom.getClass()) != null);
}
}
return false;
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if (returnValue == null) {
mavContainer.setRequestHandled(true);
return;
}
HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
if (returnValue instanceof ResponseEntity) {
ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnValue;
response.setStatus(responseEntity.getStatusCodeValue());
outputMessage.getHeaders().putAll(responseEntity.getHeaders());
returnValue = responseEntity.getBody();
if (returnValue == null) {
mavContainer.setRequestHandled(true);
return;
}
}
ServletRequest request = webRequest.getNativeRequest(ServletRequest.class);
ShallowEtagHeaderFilter.disableContentCaching(request);
ResponseBodyEmitterAdapter adapter = getAdapterFor(returnValue.getClass());
Assert.notNull(adapter);
ResponseBodyEmitter emitter = adapter.adaptToEmitter(returnValue, outputMessage);
emitter.extendResponse(outputMessage);
// Commit the response and wrap to ignore further header changes
outputMessage.getBody();
outputMessage.flush();
outputMessage = new StreamingServletServerHttpResponse(outputMessage);
DeferredResult<?> deferredResult = new DeferredResult<Object>(emitter.getTimeout());
WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);
HttpMessageConvertingHandler handler = new HttpMessageConvertingHandler(outputMessage, deferredResult);
emitter.initialize(handler);
}
/**
* Adapter for {@code ResponseBodyEmitter} return values.
*/
private static class SimpleResponseBodyEmitterAdapter implements ResponseBodyEmitterAdapter {
@Override
public ResponseBodyEmitter adaptToEmitter(Object returnValue, ServerHttpResponse response) {
Assert.isInstanceOf(ResponseBodyEmitter.class, returnValue);
return (ResponseBodyEmitter) returnValue;
}
}
/**
* ResponseBodyEmitter.Handler that writes with HttpMessageConverter's.
*/
private class HttpMessageConvertingHandler implements ResponseBodyEmitter.Handler {
private final ServerHttpResponse outputMessage;
private final DeferredResult<?> deferredResult;
public HttpMessageConvertingHandler(ServerHttpResponse outputMessage, DeferredResult<?> deferredResult) {
this.outputMessage = outputMessage;
this.deferredResult = deferredResult;
}
@Override
public void send(Object data, MediaType mediaType) throws IOException {
sendInternal(data, mediaType);
}
@SuppressWarnings("unchecked")
private <T> void sendInternal(T data, MediaType mediaType) throws IOException {
for (HttpMessageConverter<?> converter : ResponseBodyEmitterReturnValueHandler.this.messageConverters) {
if (converter.canWrite(data.getClass(), mediaType)) {
((HttpMessageConverter<T>) converter).write(data, mediaType, this.outputMessage);
this.outputMessage.flush();
if (logger.isDebugEnabled()) {
logger.debug("Written [" + data + "] using [" + converter + "]");
}
return;
}
}
throw new IllegalArgumentException("No suitable converter for " + data.getClass());
}
@Override
public void complete() {
this.deferredResult.setResult(null);
}
@Override
public void completeWithError(Throwable failure) {
this.deferredResult.setErrorResult(failure);
}
@Override
public void onTimeout(Runnable callback) {
this.deferredResult.onTimeout(callback);
}
@Override
public void onCompletion(Runnable callback) {
this.deferredResult.onCompletion(callback);
}
}
/**
* Wrap to silently ignore header changes HttpMessageConverter's that would
* otherwise cause HttpHeaders to raise exceptions.
*/
private static class StreamingServletServerHttpResponse implements ServerHttpResponse {
private final ServerHttpResponse delegate;
private final HttpHeaders mutableHeaders = new HttpHeaders();
public StreamingServletServerHttpResponse(ServerHttpResponse delegate) {
this.delegate = delegate;
this.mutableHeaders.putAll(delegate.getHeaders());
}
@Override
public void setStatusCode(HttpStatus status) {
this.delegate.setStatusCode(status);
}
@Override
public HttpHeaders getHeaders() {
return this.mutableHeaders;
}
@Override
public OutputStream getBody() throws IOException {
return this.delegate.getBody();
}
@Override
public void flush() throws IOException {
this.delegate.flush();
}
@Override
public void close() {
this.delegate.close();
}
}
}
|
package org.firstinspires.ftc.teamcode.sensors;
import com.qualcomm.robotcore.hardware.I2cAddr;
import com.qualcomm.robotcore.hardware.I2cDeviceSynch;
import com.qualcomm.robotcore.hardware.I2cDeviceSynchDevice;
import com.qualcomm.robotcore.hardware.I2cWaitControl;
import com.qualcomm.robotcore.hardware.configuration.annotations.DeviceProperties;
import com.qualcomm.robotcore.hardware.configuration.annotations.I2cDeviceType;
import com.qualcomm.robotcore.util.TypeConversion;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.HardwareBeep;
@I2cDeviceType
@DeviceProperties(name = "Maxbotics MB1242", description = "MaxSonar I2CXL Sensor from Maxbotix", xmlTag = "MB1242A")
public class SensorMB1242 extends I2cDeviceSynchDevice<I2cDeviceSynch> implements Runnable {
Telemetry telemetry;
HardwareBeep robot = null;
private Thread thread;
private boolean autoPing;
private int autoPingDelay;
private long lastPingTime = Long.MAX_VALUE;
private int lastDistance = Integer.MAX_VALUE;
private long minDelay = 100;
public SensorMB1242(I2cDeviceSynch deviceClient) {
super(deviceClient, true);
this.deviceClient.setI2cAddress(I2cAddr.create8bit(0xE0));
super.registerArmingStateCallback(false);
this.deviceClient.engage();
}
public void setAutoPingDelay(int delay) {
autoPingDelay = delay;
}
@Override
public Manufacturer getManufacturer() {
return Manufacturer.Other;
}
@Override
protected synchronized boolean doInitialize() {
return true;
}
@Override
public String getDeviceName() {
return "MaxSonar I2CXL";
}
public void setI2cAddress(I2cAddr i2cAddr) {
deviceClient.setI2cAddress(i2cAddr);
}
public void ping() {
lastPingTime = System.currentTimeMillis();
deviceClient.write8(0, 0x51, I2cWaitControl.ATOMIC);
}
public void changeI2cAddress(int i2cAddress) {
deviceClient.write8(0, 0xaa, I2cWaitControl.ATOMIC);
deviceClient.write8(0, 0xa5, I2cWaitControl.ATOMIC);
deviceClient.write8(0, i2cAddress, I2cWaitControl.ATOMIC);
this.deviceClient.setI2cAddress(I2cAddr.create8bit(i2cAddress));
}
public void setMinDelay(int minDelay) {
this.minDelay = minDelay;
}
public void startAutoPing(int delay) {
if (thread == null) {
thread = new Thread(this);
}
autoPingDelay = delay;
autoPing = true;
telemetry.addData("SensorMB1242", "startAutoPing");
telemetry.update();
thread.start();
//run();
}
public void stopAutoPing() {
autoPing = false;
thread = null;
}
public int getDistance() {
long currentTimeMillis = System.currentTimeMillis();
int distance;
if (currentTimeMillis - lastPingTime < minDelay) {
distance = lastDistance;
} else {
distance = TypeConversion.byteArrayToShort(deviceClient.read(0x01, 2));
lastDistance = distance;
}
distance = TypeConversion.byteArrayToShort(deviceClient.read(0x01, 2));
return distance;
}
@Override
public void run() {
while (autoPing) {
//Thread.sleep(40);
// ping();
//
// try
//
// {
// Thread.sleep(autoPingDelay);
// }
// catch (InterruptedException e){
// }
}
}
}
|
package cn.pandacoder.gulimall.member.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.pandacoder.common.utils.PageUtils;
import cn.pandacoder.common.utils.Query;
import cn.pandacoder.gulimall.member.dao.MemberLoginLogDao;
import cn.pandacoder.gulimall.member.entity.MemberLoginLogEntity;
import cn.pandacoder.gulimall.member.service.MemberLoginLogService;
@Service("memberLoginLogService")
public class MemberLoginLogServiceImpl extends ServiceImpl<MemberLoginLogDao, MemberLoginLogEntity> implements MemberLoginLogService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<MemberLoginLogEntity> page = this.page(
new Query<MemberLoginLogEntity>().getPage(params),
new QueryWrapper<MemberLoginLogEntity>()
);
return new PageUtils(page);
}
}
|
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.logstash;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class StringInterpolationTest {
@Test
public void testCompletelyStaticTemplate() throws IOException {
Event event = getTestEvent();
String path = "/full/path/awesome";
assertEquals(path, StringInterpolation.evaluate(event, path));
}
@Test
public void testOneLevelField() throws IOException {
Event event = getTestEvent();
String path = "/full/%{bar}/awesome";
assertEquals("/full/foo/awesome", StringInterpolation.evaluate(event, path));
}
@Test
public void testMultipleLevelField() throws IOException {
Event event = getTestEvent();
String path = "/full/%{bar}/%{awesome}";
assertEquals("/full/foo/logstash", StringInterpolation.evaluate(event, path));
}
@Test
public void testMissingKey() throws IOException {
Event event = getTestEvent();
String path = "/full/%{do-not-exist}";
assertEquals("/full/%{do-not-exist}", StringInterpolation.evaluate(event, path));
}
@Test
public void testDateFormatter() throws IOException {
Event event = getTestEvent();
String path = "/full/%{+YYYY}";
assertEquals("/full/2015", StringInterpolation.evaluate(event, path));
}
@Test
public void TestMixDateAndFields() throws IOException {
Event event = getTestEvent();
String path = "/full/%{+YYYY}/weeee/%{bar}";
assertEquals("/full/2015/weeee/foo", StringInterpolation.evaluate(event, path));
}
@Test
public void TestMixDateAndFieldsJavaSyntax() throws IOException {
Event event = getTestEvent();
String path = "/full/%{{YYYY-DDD}}/weeee/%{bar}";
assertEquals("/full/2015-274/weeee/foo", StringInterpolation.evaluate(event, path));
}
@Test
public void testUnclosedTag() throws IOException {
Event event = getTestEvent();
String path = "/full/%{+YYY/web";
assertEquals("/full/%{+YYY/web", StringInterpolation.evaluate(event, path));
}
@Test
public void TestStringIsOneDateTag() throws IOException {
Event event = getTestEvent();
String path = "%{+YYYY}";
assertEquals("2015", StringInterpolation.evaluate(event, path));
}
@Test
public void TestStringIsJavaDateTag() throws IOException {
Event event = getTestEvent();
String path = "%{{YYYY-'W'ww}}";
assertEquals("2015-W40", StringInterpolation.evaluate(event, path));
}
@Test
public void TestFieldRef() throws IOException {
Event event = getTestEvent();
String path = "%{[j][k1]}";
assertEquals("v", StringInterpolation.evaluate(event, path));
}
@Test
public void TestEpochSeconds() throws IOException {
Event event = getTestEvent();
String path = "%{+%ss}";
// `+%ss` bypasses the EPOCH syntax and instead matches the JODA syntax.
// which produces the literal `%` followed by a two-s seconds value `00`
assertEquals("%00", StringInterpolation.evaluate(event, path));
}
@Test
public void TestEpoch() throws IOException {
Event event = getTestEvent();
String path = "%{+%s}";
assertEquals("1443657600", StringInterpolation.evaluate(event, path));
}
@Test
public void TestValueIsArray() throws IOException {
ArrayList<String> l = new ArrayList<>();
l.add("Hello");
l.add("world");
Event event = getTestEvent();
event.setField("message", l);
String path = "%{message}";
assertEquals("Hello,world", StringInterpolation.evaluate(event, path));
}
@Test
public void TestValueIsHash() throws IOException {
Event event = getTestEvent();
String path = "%{j}";
assertEquals("{\"k1\":\"v\"}", StringInterpolation.evaluate(event, path));
}
public Event getTestEvent() {
Map<String, Object> data = new HashMap<>();
Map<String, String> inner = new HashMap<>();
inner.put("k1", "v");
data.put("bar", "foo");
data.put("awesome", "logstash");
data.put("j", inner);
data.put("@timestamp", new DateTime(2015, 10, 1, 0, 0, 0, DateTimeZone.UTC));
Event event = new Event(data);
return event;
}
}
|
package com.vitahlin.ladybug.spring.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author vitah
*/
@Component
public class UserService3 {
@Autowired
private OrderService1 orderService1;
public void test() {
System.out.println("user service 3");
}
}
|
package com.changfa.frame.website.controller.app;
import com.changfa.frame.model.app.Area;
import com.changfa.frame.service.mybatis.app.AreaService;
import com.changfa.frame.service.mybatis.app.impl.AreaServiceImpl;
import com.changfa.frame.website.controller.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* 区域接口
*
*/
@Api(value = "区域接口", tags = "区域接口")
@RestController("wxMiniAreaController")
@RequestMapping("/wxMini/anon/area")
public class AreaController extends BaseController {
@Resource(name = "areaServiceImpl")
private AreaService areaServiceImpl;
/**
* 根据上级代码获取区域列表
*
* @return
*/
@ApiOperation(value = "根据上级代码获取区域列表", notes = "根据上级代码获取区域列表")
@ApiImplicitParams(
@ApiImplicitParam(name = "parentId", value = "父亲", dataType = "Long"))
@RequestMapping(value = "/getListParentId", method = RequestMethod.GET)
public Map<String, Object> getList(String parentId) {
Area area = new Area();
area.setParentId(parentId);
List<Area> list = areaServiceImpl.selectList(area);
return getResult(list);
}
}
|
package ru.job4j.map;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* class SimpleMap.
* @param <K> - key.
* @param <V> - value.
*/
public class SimpleMap<K, V> implements Iterable<V> {
/** data storage.*/
private Object[] data;
/**
* default constructor.
*/
public SimpleMap() {
this(17);
}
/**
* constructor with size.
* @param size - size.
*/
public SimpleMap(int size) {
this.data = new Object[size];
}
/**
* method insert.
* @param key - key value.
* @param value - value.
* @return boolean.
*/
public boolean insert(K key, V value) {
boolean result = false;
int index = getIndex(key);
if (data[index] == null) {
data[index] = value;
result = true;
}
return result;
}
/**
* method get.
* @param key - key value.
* @return value.
*/
public V get(K key) {
int index = getIndex(key);
if (data[index] == null) {
throw new NoSuchElementException();
}
return (V) data[index];
}
/**
* method delete.
* @param key - key value.
* @return boolean.
*/
public boolean delete(K key) {
boolean result = false;
int index = getIndex(key);
if (data[index] != null) {
data[index] = null;
result = true;
}
return result;
}
/**
* method getIndex.
* @param key - key value.
* @return index in data.
*/
private int getIndex(K key) {
int index;
if (key == null) {
index = 0;
} else {
index = Math.abs(key.hashCode() % data.length);
}
return index;
}
/**
* method iterator.
* @return iterator.
*/
@Override
public Iterator<V> iterator() {
return new Iterator<V>() {
private int index;
private V value;
@Override
public boolean hasNext() {
boolean result = false;
for (; index < data.length; index++) {
if (data[index] != null) {
value = (V) data[index];
result = true;
break;
}
}
return result;
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
index++;
return value;
}
};
}
}
|
package ca.momoperes.client.world;
public class Location {
private double x, y;
public Location(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
|
package com.hihsoft.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.junit.runner.RunWith;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import com.hihsoft.framework.core.baseclass.domain.BaseDomain;
/**
* <p> Title:测试框架的基类 </p>
* <p> Description:</p>
* <p> Copyright: Copyright (c) 2014 </p>
* <p> Company:hihsoft.co.,ltd </p>
*
* @author hihsoft.co.,ltd
* @version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={"classpath:/resources/springcfg/applicationContext-global.xml"})
@TransactionConfiguration(transactionManager = "jtaTransactionManager",defaultRollback=false)
public abstract class BaseTestCase extends AbstractTransactionalJUnit4SpringContextTests {
protected final Logger log = Logger.getLogger(this.getClass());
/**
* Convenience methods to make tests simpler
*/
public MockHttpServletRequest newPost(String url) {
return new MockHttpServletRequest("POST", url);
}
public MockHttpServletRequest newGet(String url) {
return new MockHttpServletRequest("GET", url);
}
public void objectToRequestParameters(Object o,
MockHttpServletRequest request) throws Exception {
objectToRequestParameters(o, request, null);
}
/**
* Object to request parameters.
*
* @param o the o
* @param request the request
* @param prefix the prefix
* @throws Exception the exception
*/
public void objectToRequestParameters(Object o,
MockHttpServletRequest request, String prefix) throws Exception {
Class clazz = o.getClass();
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
for (int i = 0; i < fields.length; i++) {
Object field = (fields[i].get(o));
if (field instanceof BaseDomain) {
objectToRequestParameters(field, request, fields[i].getName());
} else if (!(field instanceof List) && !(field instanceof Set)) {
String paramName = fields[i].getName();
if (prefix != null) {
paramName = prefix + "." + paramName;
}
request.addParameter(paramName,
String.valueOf(fields[i].get(o)));
}
}
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.permission.PermissionStatus;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockStoragePolicySuite;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.QuotaExceededException;
import org.apache.hadoop.hdfs.server.namenode.INodeReference.DstReference;
import org.apache.hadoop.hdfs.server.namenode.INodeReference.WithName;
import org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot;
import org.apache.hadoop.hdfs.util.Diff;
import org.apache.hadoop.util.ChunkedArrayList;
import org.apache.hadoop.util.StringUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* We keep an in-memory representation of the file/block hierarchy.
* This is a base INode class containing common fields for file and
* directory inodes.
*/
@InterfaceAudience.Private
public abstract class INode implements INodeAttributes, Diff.Element<byte[]> {
public static final Log LOG = LogFactory.getLog(INode.class);
/** parent is either an {@link INodeDirectory} or an {@link INodeReference}.*/
private INode parent = null;
INode(INode parent) {
this.parent = parent;
}
/** Get inode id */
public abstract long getId();
/**
* Check whether this is the root inode.
*/
final boolean isRoot() {
return getLocalNameBytes().length == 0;
}
/** Get the {@link PermissionStatus} */
abstract PermissionStatus getPermissionStatus(int snapshotId);
/** The same as getPermissionStatus(null). */
final PermissionStatus getPermissionStatus() {
return getPermissionStatus(Snapshot.CURRENT_STATE_ID);
}
/**
* @param snapshotId
* if it is not {@link Snapshot#CURRENT_STATE_ID}, get the result
* from the given snapshot; otherwise, get the result from the
* current inode.
* @return user name
*/
abstract String getUserName(int snapshotId);
abstract String getTag(int snapshotId);
/** The same as getUserName(Snapshot.CURRENT_STATE_ID). */
@Override
public final String getUserName() {
return getUserName(Snapshot.CURRENT_STATE_ID);
}
@Override
public final String getTag() {
return getTag(Snapshot.CURRENT_STATE_ID);
}
/** Set user */
abstract void setUser(String user);
public abstract void setTag(String tag);
/** Set user */
final INode setUser(String user, int latestSnapshotId) {
recordModification(latestSnapshotId);
setUser(user);
return this;
}
public final INode setTag(String tag, int latestSnapshotId) {
recordModification(latestSnapshotId);
setTag(tag);
return this;
}
/**
* @param snapshotId
* if it is not {@link Snapshot#CURRENT_STATE_ID}, get the result
* from the given snapshot; otherwise, get the result from the
* current inode.
* @return group name
*/
abstract String getGroupName(int snapshotId);
/** The same as getGroupName(Snapshot.CURRENT_STATE_ID). */
@Override
public final String getGroupName() {
return getGroupName(Snapshot.CURRENT_STATE_ID);
}
/** Set group */
abstract void setGroup(String group);
/** Set group */
final INode setGroup(String group, int latestSnapshotId) {
recordModification(latestSnapshotId);
setGroup(group);
return this;
}
/**
* @param snapshotId
* if it is not {@link Snapshot#CURRENT_STATE_ID}, get the result
* from the given snapshot; otherwise, get the result from the
* current inode.
* @return permission.
*/
abstract FsPermission getFsPermission(int snapshotId);
/** The same as getFsPermission(Snapshot.CURRENT_STATE_ID). */
@Override
public final FsPermission getFsPermission() {
return getFsPermission(Snapshot.CURRENT_STATE_ID);
}
/** Set the {@link FsPermission} of this {@link INode} */
abstract void setPermission(FsPermission permission);
/** Set the {@link FsPermission} of this {@link INode} */
INode setPermission(FsPermission permission, int latestSnapshotId) {
recordModification(latestSnapshotId);
setPermission(permission);
return this;
}
abstract AclFeature getAclFeature(int snapshotId);
@Override
public final AclFeature getAclFeature() {
return getAclFeature(Snapshot.CURRENT_STATE_ID);
}
abstract void addAclFeature(AclFeature aclFeature);
final INode addAclFeature(AclFeature aclFeature, int latestSnapshotId) {
recordModification(latestSnapshotId);
addAclFeature(aclFeature);
return this;
}
abstract void removeAclFeature();
final INode removeAclFeature(int latestSnapshotId) {
recordModification(latestSnapshotId);
removeAclFeature();
return this;
}
/**
* @param snapshotId
* if it is not {@link Snapshot#CURRENT_STATE_ID}, get the result
* from the given snapshot; otherwise, get the result from the
* current inode.
* @return XAttrFeature
*/
abstract XAttrFeature getXAttrFeature(int snapshotId);
@Override
public final XAttrFeature getXAttrFeature() {
return getXAttrFeature(Snapshot.CURRENT_STATE_ID);
}
/**
* Set <code>XAttrFeature</code>
*/
abstract void addXAttrFeature(XAttrFeature xAttrFeature);
final INode addXAttrFeature(XAttrFeature xAttrFeature, int latestSnapshotId) {
recordModification(latestSnapshotId);
addXAttrFeature(xAttrFeature);
return this;
}
/**
* Remove <code>XAttrFeature</code>
*/
abstract void removeXAttrFeature();
final INode removeXAttrFeature(int lastestSnapshotId) {
recordModification(lastestSnapshotId);
removeXAttrFeature();
return this;
}
/**
* @return if the given snapshot id is {@link Snapshot#CURRENT_STATE_ID},
* return this; otherwise return the corresponding snapshot inode.
*/
public INodeAttributes getSnapshotINode(final int snapshotId) {
return this;
}
/** Is this inode in the latest snapshot? */
public final boolean isInLatestSnapshot(final int latestSnapshotId) {
if (latestSnapshotId == Snapshot.CURRENT_STATE_ID || latestSnapshotId == Snapshot.NO_SNAPSHOT_ID) {
return false;
}
// if parent is a reference node, parent must be a renamed node. We can
// stop the check at the reference node.
if (parent != null && parent.isReference()) {
return true;
}
final INodeDirectory parentDir = getParent();
if (parentDir == null) { // root
return true;
}
if (!parentDir.isInLatestSnapshot(latestSnapshotId)) {
return false;
}
final INode child = parentDir.getChild(getLocalNameBytes(), latestSnapshotId);
if (this == child) {
return true;
}
return child != null && child.isReference() &&
this == child.asReference().getReferredINode();
}
/** @return true if the given inode is an ancestor directory of this inode. */
public final boolean isAncestorDirectory(final INodeDirectory dir) {
for(INodeDirectory p = getParent(); p != null; p = p.getParent()) {
if (p == dir) {
return true;
}
}
return false;
}
/**
* When {@link #recordModification} is called on a referred node,
* this method tells which snapshot the modification should be
* associated with: the snapshot that belongs to the SRC tree of the rename
* operation, or the snapshot belonging to the DST tree.
*
* @param latestInDst
* id of the latest snapshot in the DST tree above the reference node
* @return True: the modification should be recorded in the snapshot that
* belongs to the SRC tree. False: the modification should be
* recorded in the snapshot that belongs to the DST tree.
*/
public final boolean shouldRecordInSrcSnapshot(final int latestInDst) {
Preconditions.checkState(!isReference());
if (latestInDst == Snapshot.CURRENT_STATE_ID) {
return true;
}
INodeReference withCount = getParentReference();
if (withCount != null) {
int dstSnapshotId = withCount.getParentReference().getDstSnapshotId();
if (dstSnapshotId != Snapshot.CURRENT_STATE_ID
&& dstSnapshotId >= latestInDst) {
return true;
}
}
return false;
}
/**
* This inode is being modified. The previous version of the inode needs to
* be recorded in the latest snapshot.
*
* @param latestSnapshotId The id of the latest snapshot that has been taken.
* Note that it is {@link Snapshot#CURRENT_STATE_ID}
* if no snapshots have been taken.
*/
abstract void recordModification(final int latestSnapshotId);
/** Check whether it's a reference. */
public boolean isReference() {
return false;
}
/** Cast this inode to an {@link INodeReference}. */
public INodeReference asReference() {
throw new IllegalStateException("Current inode is not a reference: "
+ this.toDetailString());
}
/**
* Check whether it's a file.
*/
public boolean isFile() {
return false;
}
/** Cast this inode to an {@link INodeFile}. */
public INodeFile asFile() {
throw new IllegalStateException("Current inode is not a file: "
+ this.toDetailString());
}
/**
* Check whether it's a directory
*/
public boolean isDirectory() {
return false;
}
/** Cast this inode to an {@link INodeDirectory}. */
public INodeDirectory asDirectory() {
throw new IllegalStateException("Current inode is not a directory: "
+ this.toDetailString());
}
/**
* Check whether it's a symlink
*/
public boolean isSymlink() {
return false;
}
/** Cast this inode to an {@link INodeSymlink}. */
public INodeSymlink asSymlink() {
throw new IllegalStateException("Current inode is not a symlink: "
+ this.toDetailString());
}
/**
* Clean the subtree under this inode and collect the blocks from the descents
* for further block deletion/update. The current inode can either resides in
* the current tree or be stored as a snapshot copy.
*
* <pre>
* In general, we have the following rules.
* 1. When deleting a file/directory in the current tree, we have different
* actions according to the type of the node to delete.
*
* 1.1 The current inode (this) is an {@link INodeFile}.
* 1.1.1 If {@code prior} is null, there is no snapshot taken on ancestors
* before. Thus we simply destroy (i.e., to delete completely, no need to save
* snapshot copy) the current INode and collect its blocks for further
* cleansing.
* 1.1.2 Else do nothing since the current INode will be stored as a snapshot
* copy.
*
* 1.2 The current inode is an {@link INodeDirectory}.
* 1.2.1 If {@code prior} is null, there is no snapshot taken on ancestors
* before. Similarly, we destroy the whole subtree and collect blocks.
* 1.2.2 Else do nothing with the current INode. Recursively clean its
* children.
*
* 1.3 The current inode is a file with snapshot.
* Call recordModification(..) to capture the current states.
* Mark the INode as deleted.
*
* 1.4 The current inode is an {@link INodeDirectory} with snapshot feature.
* Call recordModification(..) to capture the current states.
* Destroy files/directories created after the latest snapshot
* (i.e., the inodes stored in the created list of the latest snapshot).
* Recursively clean remaining children.
*
* 2. When deleting a snapshot.
* 2.1 To clean {@link INodeFile}: do nothing.
* 2.2 To clean {@link INodeDirectory}: recursively clean its children.
* 2.3 To clean INodeFile with snapshot: delete the corresponding snapshot in
* its diff list.
* 2.4 To clean {@link INodeDirectory} with snapshot: delete the corresponding
* snapshot in its diff list. Recursively clean its children.
* </pre>
*
* @param bsps
* block storage policy suite to calculate intended storage type usage
* @param snapshotId
* The id of the snapshot to delete.
* {@link Snapshot#CURRENT_STATE_ID} means to delete the current
* file/directory.
* @param priorSnapshotId
* The id of the latest snapshot before the to-be-deleted snapshot.
* When deleting a current inode, this parameter captures the latest
* snapshot.
* @param collectedBlocks
* blocks collected from the descents for further block
* deletion/update will be added to the given map.
* @param removedINodes
* INodes collected from the descents for further cleaning up of
* inodeMap
* @return quota usage delta when deleting a snapshot
*/
public abstract QuotaCounts cleanSubtree(final BlockStoragePolicySuite bsps,
final int snapshotId,
int priorSnapshotId, BlocksMapUpdateInfo collectedBlocks,
List<INode> removedINodes);
/**
* Destroy self and clear everything! If the INode is a file, this method
* collects its blocks for further block deletion. If the INode is a
* directory, the method goes down the subtree and collects blocks from the
* descents, and clears its parent/children references as well. The method
* also clears the diff list if the INode contains snapshot diff list.
*
* @param bsps
* block storage policy suite to calculate intended storage type usage
* This is needed because INodeReference#destroyAndCollectBlocks() needs
* to call INode#cleanSubtree(), which calls INode#computeQuotaUsage().
* @param collectedBlocks
* blocks collected from the descents for further block
* deletion/update will be added to this map.
* @param removedINodes
* INodes collected from the descents for further cleaning up of
* inodeMap
*/
public abstract void destroyAndCollectBlocks(
BlockStoragePolicySuite bsps,
BlocksMapUpdateInfo collectedBlocks, List<INode> removedINodes);
/** Compute {@link ContentSummary}. Blocking call */
public final ContentSummary computeContentSummary(BlockStoragePolicySuite bsps) {
return computeAndConvertContentSummary(
new ContentSummaryComputationContext(bsps));
}
/**
* Compute {@link ContentSummary}.
*/
public final ContentSummary computeAndConvertContentSummary(
ContentSummaryComputationContext summary) {
ContentCounts counts = computeContentSummary(summary).getCounts();
final QuotaCounts q = getQuotaCounts();
return new ContentSummary.Builder().
length(counts.getLength()).
fileCount(counts.getFileCount() + counts.getSymlinkCount()).
directoryCount(counts.getDirectoryCount()).
quota(q.getNameSpace()).
spaceConsumed(counts.getStoragespace()).
spaceQuota(q.getStorageSpace()).
typeConsumed(counts.getTypeSpaces()).
typeQuota(q.getTypeSpaces().asArray()).
build();
}
/**
* Count subtree content summary with a {@link ContentCounts}.
*
* @param summary the context object holding counts for the subtree.
* @return The same objects as summary.
*/
public abstract ContentSummaryComputationContext computeContentSummary(
ContentSummaryComputationContext summary);
/**
* Check and add namespace/storagespace/storagetype consumed to itself and the ancestors.
* @throws QuotaExceededException if quote is violated.
*/
public void addSpaceConsumed(QuotaCounts counts, boolean verify)
throws QuotaExceededException {
addSpaceConsumed2Parent(counts, verify);
}
/**
* Check and add namespace/storagespace/storagetype consumed to itself and the ancestors.
* @throws QuotaExceededException if quote is violated.
*/
void addSpaceConsumed2Parent(QuotaCounts counts, boolean verify)
throws QuotaExceededException {
if (parent != null) {
parent.addSpaceConsumed(counts, verify);
}
}
/**
* Get the quota set for this inode
* @return the quota counts. The count is -1 if it is not set.
*/
public QuotaCounts getQuotaCounts() {
return new QuotaCounts.Builder().
nameSpace(HdfsConstants.QUOTA_RESET).
storageSpace(HdfsConstants.QUOTA_RESET).
typeSpaces(HdfsConstants.QUOTA_RESET).
build();
}
public final boolean isQuotaSet() {
final QuotaCounts qc = getQuotaCounts();
return qc.anyNsSsCountGreaterOrEqual(0) || qc.anyTypeSpaceCountGreaterOrEqual(0);
}
/**
* Count subtree {@link Quota#NAMESPACE} and {@link Quota#STORAGESPACE} usages.
* Entry point for FSDirectory where blockStoragePolicyId is given its initial
* value.
*/
public final QuotaCounts computeQuotaUsage(BlockStoragePolicySuite bsps) {
final byte storagePolicyId = isSymlink() ?
BlockStoragePolicySuite.ID_UNSPECIFIED : getStoragePolicyID();
return computeQuotaUsage(bsps, storagePolicyId,
new QuotaCounts.Builder().build(), true, Snapshot.CURRENT_STATE_ID);
}
/**
* Count subtree {@link Quota#NAMESPACE} and {@link Quota#STORAGESPACE} usages.
*
* With the existence of {@link INodeReference}, the same inode and its
* subtree may be referred by multiple {@link WithName} nodes and a
* {@link DstReference} node. To avoid circles while quota usage computation,
* we have the following rules:
*
* <pre>
* 1. For a {@link DstReference} node, since the node must be in the current
* tree (or has been deleted as the end point of a series of rename
* operations), we compute the quota usage of the referred node (and its
* subtree) in the regular manner, i.e., including every inode in the current
* tree and in snapshot copies, as well as the size of diff list.
*
* 2. For a {@link WithName} node, since the node must be in a snapshot, we
* only count the quota usage for those nodes that still existed at the
* creation time of the snapshot associated with the {@link WithName} node.
* We do not count in the size of the diff list.
* <pre>
*
* @param bsps Block storage policy suite to calculate intended storage type usage
* @param blockStoragePolicyId block storage policy id of the current INode
* @param counts The subtree counts for returning.
* @param useCache Whether to use cached quota usage. Note that
* {@link WithName} node never uses cache for its subtree.
* @param lastSnapshotId {@link Snapshot#CURRENT_STATE_ID} indicates the
* computation is in the current tree. Otherwise the id
* indicates the computation range for a
* {@link WithName} node.
* @return The same objects as the counts parameter.
*/
public abstract QuotaCounts computeQuotaUsage(
BlockStoragePolicySuite bsps, byte blockStoragePolicyId,
QuotaCounts counts, boolean useCache, int lastSnapshotId);
public final QuotaCounts computeQuotaUsage(
BlockStoragePolicySuite bsps, QuotaCounts counts, boolean useCache) {
final byte storagePolicyId = isSymlink() ?
BlockStoragePolicySuite.ID_UNSPECIFIED : getStoragePolicyID();
return computeQuotaUsage(bsps, storagePolicyId, counts,
useCache, Snapshot.CURRENT_STATE_ID);
}
/**
* @return null if the local name is null; otherwise, return the local name.
*/
public final String getLocalName() {
final byte[] name = getLocalNameBytes();
return name == null? null: DFSUtil.bytes2String(name);
}
@Override
public final byte[] getKey() {
return getLocalNameBytes();
}
/**
* Set local file name
*/
public abstract void setLocalName(byte[] name);
public String getFullPathName() {
// Get the full path name of this inode.
return FSDirectory.getFullPathName(this);
}
@Override
public String toString() {
return getLocalName();
}
@VisibleForTesting
public final String getObjectString() {
return getClass().getSimpleName() + "@"
+ Integer.toHexString(super.hashCode());
}
/** @return a string description of the parent. */
@VisibleForTesting
public final String getParentString() {
final INodeReference parentRef = getParentReference();
if (parentRef != null) {
return "parentRef=" + parentRef.getLocalName() + "->";
} else {
final INodeDirectory parentDir = getParent();
if (parentDir != null) {
return "parentDir=" + parentDir.getLocalName() + "/";
} else {
return "parent=null";
}
}
}
@VisibleForTesting
public String toDetailString() {
return toString() + "(" + getObjectString() + "), " + getParentString();
}
/** @return the parent directory */
public final INodeDirectory getParent() {
return parent == null? null
: parent.isReference()? getParentReference().getParent(): parent.asDirectory();
}
/**
* @return the parent as a reference if this is a referred inode;
* otherwise, return null.
*/
public INodeReference getParentReference() {
return parent == null || !parent.isReference()? null: (INodeReference)parent;
}
/** Set parent directory */
public final void setParent(INodeDirectory parent) {
this.parent = parent;
}
/** Set container. */
public final void setParentReference(INodeReference parent) {
this.parent = parent;
}
/** Clear references to other objects. */
public void clear() {
setParent(null);
}
/**
* @param snapshotId
* if it is not {@link Snapshot#CURRENT_STATE_ID}, get the result
* from the given snapshot; otherwise, get the result from the
* current inode.
* @return modification time.
*/
abstract long getModificationTime(int snapshotId);
/** The same as getModificationTime(Snapshot.CURRENT_STATE_ID). */
@Override
public final long getModificationTime() {
return getModificationTime(Snapshot.CURRENT_STATE_ID);
}
/** Update modification time if it is larger than the current value. */
public abstract INode updateModificationTime(long mtime, int latestSnapshotId);
/** Set the last modification time of inode. */
public abstract void setModificationTime(long modificationTime);
/** Set the last modification time of inode. */
public final INode setModificationTime(long modificationTime,
int latestSnapshotId) {
recordModification(latestSnapshotId);
setModificationTime(modificationTime);
return this;
}
/**
* @param snapshotId
* if it is not {@link Snapshot#CURRENT_STATE_ID}, get the result
* from the given snapshot; otherwise, get the result from the
* current inode.
* @return access time
*/
abstract long getAccessTime(int snapshotId);
/** The same as getAccessTime(Snapshot.CURRENT_STATE_ID). */
@Override
public final long getAccessTime() {
return getAccessTime(Snapshot.CURRENT_STATE_ID);
}
/**
* Set last access time of inode.
*/
public abstract void setAccessTime(long accessTime);
/**
* Set last access time of inode.
*/
public final INode setAccessTime(long accessTime, int latestSnapshotId) {
recordModification(latestSnapshotId);
setAccessTime(accessTime);
return this;
}
/**
* @return the latest block storage policy id of the INode. Specifically,
* if a storage policy is directly specified on the INode then return the ID
* of that policy. Otherwise follow the latest parental path and return the
* ID of the first specified storage policy.
*/
public abstract byte getStoragePolicyID();
/**
* @return the storage policy directly specified on the INode. Return
* {@link BlockStoragePolicySuite#ID_UNSPECIFIED} if no policy has
* been specified.
*/
public abstract byte getLocalStoragePolicyID();
/**
* Get the storage policy ID while computing quota usage
* @param parentStoragePolicyId the storage policy ID of the parent directory
* @return the storage policy ID of this INode. Note that for an
* {@link INodeSymlink} we return {@link BlockStoragePolicySuite#ID_UNSPECIFIED}
* instead of throwing Exception
*/
public byte getStoragePolicyIDForQuota(byte parentStoragePolicyId) {
byte localId = isSymlink() ?
BlockStoragePolicySuite.ID_UNSPECIFIED : getLocalStoragePolicyID();
return localId != BlockStoragePolicySuite.ID_UNSPECIFIED ?
localId : parentStoragePolicyId;
}
/**
* Breaks {@code path} into components.
* @return array of byte arrays each of which represents
* a single path component.
*/
@VisibleForTesting
public static byte[][] getPathComponents(String path) {
return getPathComponents(getPathNames(path));
}
/** Convert strings to byte arrays for path components. */
static byte[][] getPathComponents(String[] strings) {
if (strings.length == 0) {
return new byte[][]{null};
}
byte[][] bytes = new byte[strings.length][];
for (int i = 0; i < strings.length; i++)
bytes[i] = DFSUtil.string2Bytes(strings[i]);
return bytes;
}
/**
* Splits an absolute {@code path} into an array of path components.
* @throws AssertionError if the given path is invalid.
* @return array of path components.
*/
public static String[] getPathNames(String path) {
if (path == null || !path.startsWith(Path.SEPARATOR)) {
throw new AssertionError("Absolute path required");
}
return StringUtils.split(path, Path.SEPARATOR_CHAR);
}
@Override
public final int compareTo(byte[] bytes) {
return DFSUtil.compareBytes(getLocalNameBytes(), bytes);
}
@Override
public final boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null || !(that instanceof INode)) {
return false;
}
return getId() == ((INode) that).getId();
}
@Override
public final int hashCode() {
long id = getId();
return (int)(id^(id>>>32));
}
/**
* Dump the subtree starting from this inode.
* @return a text representation of the tree.
*/
@VisibleForTesting
public final StringBuffer dumpTreeRecursively() {
final StringWriter out = new StringWriter();
dumpTreeRecursively(new PrintWriter(out, true), new StringBuilder(),
Snapshot.CURRENT_STATE_ID);
return out.getBuffer();
}
@VisibleForTesting
public final void dumpTreeRecursively(PrintStream out) {
out.println(dumpTreeRecursively().toString());
}
/**
* Dump tree recursively.
* @param prefix The prefix string that each line should print.
*/
@VisibleForTesting
public void dumpTreeRecursively(PrintWriter out, StringBuilder prefix,
int snapshotId) {
out.print(prefix);
out.print(" ");
final String name = getLocalName();
out.print(name.isEmpty()? "/": name);
out.print(" (");
out.print(getObjectString());
out.print("), ");
out.print(getParentString());
out.print(", " + getPermissionStatus(snapshotId));
}
/**
* Information used for updating the blocksMap when deleting files.
*/
public static class BlocksMapUpdateInfo {
/**
* The list of blocks that need to be removed from blocksMap
*/
private final List<Block> toDeleteList;
public BlocksMapUpdateInfo() {
toDeleteList = new ChunkedArrayList<Block>();
}
/**
* @return The list of blocks that need to be removed from blocksMap
*/
public List<Block> getToDeleteList() {
return toDeleteList;
}
/**
* Add a to-be-deleted block into the
* {@link BlocksMapUpdateInfo#toDeleteList}
* @param toDelete the to-be-deleted block
*/
public void addDeleteBlock(Block toDelete) {
assert toDelete != null : "toDelete is null";
toDeleteList.add(toDelete);
}
public void removeDeleteBlock(Block block) {
assert block != null : "block is null";
toDeleteList.remove(block);
}
/**
* Clear {@link BlocksMapUpdateInfo#toDeleteList}
*/
public void clear() {
toDeleteList.clear();
}
}
/**
* INode feature such as {@link FileUnderConstructionFeature}
* and {@link DirectoryWithQuotaFeature}.
*/
public interface Feature {
}
}
|
package ex;
import java.util.*;
/*
* Topic: 請寫一個程式讓使用者輸入體重單位 "公斤",轉換成 "磅" (1磅 = 0.45359 公斤)
* Date: 2016/09/19
* Author: 105021030 張廷毓
*/
public class ex02_105021030 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
float a=sc.nextFloat();
float b=0;
b=a*100000/45359;
System.out.print(b);
}
}
|
package com.easyandroidanimations.library;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
/**
* This animation causes the view to flip horizontally by a customizable number
* of degrees and at a customizable pivot point.
*
* @author SiYao
*
*/
public class FlipHorizontalAnimation extends Animation implements Combinable {
public static final int PIVOT_CENTER = 0, PIVOT_LEFT = 1, PIVOT_RIGHT = 2;
float degrees;
int pivot;
TimeInterpolator interpolator;
long duration;
AnimationListener listener;
/**
* This animation causes the view to flip horizontally by a customizable
* number of degrees and at a customizable pivot point.
*
* @param view
* The view to be animated.
*/
public FlipHorizontalAnimation(View view) {
this.view = view;
degrees = 360;
pivot = PIVOT_CENTER;
interpolator = new AccelerateDecelerateInterpolator();
duration = DURATION_LONG;
listener = null;
}
@Override
public void animate() {
getAnimatorSet().start();
}
@Override
public AnimatorSet getAnimatorSet() {
ViewGroup parentView = (ViewGroup) view.getParent(), rootView = (ViewGroup) view
.getRootView();
while (parentView != rootView) {
parentView.setClipChildren(false);
parentView = (ViewGroup) parentView.getParent();
}
rootView.setClipChildren(false);
float pivotX, pivotY, viewWidth = view.getWidth(), viewHeight = view
.getHeight();
switch (pivot) {
case PIVOT_LEFT:
pivotX = 0f;
pivotY = viewHeight / 2;
break;
case PIVOT_RIGHT:
pivotX = viewWidth;
pivotY = viewHeight / 2;
break;
default:
pivotX = viewWidth / 2;
pivotY = viewHeight / 2;
break;
}
view.setPivotX(pivotX);
view.setPivotY(pivotY);
AnimatorSet flipSet = new AnimatorSet();
flipSet.play(ObjectAnimator.ofFloat(view, View.ROTATION_Y,
view.getRotationY() + degrees));
flipSet.setInterpolator(interpolator);
flipSet.setDuration(duration);
flipSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (getListener() != null) {
getListener().onAnimationEnd(FlipHorizontalAnimation.this);
}
}
});
return flipSet;
}
/**
* @return The number of degrees to flip by.
*/
public float getDegrees() {
return degrees;
}
/**
* In order to flip to the left, the number of degrees should be negative
* and vice versa.
*
* @param degrees
* The number of degrees to set to flip by.
* @return This object, allowing calls to methods in this class to be
* chained.
*/
public FlipHorizontalAnimation setDegrees(float degrees) {
this.degrees = degrees;
return this;
}
/**
* The available pivot points are <code>PIVOT_CENTER</code>,
* <code>PIVOT_LEFT</code> and <code>PIVOT_RIGHT</code>.
*
* @return The pivot point for flipping.
*/
public int getPivot() {
return pivot;
}
/**
* The available pivot points are <code>PIVOT_CENTER</code>,
* <code>PIVOT_LEFT</code> and <code>PIVOT_RIGHT</code>.
*
* @param pivot
* The pivot point to set for flipping.
* @return This object, allowing calls to methods in this class to be
* chained.
*/
public FlipHorizontalAnimation setPivot(int pivot) {
this.pivot = pivot;
return this;
}
/**
* @return The interpolator of the entire animation.
*/
public TimeInterpolator getInterpolator() {
return interpolator;
}
/**
* @param interpolator
* The interpolator of the entire animation to set.
*/
public FlipHorizontalAnimation setInterpolator(TimeInterpolator interpolator) {
this.interpolator = interpolator;
return this;
}
/**
* @return The duration of the entire animation.
*/
public long getDuration() {
return duration;
}
/**
* @param duration
* The duration of the entire animation to set.
* @return This object, allowing calls to methods in this class to be
* chained.
*/
public FlipHorizontalAnimation setDuration(long duration) {
this.duration = duration;
return this;
}
/**
* @return The listener for the end of the animation.
*/
public AnimationListener getListener() {
return listener;
}
/**
* @param listener
* The listener to set for the end of the animation.
* @return This object, allowing calls to methods in this class to be
* chained.
*/
public FlipHorizontalAnimation setListener(AnimationListener listener) {
this.listener = listener;
return this;
}
}
|
/*
If you like this, you should donate to Peter O.
at: http://peteroupc.github.io/
Licensed under the Expat License.
Copyright (C) 2013 Peter Occil
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.upokecenter.net;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import com.upokecenter.io.StreamUtility;
import com.upokecenter.util.IAction;
import com.upokecenter.util.LowPriorityExecutors;
public final class LightweightDownloadService {
private final LightweightCacheService service;
private final ExecutorService pool;
private IAction<Runnable> postResult=null;
private final Object syncRoot=new Object();
public LightweightDownloadService(File publicPath, File privatePath, long cacheSize){
pool=LowPriorityExecutors.newFixedThreadPool(6);
service=new LightweightCacheService(publicPath,privatePath);
service.setCacheSize(cacheSize);
}
private void handleDownload(final String url, final IResponseListener<Object> cbobj,
final IOnFinishedListener<Object> finobj) {
service.enableCache();
try {
final Object value=DownloadHelper.downloadUrl(
url,
new IResponseListener<Object>(){
@Override
public Object processResponse(String url,
InputStream stream, IHttpHeaders headers)
throws IOException {
Object value=(cbobj==null) ? null : cbobj.processResponse(url,stream,headers);
//Skip to the end of the stream; otherwise the response
//won't be cached by HttpURLConnection
StreamUtility.skipToEnd(stream);
return value;
}
}, false);
IAction<Runnable> poster=null;
synchronized(syncRoot){
poster=postResult;
}
if(poster!=null){
poster.action(new Runnable(){
@Override
public void run() {
if(finobj!=null) {
finobj.onFinished(url,value,null);
}
}
});
}
} catch (IOException e) {
if(finobj!=null) {
finobj.onFinished(url,null,e);
}
e.printStackTrace();
}
}
public void sendRequest(final String url, final IResponseListener<Object> cbobj,
final IOnFinishedListener<Object> finobj) {
pool.submit(new Runnable(){
@Override
public void run() {
handleDownload(url,cbobj,finobj);
}
});
}
public void setResultPoster(IAction<Runnable> action){
synchronized(syncRoot){
postResult=action;
}
}
public void shutdown(){
service.shutdown();
pool.shutdown();
}
}
|
package io.joshatron.bgt.tictactoe;
import io.joshatron.bgt.engine.action.Action;
import io.joshatron.bgt.engine.component.board.grid.GridBoardLocation;
import io.joshatron.bgt.engine.player.PlayerIndicator;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class TicTacToeAction extends Action {
private GridBoardLocation location;
public TicTacToeAction(PlayerIndicator player, GridBoardLocation location) {
super(player);
this.location = location;
}
}
|
package me.hrps.aas.web.sys.domain;
import java.util.ArrayList;
import java.util.List;
public class SysRolePermissionExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public SysRolePermissionExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andRoleIdIsNull() {
addCriterion("role_id is null");
return (Criteria) this;
}
public Criteria andRoleIdIsNotNull() {
addCriterion("role_id is not null");
return (Criteria) this;
}
public Criteria andRoleIdEqualTo(String value) {
addCriterion("role_id =", value, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdNotEqualTo(String value) {
addCriterion("role_id <>", value, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdGreaterThan(String value) {
addCriterion("role_id >", value, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdGreaterThanOrEqualTo(String value) {
addCriterion("role_id >=", value, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdLessThan(String value) {
addCriterion("role_id <", value, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdLessThanOrEqualTo(String value) {
addCriterion("role_id <=", value, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdLike(String value) {
addCriterion("role_id like", value, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdNotLike(String value) {
addCriterion("role_id not like", value, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdIn(List<String> values) {
addCriterion("role_id in", values, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdNotIn(List<String> values) {
addCriterion("role_id not in", values, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdBetween(String value1, String value2) {
addCriterion("role_id between", value1, value2, "roleId");
return (Criteria) this;
}
public Criteria andRoleIdNotBetween(String value1, String value2) {
addCriterion("role_id not between", value1, value2, "roleId");
return (Criteria) this;
}
public Criteria andPermissionIdIsNull() {
addCriterion("permission_id is null");
return (Criteria) this;
}
public Criteria andPermissionIdIsNotNull() {
addCriterion("permission_id is not null");
return (Criteria) this;
}
public Criteria andPermissionIdEqualTo(String value) {
addCriterion("permission_id =", value, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdNotEqualTo(String value) {
addCriterion("permission_id <>", value, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdGreaterThan(String value) {
addCriterion("permission_id >", value, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdGreaterThanOrEqualTo(String value) {
addCriterion("permission_id >=", value, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdLessThan(String value) {
addCriterion("permission_id <", value, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdLessThanOrEqualTo(String value) {
addCriterion("permission_id <=", value, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdLike(String value) {
addCriterion("permission_id like", value, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdNotLike(String value) {
addCriterion("permission_id not like", value, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdIn(List<String> values) {
addCriterion("permission_id in", values, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdNotIn(List<String> values) {
addCriterion("permission_id not in", values, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdBetween(String value1, String value2) {
addCriterion("permission_id between", value1, value2, "permissionId");
return (Criteria) this;
}
public Criteria andPermissionIdNotBetween(String value1, String value2) {
addCriterion("permission_id not between", value1, value2, "permissionId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
/*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.internal.serialization.impl;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
import java.io.IOException;
import java.util.Map;
/**
* The {@link Map} serializer
*/
abstract class AbstractMapStreamSerializer<MapType extends Map> implements StreamSerializer<MapType> {
@Override
public void write(ObjectDataOutput out, MapType map) throws IOException {
int size = map.size();
out.writeInt(size);
if (size > 0) {
for (Object entryObject : map.entrySet()) {
Map.Entry entry = (Map.Entry) entryObject;
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
}
}
MapType deserializeEntries(ObjectDataInput in, int size, MapType result) throws IOException {
for (int i = 0; i < size; i++) {
result.put(in.readObject(), in.readObject());
}
return result;
}
@Override
public void destroy() {
}
}
|
package br.com.valtergodoy.testSpring.integration;
import br.com.valtergodoy.testSpring.controller.dto.CustomerRequestBody;
import br.com.valtergodoy.testSpring.model.Customer;
import br.com.valtergodoy.testSpring.repository.CustomerRepository;
import br.com.valtergodoy.testSpring.util.CustomerCreator;
import br.com.valtergodoy.testSpring.util.CustomerRequestBodyCreator;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import java.util.List;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class CustomerControleIntegration {
@Autowired
@Qualifier(value = "testRestTemplateWithSimpleUser")
private TestRestTemplate testRestTemplateWithSimpleUser;
@Autowired
@Qualifier(value = "testRestTemplateWithAdminUser")
private TestRestTemplate testRestTemplateWithAdminUser;
@Autowired
private CustomerRepository customerRepository;
@TestConfiguration
@Lazy
static class Config {
@Bean(name = "testRestTemplateWithSimpleUser")
public TestRestTemplate testRestTemplateWithSimpleUserCreator(@Value("${local.server.port}") int port) {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder()
.rootUri("http://localhost:"+port)
.basicAuthentication("valter", "!@#1234Abc");
return new TestRestTemplate(restTemplateBuilder);
}
@Bean(name = "testRestTemplateWithAdminUser")
public TestRestTemplate testRestTemplateWithAdminUserCreator(@Value("${local.server.port}") int port) {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder()
.rootUri("http://localhost:"+port)
.basicAuthentication("administrator", "bcA4321#@!");
return new TestRestTemplate(restTemplateBuilder);
}
}
@Test
@DisplayName("List all customers")
void successListAll() {
Customer customerSaved = customerRepository.save(CustomerCreator.createValidCustomer());
List<Customer> list = testRestTemplateWithSimpleUser.exchange("/customer/", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>() {
}).getBody();
Assertions.assertThat(list)
.isNotNull()
.isNotEmpty();
}
@Test
@DisplayName("Find customer by ID")
void successFindById() {
Customer customerSaved = customerRepository.save(CustomerCreator.createValidCustomer());
Customer customerReached = testRestTemplateWithSimpleUser.exchange("/customer/" + customerSaved.getId().toString(), HttpMethod.GET, null,
new ParameterizedTypeReference<Customer>() {
}).getBody();
Assertions.assertThat(customerReached).isNotNull()
.isEqualTo(customerSaved);
}
@Test
@DisplayName("Find customer by Name")
void successFindByName() {
Customer customerSaved = customerRepository.save(CustomerCreator.createValidCustomer());
String url = String.format("/customer/find?name=%s", customerSaved.getName());
List<Customer> list = testRestTemplateWithSimpleUser.exchange(url, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>() {
}).getBody();
Assertions.assertThat(list).isNotNull();
Assertions.assertThat(list.get(0).getName()).isEqualTo(customerSaved.getName());
}
@Test
@DisplayName("Throws when customer not found by Name")
void failFindByNameNotFound() {
String url = String.format("/customer/find?name=%s", "Not Found");
List<Customer> list = testRestTemplateWithSimpleUser.exchange(url, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>() {
}).getBody();
Assertions.assertThat(list).isNotNull()
.isEmpty();
}
@Test
@DisplayName("Insert customer without permission")
void failInsert() {
CustomerRequestBodyCreator customerRequestBodyCreator = new CustomerRequestBodyCreator();
CustomerRequestBody customerRequestBody = customerRequestBodyCreator.createValidCustomerRequestBody();
ResponseEntity<Customer> customerResponseEntity = testRestTemplateWithSimpleUser.postForEntity("/customer", customerRequestBody, Customer.class);
Assertions.assertThat(customerResponseEntity).isNotNull();
Assertions.assertThat(customerResponseEntity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
@DisplayName("Insert customer")
void successInsert() {
CustomerRequestBodyCreator customerRequestBodyCreator = new CustomerRequestBodyCreator();
CustomerRequestBody customerRequestBody = customerRequestBodyCreator.createValidCustomerRequestBody();
ResponseEntity<Customer> customerResponseEntity = testRestTemplateWithAdminUser.postForEntity("/customer", customerRequestBody, Customer.class);
Assertions.assertThat(customerResponseEntity).isNotNull();
Assertions.assertThat(customerResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
Assertions.assertThat(customerResponseEntity.getBody()).isNotNull();
Assertions.assertThat(customerResponseEntity.getBody().getId()).isNotNull();
}
@Test
@DisplayName("Update customer without permission")
void failUpdate() {
Customer customerSaved = customerRepository.save(CustomerCreator.createValidCustomer());
customerSaved.setName("UPDATED");
ResponseEntity<Customer> customerResponseEntity = testRestTemplateWithSimpleUser.exchange("/customer", HttpMethod.PUT, new HttpEntity<>(customerSaved),
Customer.class);
Assertions.assertThat(customerResponseEntity).isNotNull();
Assertions.assertThat(customerResponseEntity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
@DisplayName("Update customer")
void successUpdate() {
Customer customerSaved = customerRepository.save(CustomerCreator.createValidCustomer());
customerSaved.setName("UPDATED");
ResponseEntity<Customer> customerResponseEntity = testRestTemplateWithAdminUser.exchange("/customer", HttpMethod.PUT, new HttpEntity<>(customerSaved),
Customer.class);
Assertions.assertThat(customerResponseEntity).isNotNull();
Assertions.assertThat(customerResponseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
Assertions.assertThat(customerResponseEntity.getBody()).isNotNull();
Assertions.assertThat(customerResponseEntity.getBody().getName()).isEqualTo(customerSaved.getName());
}
@Test
@DisplayName("Delete customer without permission")
void failDelete() {
Customer customerSaved = customerRepository.save(CustomerCreator.createValidCustomer());
ResponseEntity<Void> customerResponseEntity = testRestTemplateWithSimpleUser.exchange("/customer/{id}", HttpMethod.DELETE, null,
Void.class, customerSaved.getId());
Assertions.assertThat(customerResponseEntity).isNotNull();
Assertions.assertThat(customerResponseEntity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
@DisplayName("Delete customer")
void successDelete() {
Customer customerSaved = customerRepository.save(CustomerCreator.createValidCustomer());
ResponseEntity<Void> customerResponseEntity = testRestTemplateWithAdminUser.exchange("/customer/{id}", HttpMethod.DELETE, null,
Void.class, customerSaved.getId());
Assertions.assertThat(customerResponseEntity).isNotNull();
Assertions.assertThat(customerResponseEntity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
}
}
|
// Copyright (C) 2021 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.notedb;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.entities.LabelId.CODE_REVIEW;
import static com.google.gerrit.entities.LabelId.VERIFIED;
import static com.google.gerrit.server.notedb.ReviewerStateInternal.CC;
import static com.google.gerrit.server.notedb.ReviewerStateInternal.REMOVED;
import static com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER;
import static java.util.Objects.requireNonNull;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.entities.Account;
import com.google.gerrit.entities.AttentionSetUpdate;
import com.google.gerrit.entities.AttentionSetUpdate.Operation;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.ChangeMessage;
import com.google.gerrit.entities.LabelId;
import com.google.gerrit.entities.PatchSetApproval;
import com.google.gerrit.entities.RefNames;
import com.google.gerrit.entities.SubmitRecord;
import com.google.gerrit.json.OutputFormat;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.ReviewerStatusUpdate;
import com.google.gerrit.server.notedb.ChangeNoteUtil.AttentionStatusInNoteDb;
import com.google.gerrit.server.notedb.CommitRewriter.BackfillResult;
import com.google.gerrit.server.notedb.CommitRewriter.RunOptions;
import com.google.gerrit.server.util.AccountTemplateUtil;
import com.google.gerrit.server.util.time.TimeUtil;
import com.google.gson.Gson;
import com.google.inject.Inject;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevSort;
import org.eclipse.jgit.revwalk.RevWalk;
import org.junit.Before;
import org.junit.Test;
/** Tests for {@link CommitRewriter} */
public class CommitRewriterTest extends AbstractChangeNotesTest {
private @Inject CommitRewriter rewriter;
@Inject private ChangeNoteUtil changeNoteUtil;
private static final Gson gson = OutputFormat.JSON_COMPACT.newGson();
@Before
public void setUp() throws Exception {}
@Test
public void validHistoryNoOp() throws Exception {
String tag = "jenkins";
Change c = newChange();
ChangeUpdate update = newUpdate(c, changeOwner);
update.setChangeMessage("verification from jenkins");
update.setTag(tag);
update.commit();
ChangeUpdate updateWithSubject = newUpdate(c, changeOwner);
updateWithSubject.setSubjectForCommit("Update with subject");
updateWithSubject.commit();
ChangeNotes notesBeforeRewrite = newNotes(c);
Ref metaRefBefore = repo.exactRef(RefNames.changeMetaRef(c.getId()));
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult backfillResult = rewriter.backfillProject(project, repo, options);
ChangeNotes notesAfterRewrite = newNotes(c);
Ref metaRefAfter = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(notesBeforeRewrite.getMetaId()).isEqualTo(notesAfterRewrite.getMetaId());
assertThat(metaRefBefore.getObjectId()).isEqualTo(metaRefAfter.getObjectId());
assertThat(backfillResult.fixedRefDiff).isEmpty();
}
@Test
public void failedVerification() throws Exception {
String tag = "jenkins";
Change c = newChange();
ChangeUpdate update = newUpdate(c, changeOwner);
update.setChangeMessage("Unknown commit " + changeOwner.getName());
update.setTag(tag);
update.commit();
ChangeUpdate updateWithSubject = newUpdate(c, changeOwner);
updateWithSubject.setSubjectForCommit("Update with subject");
updateWithSubject.commit();
ChangeNotes notesBeforeRewrite = newNotes(c);
Ref metaRefBefore = repo.exactRef(RefNames.changeMetaRef(c.getId()));
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult backfillResult = rewriter.backfillProject(project, repo, options);
assertThat(backfillResult.fixedRefDiff).isEmpty();
assertThat(backfillResult.refsStillInvalidAfterFix)
.containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
Ref metaRefAfter = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(notesBeforeRewrite.getMetaId()).isEqualTo(notesAfterRewrite.getMetaId());
assertThat(metaRefBefore.getObjectId()).isEqualTo(metaRefAfter.getObjectId());
}
@Test
public void fixAuthorIdent() throws Exception {
Change c = newChange();
Timestamp when = TimeUtil.nowTs();
PersonIdent invalidAuthorIdent =
new PersonIdent(
changeOwner.getName(),
changeNoteUtil.getAccountIdAsEmailAddress(changeOwner.getAccountId()),
when,
serverIdent.getTimeZone());
RevCommit invalidUpdateCommit =
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, /*changeMessage=*/ null),
invalidAuthorIdent);
ChangeUpdate validUpdate = newUpdate(c, changeOwner);
validUpdate.setChangeMessage("verification from jenkins");
validUpdate.setTag("jenkins");
validUpdate.commit();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(notesAfterRewrite.getChange().getOwner())
.isEqualTo(notesBeforeRewrite.getChange().getOwner());
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
int invalidCommitIndex = commitsBeforeRewrite.indexOf(invalidUpdateCommit);
assertValidCommits(
commitsBeforeRewrite, commitsAfterRewrite, ImmutableList.of(invalidCommitIndex));
RevCommit fixedUpdateCommit = commitsAfterRewrite.get(invalidCommitIndex);
PersonIdent originalAuthorIdent = invalidUpdateCommit.getAuthorIdent();
PersonIdent fixedAuthorIdent = fixedUpdateCommit.getAuthorIdent();
assertThat(originalAuthorIdent).isNotEqualTo(fixedAuthorIdent);
assertThat(fixedUpdateCommit.getAuthorIdent().getName())
.isEqualTo("Gerrit User " + changeOwner.getAccountId());
assertThat(originalAuthorIdent.getEmailAddress()).isEqualTo(fixedAuthorIdent.getEmailAddress());
assertThat(originalAuthorIdent.getWhen()).isEqualTo(fixedAuthorIdent.getWhen());
assertThat(originalAuthorIdent.getTimeZone()).isEqualTo(fixedAuthorIdent.getTimeZone());
assertThat(invalidUpdateCommit.getFullMessage()).isEqualTo(fixedUpdateCommit.getFullMessage());
assertThat(invalidUpdateCommit.getCommitterIdent())
.isEqualTo(fixedUpdateCommit.getCommitterIdent());
assertThat(fixedUpdateCommit.getFullMessage()).doesNotContain(changeOwner.getName());
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff).hasSize(1);
assertThat(commitHistoryDiff.get(0)).contains("-author Change Owner <1@gerrit>");
assertThat(commitHistoryDiff.get(0)).contains("+author Gerrit User 1 <1@gerrit>");
}
@Test
public void fixRealUserFooterIdent() throws Exception {
Change c = newChange();
String realUserIdentToFix = getAccountIdentToFix(otherUser.getAccount());
RevCommit invalidUpdateCommit =
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, "Comment on behalf of user", "Real-user: " + realUserIdentToFix),
getAuthorIdent(changeOwner.getAccount()));
IdentifiedUser impersonatedChangeOwner =
this.userFactory.runAs(
null, changeOwner.getAccountId(), requireNonNull(otherUser).getRealUser());
ChangeUpdate impersonatedChangeMessageUpdate = newUpdate(c, impersonatedChangeOwner);
impersonatedChangeMessageUpdate.setChangeMessage("Other comment on behalf of");
impersonatedChangeMessageUpdate.commit();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
int invalidCommitIndex = commitsBeforeRewrite.indexOf(invalidUpdateCommit);
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(changeMessages(notesBeforeRewrite))
.containsExactly("Comment on behalf of user", "Other comment on behalf of");
assertThat(notesBeforeRewrite.getChangeMessages().get(0).getAuthor())
.isEqualTo(changeOwner.getAccountId());
assertThat(notesBeforeRewrite.getChangeMessages().get(0).getRealAuthor())
.isEqualTo(otherUser.getAccountId());
assertThat(changeMessages(notesAfterRewrite))
.containsExactly("Comment on behalf of user", "Other comment on behalf of");
assertThat(notesBeforeRewrite.getChangeMessages().get(0).getAuthor())
.isEqualTo(changeOwner.getAccountId());
assertThat(notesBeforeRewrite.getChangeMessages().get(0).getRealAuthor())
.isEqualTo(otherUser.getAccountId());
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(
commitsBeforeRewrite, commitsAfterRewrite, ImmutableList.of(invalidCommitIndex));
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -9 +9 @@\n"
+ "-Real-user: Other Account <2@gerrit>\n"
+ "+Real-user: Gerrit User 2 <2@gerrit>\n");
}
@Test
public void fixReviewerFooterIdent() throws Exception {
Change c = newChange();
String reviewerIdentToFix = getAccountIdentToFix(otherUser.getAccount());
ImmutableList<RevCommit> commitsToFix =
new ImmutableList.Builder<RevCommit>()
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
// valid change message that should not be overwritten
getChangeUpdateBody(
c,
"Removed reviewer <GERRIT_ACCOUNT_1>.",
"Reviewer: " + reviewerIdentToFix),
getAuthorIdent(changeOwner.getAccount())))
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
// valid change message that should not be overwritten
getChangeUpdateBody(
c,
"Removed cc <GERRIT_ACCOUNT_2> with the following votes:\n\n * Code-Review+2 by <GERRIT_ACCOUNT_2>",
"CC: " + reviewerIdentToFix),
getAuthorIdent(otherUser.getAccount())))
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, "Removed cc", "Removed: " + reviewerIdentToFix),
getAuthorIdent(changeOwner.getAccount())))
.build();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
Timestamp updateTimestamp = new Timestamp(serverIdent.getWhen().getTime());
ImmutableList<ReviewerStatusUpdate> expectedReviewerUpdates =
ImmutableList.of(
ReviewerStatusUpdate.create(
updateTimestamp, changeOwner.getAccountId(), otherUserId, REVIEWER),
ReviewerStatusUpdate.create(updateTimestamp, otherUserId, otherUserId, CC),
ReviewerStatusUpdate.create(
updateTimestamp, changeOwner.getAccountId(), otherUserId, REMOVED));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(notesBeforeRewrite.getReviewerUpdates()).isEqualTo(expectedReviewerUpdates);
assertThat(notesAfterRewrite.getReviewerUpdates()).isEqualTo(expectedReviewerUpdates);
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -9 +9 @@\n"
+ "-Reviewer: Other Account <2@gerrit>\n"
+ "+Reviewer: Gerrit User 2 <2@gerrit>\n",
"@@ -11 +11 @@\n"
+ "-CC: Other Account <2@gerrit>\n"
+ "+CC: Gerrit User 2 <2@gerrit>\n",
"@@ -9 +9 @@\n"
+ "-Removed: Other Account <2@gerrit>\n"
+ "+Removed: Gerrit User 2 <2@gerrit>\n");
}
@Test
public void fixReviewerMessage() throws Exception {
Change c = newChange();
ImmutableList.Builder<RevCommit> commitsToFix = new ImmutableList.Builder<>();
ChangeUpdate addReviewerUpdate = newUpdate(c, changeOwner);
addReviewerUpdate.putReviewer(otherUserId, REVIEWER);
addReviewerUpdate.commit();
commitsToFix.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
String.format("Removed reviewer %s.", otherUser.getAccount().fullName()),
"Removed: " + getValidIdentAsString(otherUser.getAccount())),
getAuthorIdent(changeOwner.getAccount())));
ChangeUpdate addCcUpdate = newUpdate(c, changeOwner);
addCcUpdate.putReviewer(otherUserId, CC);
addCcUpdate.commit();
commitsToFix.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
String.format(
"Removed cc %s with the following votes:\n\n * Code-Review+2",
otherUser.getAccount().fullName()),
"Removed: " + getValidIdentAsString(otherUser.getAccount())),
getAuthorIdent(changeOwner.getAccount())));
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.build().stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
Timestamp updateTimestamp = new Timestamp(serverIdent.getWhen().getTime());
ImmutableList<ReviewerStatusUpdate> expectedReviewerUpdates =
ImmutableList.of(
ReviewerStatusUpdate.create(
new Timestamp(addReviewerUpdate.when.getTime()),
changeOwner.getAccountId(),
otherUserId,
REVIEWER),
ReviewerStatusUpdate.create(
updateTimestamp, changeOwner.getAccountId(), otherUserId, REMOVED),
ReviewerStatusUpdate.create(
new Timestamp(addCcUpdate.when.getTime()),
changeOwner.getAccountId(),
otherUserId,
CC),
ReviewerStatusUpdate.create(
updateTimestamp, changeOwner.getAccountId(), otherUserId, REMOVED));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(notesBeforeRewrite.getReviewerUpdates()).isEqualTo(expectedReviewerUpdates);
assertThat(changeMessages(notesBeforeRewrite))
.containsExactly(
"Removed reviewer Other Account.",
"Removed cc Other Account with the following votes:\n\n * Code-Review+2");
assertThat(notesAfterRewrite.getReviewerUpdates()).isEqualTo(expectedReviewerUpdates);
assertThat(changeMessages(notesAfterRewrite)).containsExactly("Removed reviewer", "Removed cc");
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n" + "-Removed reviewer Other Account.\n" + "+Removed reviewer\n",
"@@ -6,3 +6 @@\n"
+ "-Removed cc Other Account with the following votes:\n"
+ "-\n"
+ "- * Code-Review+2\n"
+ "+Removed cc\n");
}
@Test
public void fixReviewerMessageNoReviewerFooter() throws Exception {
Change c = newChange();
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c, String.format("Removed reviewer %s.", otherUser.getAccount().fullName())),
getAuthorIdent(changeOwner.getAccount()));
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
String.format(
"Removed cc %s with the following votes:\n\n * Code-Review+2",
otherUser.getAccount().fullName())),
getAuthorIdent(changeOwner.getAccount()));
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n" + "-Removed reviewer Other Account.\n" + "+Removed reviewer\n",
"@@ -6,3 +6 @@\n"
+ "-Removed cc Other Account with the following votes:\n"
+ "-\n"
+ "- * Code-Review+2\n"
+ "+Removed cc\n");
}
@Test
public void fixLabelFooterIdent() throws Exception {
Change c = newChange();
String approverIdentToFix = getAccountIdentToFix(otherUser.getAccount());
String changeOwnerIdentToFix = getAccountIdentToFix(changeOwner.getAccount());
ChangeUpdate approvalUpdateByOtherUser = newUpdate(c, otherUser);
approvalUpdateByOtherUser.putApproval(VERIFIED, (short) -1);
approvalUpdateByOtherUser.commit();
ImmutableList<RevCommit> commitsToFix =
new ImmutableList.Builder<RevCommit>()
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
/*changeMessage=*/ null,
"Label: -Verified " + approverIdentToFix,
"Label: Custom-Label-1=-1 " + approverIdentToFix,
"Label: Verified=+1",
"Label: Custom-Label-1=+1",
"Label: Custom-Label-2=+2 " + approverIdentToFix,
"Label: Custom-Label-3=0 " + approverIdentToFix),
getAuthorIdent(changeOwner.getAccount())))
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
/*changeMessage=*/ null,
"Label: -Verified " + changeOwnerIdentToFix,
"Label: Custom-Label-1=+1"),
getAuthorIdent(otherUser.getAccount())))
.build();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
Timestamp updateTimestamp = new Timestamp(serverIdent.getWhen().getTime());
ImmutableList<PatchSetApproval> expectedApprovals =
ImmutableList.of(
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(),
changeOwner.getAccountId(),
LabelId.create(VERIFIED)))
.value(0)
.granted(updateTimestamp)
.build(),
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(),
changeOwner.getAccountId(),
LabelId.create("Custom-Label-1")))
.value(+1)
.granted(updateTimestamp)
.build(),
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(), otherUserId, LabelId.create(VERIFIED)))
.value(0)
.granted(updateTimestamp)
.build(),
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(), otherUserId, LabelId.create("Custom-Label-1")))
.value(+1)
.granted(updateTimestamp)
.build(),
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(), otherUserId, LabelId.create("Custom-Label-2")))
.value(+2)
.granted(updateTimestamp)
.build(),
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(), otherUserId, LabelId.create("Custom-Label-3")))
.value(0)
.granted(updateTimestamp)
.build());
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(notesBeforeRewrite.getApprovals().get(c.currentPatchSetId()))
.containsExactlyElementsIn(expectedApprovals);
assertThat(notesAfterRewrite.getApprovals().get(c.currentPatchSetId()))
.containsExactlyElementsIn(expectedApprovals);
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -7,2 +7,2 @@\n"
+ "-Label: -Verified Other Account <2@gerrit>\n"
+ "-Label: Custom-Label-1=-1 Other Account <2@gerrit>\n"
+ "+Label: -Verified Gerrit User 2 <2@gerrit>\n"
+ "+Label: Custom-Label-1=-1 Gerrit User 2 <2@gerrit>\n"
+ "@@ -11,2 +11,2 @@\n"
+ "-Label: Custom-Label-2=+2 Other Account <2@gerrit>\n"
+ "-Label: Custom-Label-3=0 Other Account <2@gerrit>\n"
+ "+Label: Custom-Label-2=+2 Gerrit User 2 <2@gerrit>\n"
+ "+Label: Custom-Label-3=0 Gerrit User 2 <2@gerrit>\n",
"@@ -7 +7 @@\n"
+ "-Label: -Verified Change Owner <1@gerrit>\n"
+ "+Label: -Verified Gerrit User 1 <1@gerrit>\n");
}
@Test
public void fixRemoveVoteChangeMessage() throws Exception {
Change c = newChange();
String approverIdentToFix = getAccountIdentToFix(otherUser.getAccount());
ChangeUpdate approvalUpdateByOtherUser = newUpdate(c, otherUser);
approvalUpdateByOtherUser.putApproval(CODE_REVIEW, (short) +2);
approvalUpdateByOtherUser.putApproval("Custom-Label", (short) -1);
approvalUpdateByOtherUser.putApprovalFor(changeOwner.getAccountId(), VERIFIED, (short) -1);
approvalUpdateByOtherUser.commit();
ImmutableList<RevCommit> commitsToFix =
new ImmutableList.Builder<RevCommit>()
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
/*changeMessage=*/ "Removed Code-Review+2 by " + otherUser.getNameEmail(),
"Label: -Code-Review " + approverIdentToFix),
getAuthorIdent(changeOwner.getAccount())))
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
/*changeMessage=*/ "Removed Custom-Label-1 by " + otherUser.getNameEmail(),
"Label: -Custom-Label " + getValidIdentAsString(otherUser.getAccount())),
getAuthorIdent(changeOwner.getAccount())))
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
/*changeMessage=*/ "Removed Verified+2 by " + changeOwner.getNameEmail(),
"Label: -Verified"),
getAuthorIdent(changeOwner.getAccount())))
.build();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
Timestamp updateTimestamp = new Timestamp(serverIdent.getWhen().getTime());
ImmutableList<PatchSetApproval> expectedApprovals =
ImmutableList.of(
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(),
changeOwner.getAccountId(),
LabelId.create(VERIFIED)))
.value(0)
.granted(updateTimestamp)
.build(),
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(), otherUserId, LabelId.create("Custom-Label")))
.value(0)
.granted(updateTimestamp)
.build(),
PatchSetApproval.builder()
.key(
PatchSetApproval.key(
c.currentPatchSetId(), otherUserId, LabelId.create(CODE_REVIEW)))
.value(0)
.granted(updateTimestamp)
.build());
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(changeMessages(notesBeforeRewrite))
.containsExactly(
"Removed Code-Review+2 by Other Account <other@account.com>",
"Removed Custom-Label-1 by Other Account <other@account.com>",
"Removed Verified+2 by Change Owner <change@owner.com>");
assertThat(notesBeforeRewrite.getApprovals().get(c.currentPatchSetId()))
.containsExactlyElementsIn(expectedApprovals);
assertThat(changeMessages(notesAfterRewrite))
.containsExactly(
"Removed Code-Review+2 by <GERRIT_ACCOUNT_2>",
"Removed Custom-Label-1 by <GERRIT_ACCOUNT_2>",
"Removed Verified+2 by <GERRIT_ACCOUNT_1>");
assertThat(notesAfterRewrite.getApprovals().get(c.currentPatchSetId()))
.containsExactlyElementsIn(expectedApprovals);
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n"
+ "-Removed Code-Review+2 by Other Account <other@account.com>\n"
+ "+Removed Code-Review+2 by <GERRIT_ACCOUNT_2>\n"
+ "@@ -9 +9 @@\n"
+ "-Label: -Code-Review Other Account <2@gerrit>\n"
+ "+Label: -Code-Review Gerrit User 2 <2@gerrit>\n",
"@@ -6 +6 @@\n"
+ "-Removed Custom-Label-1 by Other Account <other@account.com>\n"
+ "+Removed Custom-Label-1 by <GERRIT_ACCOUNT_2>\n",
"@@ -6 +6 @@\n"
+ "-Removed Verified+2 by Change Owner <change@owner.com>\n"
+ "+Removed Verified+2 by <GERRIT_ACCOUNT_1>\n");
}
@Test
public void fixRemoveVoteChangeMessageWithUnparsableAuthorIdent() throws Exception {
Change c = newChange();
PersonIdent invalidAuthorIdent =
new PersonIdent(
changeOwner.getName(),
"server@" + serverId,
TimeUtil.nowTs(),
serverIdent.getTimeZone());
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
/*changeMessage=*/ "Removed Verified+2 by " + otherUser.getNameEmail(),
"Label: -Verified"),
invalidAuthorIdent);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
// Other Account does not applier in any change updates, replaced with default
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n"
+ "-Removed Verified+2 by Other Account <other@account.com>\n"
+ "+Removed Verified+2 by Gerrit Account\n");
}
@Test
public void fixRemoveVoteChangeMessageWithNoFooterLabel() throws Exception {
Change c = newChange();
ChangeUpdate approvalUpdate = newUpdate(c, changeOwner);
approvalUpdate.putApproval(VERIFIED, (short) +2);
approvalUpdate.putApprovalFor(otherUserId, VERIFIED, (short) -1);
approvalUpdate.commit();
writeUpdate(
RefNames.changeMetaRef(c.getId()),
// Even though footer is missing, accounts are matched among the account in change updates.
getChangeUpdateBody(c, /*changeMessage=*/ "Removed Verified-1 by Other Account (0002)"),
getAuthorIdent(changeOwner.getAccount()));
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c, /*changeMessage=*/ "Removed Verified+2 by " + changeOwner.getNameEmail()),
getAuthorIdent(changeOwner.getAccount()));
// No rewrite for default
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, /*changeMessage=*/ "Removed Verified+2 by Gerrit Account"),
getAuthorIdent(changeOwner.getAccount()));
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n"
+ "-Removed Verified-1 by Other Account (0002)\n"
+ "+Removed Verified-1 by <GERRIT_ACCOUNT_2>\n",
"@@ -6 +6 @@\n"
+ "-Removed Verified+2 by Change Owner <change@owner.com>\n"
+ "+Removed Verified+2 by <GERRIT_ACCOUNT_1>\n");
}
@Test
public void fixAttentionFooter() throws Exception {
Change c = newChange();
ImmutableList.Builder<ObjectId> commitsToFix = new ImmutableList.Builder<>();
// Only 'reason' fix is required
ChangeUpdate invalidAttentionSetUpdate = newUpdate(c, changeOwner);
invalidAttentionSetUpdate.putReviewer(otherUserId, REVIEWER);
invalidAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
otherUserId,
Operation.ADD,
String.format("Added by %s using the hovercard menu", otherUser.getName())));
commitsToFix.add(invalidAttentionSetUpdate.commit());
ChangeUpdate invalidMultipleAttentionSetUpdate = newUpdate(c, changeOwner);
invalidMultipleAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
changeOwner.getAccountId(),
Operation.ADD,
String.format("%s replied on the change", otherUser.getName())));
invalidMultipleAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
otherUserId,
Operation.REMOVE,
String.format("Removed by %s using the hovercard menu", otherUser.getName())));
commitsToFix.add(invalidMultipleAttentionSetUpdate.commit());
String otherUserIdentToFix = getAccountIdentToFix(otherUser.getAccount());
String changeOwnerIdentToFix = getAccountIdentToFix(changeOwner.getAccount());
commitsToFix.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
/*changeMessage=*/ null,
// Only 'person_ident' fix is required
"Attention: "
+ gson.toJson(
new AttentionStatusInNoteDb(
otherUserIdentToFix,
Operation.ADD,
"Added by someone using the hovercard menu")),
// Both 'reason' and 'person_ident' fix is required
"Attention: "
+ gson.toJson(
new AttentionStatusInNoteDb(
changeOwnerIdentToFix,
Operation.REMOVE,
String.format("%s replied on the change", otherUser.getName())))),
getAuthorIdent(changeOwner.getAccount())));
ChangeUpdate validAttentionSetUpdate = newUpdate(c, changeOwner);
validAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(otherUserId, Operation.REMOVE, "Removed by someone"));
validAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
changeOwner.getAccountId(), Operation.ADD, "Added by someone"));
validAttentionSetUpdate.commit();
ChangeUpdate invalidRemovedByClickUpdate = newUpdate(c, changeOwner);
invalidRemovedByClickUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
changeOwner.getAccountId(),
Operation.REMOVE,
String.format("Removed by %s by clicking the attention icon", otherUser.getName())));
commitsToFix.add(invalidRemovedByClickUpdate.commit());
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.build().stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
notesBeforeRewrite.getAttentionSetUpdates();
Timestamp updateTimestamp = new Timestamp(serverIdent.getWhen().getTime());
ImmutableList<AttentionSetUpdate> attentionSetUpdatesBeforeRewrite =
ImmutableList.of(
AttentionSetUpdate.createFromRead(
invalidRemovedByClickUpdate.getWhen().toInstant(),
changeOwner.getAccountId(),
Operation.REMOVE,
String.format("Removed by %s by clicking the attention icon", otherUser.getName())),
AttentionSetUpdate.createFromRead(
validAttentionSetUpdate.getWhen().toInstant(),
changeOwner.getAccountId(),
Operation.ADD,
"Added by someone"),
AttentionSetUpdate.createFromRead(
validAttentionSetUpdate.getWhen().toInstant(),
otherUserId,
Operation.REMOVE,
"Removed by someone"),
AttentionSetUpdate.createFromRead(
updateTimestamp.toInstant(),
changeOwner.getAccountId(),
Operation.REMOVE,
String.format("%s replied on the change", otherUser.getName())),
AttentionSetUpdate.createFromRead(
updateTimestamp.toInstant(),
otherUserId,
Operation.ADD,
"Added by someone using the hovercard menu"),
AttentionSetUpdate.createFromRead(
invalidMultipleAttentionSetUpdate.getWhen().toInstant(),
otherUserId,
Operation.REMOVE,
String.format("Removed by %s using the hovercard menu", otherUser.getName())),
AttentionSetUpdate.createFromRead(
invalidMultipleAttentionSetUpdate.getWhen().toInstant(),
changeOwner.getAccountId(),
Operation.ADD,
String.format("%s replied on the change", otherUser.getName())),
AttentionSetUpdate.createFromRead(
invalidAttentionSetUpdate.getWhen().toInstant(),
otherUserId,
Operation.ADD,
String.format("Added by %s using the hovercard menu", otherUser.getName())));
ImmutableList<AttentionSetUpdate> attentionSetUpdatesAfterRewrite =
ImmutableList.of(
AttentionSetUpdate.createFromRead(
invalidRemovedByClickUpdate.getWhen().toInstant(),
changeOwner.getAccountId(),
Operation.REMOVE,
"Removed by someone by clicking the attention icon"),
AttentionSetUpdate.createFromRead(
validAttentionSetUpdate.getWhen().toInstant(),
changeOwner.getAccountId(),
Operation.ADD,
"Added by someone"),
AttentionSetUpdate.createFromRead(
validAttentionSetUpdate.getWhen().toInstant(),
otherUserId,
Operation.REMOVE,
"Removed by someone"),
AttentionSetUpdate.createFromRead(
updateTimestamp.toInstant(),
changeOwner.getAccountId(),
Operation.REMOVE,
"Someone replied on the change"),
AttentionSetUpdate.createFromRead(
updateTimestamp.toInstant(),
otherUserId,
Operation.ADD,
"Added by someone using the hovercard menu"),
AttentionSetUpdate.createFromRead(
invalidMultipleAttentionSetUpdate.getWhen().toInstant(),
otherUserId,
Operation.REMOVE,
"Removed by someone using the hovercard menu"),
AttentionSetUpdate.createFromRead(
invalidMultipleAttentionSetUpdate.getWhen().toInstant(),
changeOwner.getAccountId(),
Operation.ADD,
"Someone replied on the change"),
AttentionSetUpdate.createFromRead(
invalidAttentionSetUpdate.getWhen().toInstant(),
otherUserId,
Operation.ADD,
"Added by someone using the hovercard menu"));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(notesBeforeRewrite.getAttentionSetUpdates())
.containsExactlyElementsIn(attentionSetUpdatesBeforeRewrite);
assertThat(notesAfterRewrite.getAttentionSetUpdates())
.containsExactlyElementsIn(attentionSetUpdatesAfterRewrite);
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff).hasSize(4);
assertThat(commitHistoryDiff.get(0))
.isEqualTo(
"@@ -8 +8 @@\n"
+ "-Attention: {\"person_ident\":\"Gerrit User 2 \\u003c2@gerrit\\u003e\",\"operation\":\"ADD\",\"reason\":\"Added by Other Account using the hovercard menu\"}\n"
+ "+Attention: {\"person_ident\":\"Gerrit User 2 \\u003c2@gerrit\\u003e\",\"operation\":\"ADD\",\"reason\":\"Added by someone using the hovercard menu\"}\n");
assertThat(Arrays.asList(commitHistoryDiff.get(1).split("\n")))
.containsExactly(
"@@ -7,2 +7,2 @@",
"-Attention: {\"person_ident\":\"Gerrit User 1 \\u003c1@gerrit\\u003e\",\"operation\":\"ADD\",\"reason\":\"Other Account replied on the change\"}",
"-Attention: {\"person_ident\":\"Gerrit User 2 \\u003c2@gerrit\\u003e\",\"operation\":\"REMOVE\",\"reason\":\"Removed by Other Account using the hovercard menu\"}",
"+Attention: {\"person_ident\":\"Gerrit User 1 \\u003c1@gerrit\\u003e\",\"operation\":\"ADD\",\"reason\":\"Someone replied on the change\"}",
"+Attention: {\"person_ident\":\"Gerrit User 2 \\u003c2@gerrit\\u003e\",\"operation\":\"REMOVE\",\"reason\":\"Removed by someone using the hovercard menu\"}");
assertThat(Arrays.asList(commitHistoryDiff.get(2).split("\n")))
.containsExactly(
"@@ -7,2 +7,2 @@",
"-Attention: {\"person_ident\":\"Other Account \\u003c2@gerrit\\u003e\",\"operation\":\"ADD\",\"reason\":\"Added by someone using the hovercard menu\"}",
"-Attention: {\"person_ident\":\"Change Owner \\u003c1@gerrit\\u003e\",\"operation\":\"REMOVE\",\"reason\":\"Other Account replied on the change\"}",
"+Attention: {\"person_ident\":\"Gerrit User 2 \\u003c2@gerrit\\u003e\",\"operation\":\"ADD\",\"reason\":\"Added by someone using the hovercard menu\"}",
"+Attention: {\"person_ident\":\"Gerrit User 1 \\u003c1@gerrit\\u003e\",\"operation\":\"REMOVE\",\"reason\":\"Someone replied on the change\"}");
assertThat(commitHistoryDiff.get(3))
.isEqualTo(
"@@ -7 +7 @@\n"
+ "-Attention: {\"person_ident\":\"Gerrit User 1 \\u003c1@gerrit\\u003e\",\"operation\":\"REMOVE\",\"reason\":\"Removed by Other Account by clicking the attention icon\"}\n"
+ "+Attention: {\"person_ident\":\"Gerrit User 1 \\u003c1@gerrit\\u003e\",\"operation\":\"REMOVE\",\"reason\":\"Removed by someone by clicking the attention icon\"}\n");
}
@Test
public void fixAttentionFooter_okReason_noRewrite() throws Exception {
Change c = newChange();
ImmutableList<String> okAccountNames =
ImmutableList.of(
"Someone",
"Someone else",
"someone",
"someone else",
"Anonymous",
"anonymous",
"<GERRIT_ACCOUNT_1>",
"<GERRIT_ACCOUNT_2>");
ImmutableList.Builder<AttentionSetUpdate> attentionSetUpdatesBeforeRewrite =
new ImmutableList.Builder<>();
for (String okAccountName : okAccountNames) {
ChangeUpdate firstAttentionSetUpdate = newUpdate(c, changeOwner);
firstAttentionSetUpdate.putReviewer(otherUserId, REVIEWER);
firstAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
otherUserId,
Operation.ADD,
String.format("Added by %s using the hovercard menu", okAccountName)));
firstAttentionSetUpdate.commit();
ChangeUpdate secondAttentionSetUpdate = newUpdate(c, changeOwner);
secondAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
changeOwner.getAccountId(),
Operation.ADD,
String.format("%s replied on the change", okAccountName)));
secondAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
otherUserId,
Operation.REMOVE,
String.format("Removed by %s using the hovercard menu", okAccountName)));
secondAttentionSetUpdate.commit();
ChangeUpdate thirdAttentionSetUpdate = newUpdate(c, changeOwner);
thirdAttentionSetUpdate.addToPlannedAttentionSetUpdates(
AttentionSetUpdate.createForWrite(
changeOwner.getAccountId(),
Operation.REMOVE,
String.format("Removed by %s by clicking the attention icon", okAccountName)));
thirdAttentionSetUpdate.commit();
attentionSetUpdatesBeforeRewrite.add(
AttentionSetUpdate.createFromRead(
thirdAttentionSetUpdate.getWhen().toInstant(),
changeOwner.getAccountId(),
Operation.REMOVE,
String.format("Removed by %s by clicking the attention icon", okAccountName)),
AttentionSetUpdate.createFromRead(
secondAttentionSetUpdate.getWhen().toInstant(),
otherUserId,
Operation.REMOVE,
String.format("Removed by %s using the hovercard menu", okAccountName)),
AttentionSetUpdate.createFromRead(
secondAttentionSetUpdate.getWhen().toInstant(),
changeOwner.getAccountId(),
Operation.ADD,
String.format("%s replied on the change", okAccountName)),
AttentionSetUpdate.createFromRead(
firstAttentionSetUpdate.getWhen().toInstant(),
otherUserId,
Operation.ADD,
String.format("Added by %s using the hovercard menu", okAccountName)));
}
ChangeNotes notesBeforeRewrite = newNotes(c);
assertThat(notesBeforeRewrite.getAttentionSetUpdates())
.containsExactlyElementsIn(attentionSetUpdatesBeforeRewrite.build());
Ref metaRefBefore = repo.exactRef(RefNames.changeMetaRef(c.getId()));
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult backfillResult = rewriter.backfillProject(project, repo, options);
ChangeNotes notesAfterRewrite = newNotes(c);
Ref metaRefAfter = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(notesBeforeRewrite.getMetaId()).isEqualTo(notesAfterRewrite.getMetaId());
assertThat(metaRefBefore.getObjectId()).isEqualTo(metaRefAfter.getObjectId());
assertThat(backfillResult.fixedRefDiff).isEmpty();
}
@Test
public void fixSubmitChangeMessage() throws Exception {
Change c = newChange();
ImmutableList.Builder<ObjectId> commitsToFix = new ImmutableList.Builder<>();
ChangeUpdate invalidMergedMessageUpdate = newUpdate(c, changeOwner);
invalidMergedMessageUpdate.setChangeMessage(
"Change has been successfully merged by " + changeOwner.getName());
invalidMergedMessageUpdate.setTopic("");
commitsToFix.add(invalidMergedMessageUpdate.commit());
ChangeUpdate invalidCherryPickedMessageUpdate = newUpdate(c, changeOwner);
invalidCherryPickedMessageUpdate.setChangeMessage(
"Change has been successfully cherry-picked as e40dc1a50dc7f457a37579e2755374f3e1a5413b by "
+ changeOwner.getName());
commitsToFix.add(invalidCherryPickedMessageUpdate.commit());
ChangeUpdate invalidRebasedMessageUpdate = newUpdate(c, changeOwner);
invalidRebasedMessageUpdate.setChangeMessage(
"Change has been successfully rebased and submitted as e40dc1a50dc7f457a37579e2755374f3e1a5413b by "
+ changeOwner.getName());
commitsToFix.add(invalidRebasedMessageUpdate.commit());
ChangeUpdate validSubmitMessageUpdate = newUpdate(c, changeOwner);
validSubmitMessageUpdate.setChangeMessage(
"Change has been successfully rebased and submitted as e40dc1a50dc7f457a37579e2755374f3e1a5413b");
validSubmitMessageUpdate.commit();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.build().stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(changeMessages(notesBeforeRewrite))
.containsExactly(
"Change has been successfully merged by Change Owner",
"Change has been successfully cherry-picked as e40dc1a50dc7f457a37579e2755374f3e1a5413b by Change Owner",
"Change has been successfully rebased and submitted as e40dc1a50dc7f457a37579e2755374f3e1a5413b by Change Owner",
"Change has been successfully rebased and submitted as e40dc1a50dc7f457a37579e2755374f3e1a5413b");
assertThat(changeMessages(notesAfterRewrite))
.containsExactly(
"Change has been successfully merged",
"Change has been successfully cherry-picked as e40dc1a50dc7f457a37579e2755374f3e1a5413b",
"Change has been successfully rebased and submitted as e40dc1a50dc7f457a37579e2755374f3e1a5413b",
"Change has been successfully rebased and submitted as e40dc1a50dc7f457a37579e2755374f3e1a5413b");
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n"
+ "-Change has been successfully merged by Change Owner\n"
+ "+Change has been successfully merged\n",
"@@ -6 +6 @@\n"
+ "-Change has been successfully cherry-picked as e40dc1a50dc7f457a37579e2755374f3e1a5413b by Change Owner\n"
+ "+Change has been successfully cherry-picked as e40dc1a50dc7f457a37579e2755374f3e1a5413b\n",
"@@ -6 +6 @@\n"
+ "-Change has been successfully rebased and submitted as e40dc1a50dc7f457a37579e2755374f3e1a5413b by Change Owner\n"
+ "+Change has been successfully rebased and submitted as e40dc1a50dc7f457a37579e2755374f3e1a5413b\n");
}
@Test
public void fixSubmitChangeMessageAndFooters() throws Exception {
Change c = newChange();
PersonIdent invalidAuthorIdent =
new PersonIdent(
changeOwner.getName(),
changeNoteUtil.getAccountIdAsEmailAddress(changeOwner.getAccountId()),
TimeUtil.nowTs(),
serverIdent.getTimeZone());
String changeOwnerIdentToFix = getAccountIdentToFix(changeOwner.getAccount());
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
"Change has been successfully merged by " + changeOwner.getName(),
"Status: merged",
"Tag: autogenerated:gerrit:merged",
"Reviewer: " + changeOwnerIdentToFix,
"Label: SUBM=+1",
"Submission-id: 6310-1521542139810-cfb7e159",
"Submitted-with: OK",
"Submitted-with: OK: Code-Review: " + changeOwnerIdentToFix),
invalidAuthorIdent);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -1 +1 @@\n"
+ "-author Change Owner <1@gerrit> 1254344405 -0700\n"
+ "+author Gerrit User 1 <1@gerrit> 1254344405 -0700\n"
+ "@@ -6 +6 @@\n"
+ "-Change has been successfully merged by Change Owner\n"
+ "+Change has been successfully merged\n"
+ "@@ -11 +11 @@\n"
+ "-Reviewer: Change Owner <1@gerrit>\n"
+ "+Reviewer: Gerrit User 1 <1@gerrit>\n"
+ "@@ -15 +15 @@\n"
+ "-Submitted-with: OK: Code-Review: Change Owner <1@gerrit>\n"
+ "+Submitted-with: OK: Code-Review: Gerrit User 1 <1@gerrit>\n");
}
@Test
public void fixSubmittedWithFooterIdent() throws Exception {
Change c = newChange();
ChangeUpdate preSubmitUpdate = newUpdate(c, changeOwner);
preSubmitUpdate.setChangeMessage("Per-submit update");
preSubmitUpdate.commit();
String otherUserIdentToFix = getAccountIdentToFix(otherUser.getAccount());
String changeOwnerIdentToFix = getAccountIdentToFix(changeOwner.getAccount());
RevCommit invalidUpdateCommit =
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
/*changeMessage=*/ null,
"Label: SUBM=+1",
"Submission-id: 5271-1496917120975-10a10df9",
"Submitted-with: NOT_READY",
"Submitted-with: NEED: Code-Review: " + otherUserIdentToFix,
"Submitted-with: OK: Code-Style",
"Submitted-with: OK: Verified: " + changeOwnerIdentToFix,
"Submitted-with: FORCED with error"),
getAuthorIdent(changeOwner.getAccount()));
ChangeUpdate postSubmitUpdate = newUpdate(c, changeOwner);
postSubmitUpdate.setChangeMessage("Per-submit update");
postSubmitUpdate.commit();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
int invalidCommitIndex = commitsBeforeRewrite.indexOf(invalidUpdateCommit);
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
ImmutableList<SubmitRecord> expectedRecords =
ImmutableList.of(
submitRecord(
"NOT_READY",
null,
submitLabel(CODE_REVIEW, "NEED", otherUserId),
submitLabel("Code-Style", "OK", null),
submitLabel(VERIFIED, "OK", changeOwner.getAccountId())),
submitRecord("FORCED", " with error"));
assertThat(notesBeforeRewrite.getSubmitRecords()).isEqualTo(expectedRecords);
assertThat(notesAfterRewrite.getSubmitRecords()).isEqualTo(expectedRecords);
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(
commitsBeforeRewrite, commitsAfterRewrite, ImmutableList.of(invalidCommitIndex));
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -10 +10 @@\n"
+ "-Submitted-with: NEED: Code-Review: Other Account <2@gerrit>\n"
+ "+Submitted-with: NEED: Code-Review: Gerrit User 2 <2@gerrit>\n"
+ "@@ -12 +12 @@\n"
+ "-Submitted-with: OK: Verified: Change Owner <1@gerrit>\n"
+ "+Submitted-with: OK: Verified: Gerrit User 1 <1@gerrit>\n");
}
@Test
public void fixDeleteChangeMessageCommitMessage() throws Exception {
Change c = newChange();
ImmutableList.Builder<ObjectId> commitsToFix = new ImmutableList.Builder<>();
ChangeUpdate invalidDeleteChangeMessageUpdate = newUpdate(c, changeOwner);
invalidDeleteChangeMessageUpdate.setChangeMessage(
"Change message removed by: " + changeOwner.getName());
commitsToFix.add(invalidDeleteChangeMessageUpdate.commit());
ChangeUpdate invalidDeleteChangeMessageUpdateWithReason = newUpdate(c, changeOwner);
invalidDeleteChangeMessageUpdateWithReason.setChangeMessage(
String.format(
"Change message removed by: %s\nReason: %s",
changeOwner.getName(), "contains confidential information"));
commitsToFix.add(invalidDeleteChangeMessageUpdateWithReason.commit());
ChangeUpdate validDeleteChangeMessageUpdate = newUpdate(c, changeOwner);
validDeleteChangeMessageUpdate.setChangeMessage(
"Change message removed by: <GERRIT_ACCOUNT_1>");
validDeleteChangeMessageUpdate.commit();
ChangeUpdate validDeleteChangeMessageUpdateWithReason = newUpdate(c, changeOwner);
validDeleteChangeMessageUpdateWithReason.setChangeMessage(
"Change message removed by: <GERRIT_ACCOUNT_1>\nReason: abusive language");
validDeleteChangeMessageUpdateWithReason.commit();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.build().stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(changeMessages(notesBeforeRewrite))
.containsExactly(
"Change message removed by: Change Owner",
"Change message removed by: Change Owner\n"
+ "Reason: contains confidential information",
"Change message removed by: <GERRIT_ACCOUNT_1>",
"Change message removed by: <GERRIT_ACCOUNT_1>\n" + "Reason: abusive language");
assertThat(changeMessages(notesAfterRewrite))
.containsExactly(
"Change message removed",
"Change message removed\n" + "Reason: contains confidential information",
"Change message removed by: <GERRIT_ACCOUNT_1>",
"Change message removed by: <GERRIT_ACCOUNT_1>\n" + "Reason: abusive language");
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n"
+ "-Change message removed by: Change Owner\n"
+ "+Change message removed\n",
"@@ -6 +6 @@\n"
+ "-Change message removed by: Change Owner\n"
+ "+Change message removed\n");
}
@Test
public void fixCodeOwnersOnAddReviewerChangeMessage() throws Exception {
Account reviewer =
Account.builder(Account.id(3), TimeUtil.nowTs())
.setFullName("Reviewer User")
.setPreferredEmail("reviewer@account.com")
.build();
accountCache.put(reviewer);
Account duplicateCodeOwner =
Account.builder(Account.id(4), TimeUtil.nowTs()).setFullName(changeOwner.getName()).build();
accountCache.put(duplicateCodeOwner);
Account duplicateReviewer =
Account.builder(Account.id(5), TimeUtil.nowTs()).setFullName(reviewer.getName()).build();
accountCache.put(duplicateReviewer);
Change c = newChange();
ImmutableList.Builder<ObjectId> commitsToFix = new ImmutableList.Builder<>();
ChangeUpdate addReviewerUpdate = newUpdate(c, changeOwner);
addReviewerUpdate.putReviewer(reviewer.id(), REVIEWER);
addReviewerUpdate.commit();
ChangeUpdate invalidOnAddReviewerUpdate = newUpdate(c, changeOwner);
invalidOnAddReviewerUpdate.setChangeMessage(
"Reviewer User who was added as reviewer owns the following files:\n"
+ " * file1.java\n"
+ " * file2.ts\n");
commitsToFix.add(invalidOnAddReviewerUpdate.commit());
ChangeUpdate addOtherReviewerUpdate = newUpdate(c, changeOwner);
addOtherReviewerUpdate.putReviewer(otherUserId, REVIEWER);
addOtherReviewerUpdate.commit();
ChangeUpdate invalidOnAddReviewerMultipleReviewerUpdate = newUpdate(c, changeOwner);
invalidOnAddReviewerMultipleReviewerUpdate.setChangeMessage(
"Reviewer User who was added as reviewer owns the following files:\n"
+ " * file1.java\n"
+ "\nOther Account who was added as reviewer owns the following files:\n"
+ " * file3.js\n"
+ "\nMissing Reviewer who was added as reviewer owns the following files:\n"
+ " * file4.java\n");
commitsToFix.add(invalidOnAddReviewerMultipleReviewerUpdate.commit());
ChangeUpdate addDuplicateReviewerUpdate = newUpdate(c, changeOwner);
addDuplicateReviewerUpdate.putReviewer(duplicateReviewer.id(), REVIEWER);
addDuplicateReviewerUpdate.commit();
// Reviewer name resolves to multiple accounts in the same change
ChangeUpdate onAddReviewerUpdateWithDuplicate = newUpdate(c, changeOwner);
onAddReviewerUpdateWithDuplicate.setChangeMessage(
"Reviewer User who was added as reviewer owns the following files:\n"
+ " * file6.java\n");
commitsToFix.add(onAddReviewerUpdateWithDuplicate.commit());
ChangeUpdate validOnAddReviewerUpdate = newUpdate(c, changeOwner);
validOnAddReviewerUpdate.setChangeMessage(
"Gerrit Account who was added as reviewer owns the following files:\n"
+ " * file1.java\n"
+ "\n<GERRIT_ACCOUNT_1> who was added as reviewer owns the following files:\n"
+ " * file3.js\n");
validOnAddReviewerUpdate.commit();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.build().stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(changeMessages(notesBeforeRewrite)).hasSize(4);
assertThat(changeMessages(notesAfterRewrite))
.containsExactly(
"<GERRIT_ACCOUNT_3>, who was added as reviewer owns the following files:\n"
+ " * file1.java\n"
+ " * file2.ts\n",
"<GERRIT_ACCOUNT_3>, who was added as reviewer owns the following files:\n"
+ " * file1.java\n"
+ "\n<GERRIT_ACCOUNT_2>, who was added as reviewer owns the following files:\n"
+ " * file3.js\n"
+ "\nGerrit Account, who was added as reviewer owns the following files:\n"
+ " * file4.java\n",
"Gerrit Account, who was added as reviewer owns the following files:\n"
+ " * file6.java\n",
"Gerrit Account who was added as reviewer owns the following files:\n"
+ " * file1.java\n"
+ "\n<GERRIT_ACCOUNT_1> who was added as reviewer owns the following files:\n"
+ " * file3.js\n");
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n"
+ "-Reviewer User who was added as reviewer owns the following files:\n"
+ "+<GERRIT_ACCOUNT_3>, who was added as reviewer owns the following files:\n",
"@@ -6 +6 @@\n"
+ "-Reviewer User who was added as reviewer owns the following files:\n"
+ "+<GERRIT_ACCOUNT_3>, who was added as reviewer owns the following files:\n"
+ "@@ -9 +9 @@\n"
+ "-Other Account who was added as reviewer owns the following files:\n"
+ "+<GERRIT_ACCOUNT_2>, who was added as reviewer owns the following files:\n"
+ "@@ -12 +12 @@\n"
+ "-Missing Reviewer who was added as reviewer owns the following files:\n"
+ "+Gerrit Account, who was added as reviewer owns the following files:\n",
"@@ -6 +6 @@\n"
+ "-Reviewer User who was added as reviewer owns the following files:\n"
+ "+Gerrit Account, who was added as reviewer owns the following files:\n");
}
@Test
public void fixCodeOwnersOnReviewChangeMessage() throws Exception {
Change c = newChange();
ImmutableList.Builder<ObjectId> commitsToFix = new ImmutableList.Builder<>();
ChangeUpdate invalidOnReviewUpdate = newUpdate(c, changeOwner);
invalidOnReviewUpdate.setChangeMessage(
"Patch Set 1: Any-Label+2 Other-Label+2 Code-Review+2\n\n"
+ "By voting Code-Review+2 the following files are now code-owner approved by Change Owner:\n"
+ " * file1.java\n"
+ " * file2.ts\n"
+ "By voting Any-Label+2 the code-owners submit requirement is overridden by Change Owner\n"
+ "By voting Other-Label+2 the code-owners submit requirement is still overridden by Change Owner\n");
commitsToFix.add(invalidOnReviewUpdate.commit());
ChangeUpdate invalidOnReviewUpdateAnyOrder = newUpdate(c, changeOwner);
invalidOnReviewUpdateAnyOrder.setChangeMessage(
"Patch Set 1: Any-Label+2 Other-Label+2 Code-Review+2\n\n"
+ "By voting Any-Label+2 the code-owners submit requirement is overridden by Change Owner\n"
+ "By voting Other-Label+2 the code-owners submit requirement is still overridden by Change Owner\n"
+ "By voting Code-Review+2 the following files are now code-owner approved by Change Owner:\n"
+ " * file1.java\n"
+ " * file2.ts\n");
commitsToFix.add(invalidOnReviewUpdateAnyOrder.commit());
ChangeUpdate invalidOnApprovalUpdate = newUpdate(c, otherUser);
invalidOnApprovalUpdate.setChangeMessage(
"Patch Set 1: -Code-Review\n\n"
+ "By removing the Code-Review+2 vote the following files are no longer explicitly code-owner approved by Other Account:\n"
+ " * file1.java\n"
+ " * file2.ts\n"
+ "\nThe listed files are still implicitly approved by Other Account.\n");
commitsToFix.add(invalidOnApprovalUpdate.commit());
ChangeUpdate invalidOnOverrideUpdate = newUpdate(c, changeOwner);
invalidOnOverrideUpdate.setChangeMessage(
"Patch Set 1: -Owners-Override\n\n"
+ "(1 comment)\n\n"
+ "By removing the Owners-Override+1 vote the code-owners submit requirement is no longer overridden by Change Owner\n");
commitsToFix.add(invalidOnOverrideUpdate.commit());
ChangeUpdate partiallyValidOnReviewUpdate = newUpdate(c, changeOwner);
partiallyValidOnReviewUpdate.setChangeMessage(
"Patch Set 1: Any-Label+2 Code-Review+2\n\n"
+ "By voting Code-Review+2 the following files are now code-owner approved by <GERRIT_ACCOUNT_1>:\n"
+ " * file1.java\n"
+ " * file2.ts\n"
+ "By voting Any-Label+2 the code-owners submit requirement is overridden by Change Owner\n");
commitsToFix.add(partiallyValidOnReviewUpdate.commit());
ChangeUpdate validOnApprovalUpdate = newUpdate(c, changeOwner);
validOnApprovalUpdate.setChangeMessage(
"Patch Set 1: Code-Review-2\n\n"
+ "By voting Code-Review-2 the following files are no longer explicitly code-owner approved by <GERRIT_ACCOUNT_1>:\n"
+ " * file4.java\n");
validOnApprovalUpdate.commit();
ChangeUpdate validOnOverrideUpdate = newUpdate(c, changeOwner);
validOnOverrideUpdate.setChangeMessage(
"Patch Set 1: Owners-Override+1\n\n"
+ "By voting Owners-Override+1 the code-owners submit requirement is still overridden by <GERRIT_ACCOUNT_1>\n");
validOnOverrideUpdate.commit();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.build().stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(changeMessages(notesBeforeRewrite)).hasSize(7);
assertThat(changeMessages(notesAfterRewrite))
.containsExactly(
"Patch Set 1: Any-Label+2 Other-Label+2 Code-Review+2\n\n"
+ "By voting Code-Review+2 the following files are now code-owner approved by <GERRIT_ACCOUNT_1>:\n"
+ " * file1.java\n"
+ " * file2.ts\n"
+ "By voting Any-Label+2 the code-owners submit requirement is overridden by <GERRIT_ACCOUNT_1>\n"
+ "By voting Other-Label+2 the code-owners submit requirement is still overridden by <GERRIT_ACCOUNT_1>\n",
"Patch Set 1: Any-Label+2 Other-Label+2 Code-Review+2\n\n"
+ "By voting Any-Label+2 the code-owners submit requirement is overridden by <GERRIT_ACCOUNT_1>\n"
+ "By voting Other-Label+2 the code-owners submit requirement is still overridden by <GERRIT_ACCOUNT_1>\n"
+ "By voting Code-Review+2 the following files are now code-owner approved by <GERRIT_ACCOUNT_1>:\n"
+ " * file1.java\n"
+ " * file2.ts\n",
"Patch Set 1: -Code-Review\n"
+ "\n"
+ "By removing the Code-Review+2 vote the following files are no longer explicitly code-owner approved by <GERRIT_ACCOUNT_2>:\n"
+ " * file1.java\n"
+ " * file2.ts\n"
+ "\nThe listed files are still implicitly approved by <GERRIT_ACCOUNT_2>.\n",
"Patch Set 1: -Owners-Override\n"
+ "\n"
+ "(1 comment)\n"
+ "\n"
+ "By removing the Owners-Override+1 vote the code-owners submit requirement is no longer overridden by <GERRIT_ACCOUNT_1>\n",
"Patch Set 1: Any-Label+2 Code-Review+2\n\n"
+ "By voting Code-Review+2 the following files are now code-owner approved by <GERRIT_ACCOUNT_1>:\n"
+ " * file1.java\n"
+ " * file2.ts\n"
+ "By voting Any-Label+2 the code-owners submit requirement is overridden by <GERRIT_ACCOUNT_1>\n",
"Patch Set 1: Code-Review-2\n\n"
+ "By voting Code-Review-2 the following files are no longer explicitly code-owner approved by <GERRIT_ACCOUNT_1>:\n"
+ " * file4.java\n",
"Patch Set 1: Owners-Override+1\n"
+ "\n"
+ "By voting Owners-Override+1 the code-owners submit requirement is still overridden by <GERRIT_ACCOUNT_1>\n");
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -8 +8 @@\n"
+ "-By voting Code-Review+2 the following files are now code-owner approved by Change Owner:\n"
+ "+By voting Code-Review+2 the following files are now code-owner approved by <GERRIT_ACCOUNT_1>:\n"
+ "@@ -11,2 +11,2 @@\n"
+ "-By voting Any-Label+2 the code-owners submit requirement is overridden by Change Owner\n"
+ "-By voting Other-Label+2 the code-owners submit requirement is still overridden by Change Owner\n"
+ "+By voting Any-Label+2 the code-owners submit requirement is overridden by <GERRIT_ACCOUNT_1>\n"
+ "+By voting Other-Label+2 the code-owners submit requirement is still overridden by <GERRIT_ACCOUNT_1>\n",
"@@ -8,3 +8,3 @@\n"
+ "-By voting Any-Label+2 the code-owners submit requirement is overridden by Change Owner\n"
+ "-By voting Other-Label+2 the code-owners submit requirement is still overridden by Change Owner\n"
+ "-By voting Code-Review+2 the following files are now code-owner approved by Change Owner:\n"
+ "+By voting Any-Label+2 the code-owners submit requirement is overridden by <GERRIT_ACCOUNT_1>\n"
+ "+By voting Other-Label+2 the code-owners submit requirement is still overridden by <GERRIT_ACCOUNT_1>\n"
+ "+By voting Code-Review+2 the following files are now code-owner approved by <GERRIT_ACCOUNT_1>:\n",
"@@ -8 +8 @@\n"
+ "-By removing the Code-Review+2 vote the following files are no longer explicitly code-owner approved by Other Account:\n"
+ "+By removing the Code-Review+2 vote the following files are no longer explicitly code-owner approved by <GERRIT_ACCOUNT_2>:\n"
+ "@@ -12 +12 @@\n"
+ "-The listed files are still implicitly approved by Other Account.\n"
+ "+The listed files are still implicitly approved by <GERRIT_ACCOUNT_2>.\n",
"@@ -10 +10 @@\n"
+ "-By removing the Owners-Override+1 vote the code-owners submit requirement is no longer overridden by Change Owner\n"
+ "+By removing the Owners-Override+1 vote the code-owners submit requirement is no longer overridden by <GERRIT_ACCOUNT_1>\n",
"@@ -11 +11 @@\n"
+ "-By voting Any-Label+2 the code-owners submit requirement is overridden by Change Owner\n"
+ "+By voting Any-Label+2 the code-owners submit requirement is overridden by <GERRIT_ACCOUNT_1>\n");
}
@Test
public void fixAssigneeFooterIdent() throws Exception {
Change c = newChange();
String assigneeIdentToFix = getAccountIdentToFix(changeOwner.getAccount());
RevCommit invalidUpdateCommit =
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, "Assignee added", "Assignee: " + assigneeIdentToFix),
getAuthorIdent(changeOwner.getAccount()));
ChangeUpdate changeAssigneeUpdate = newUpdate(c, changeOwner);
changeAssigneeUpdate.setAssignee(otherUserId);
changeAssigneeUpdate.commit();
ChangeUpdate removeAssigneeUpdate = newUpdate(c, changeOwner);
removeAssigneeUpdate.removeAssignee();
removeAssigneeUpdate.commit();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
int invalidCommitIndex = commitsBeforeRewrite.indexOf(invalidUpdateCommit);
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(notesBeforeRewrite.getPastAssignees())
.containsExactly(changeOwner.getAccountId(), otherUser.getAccountId());
assertThat(notesBeforeRewrite.getChange().getAssignee()).isNull();
assertThat(notesAfterRewrite.getPastAssignees())
.containsExactly(changeOwner.getAccountId(), otherUser.getAccountId());
assertThat(notesAfterRewrite.getChange().getAssignee()).isNull();
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(
commitsBeforeRewrite, commitsAfterRewrite, ImmutableList.of(invalidCommitIndex));
RevCommit fixedUpdateCommit = commitsAfterRewrite.get(invalidCommitIndex);
assertThat(invalidUpdateCommit.getAuthorIdent()).isEqualTo(fixedUpdateCommit.getAuthorIdent());
assertThat(invalidUpdateCommit.getCommitterIdent())
.isEqualTo(fixedUpdateCommit.getCommitterIdent());
assertThat(invalidUpdateCommit.getFullMessage())
.isNotEqualTo(fixedUpdateCommit.getFullMessage());
assertThat(fixedUpdateCommit.getFullMessage()).doesNotContain(changeOwner.getName());
assertThat(invalidUpdateCommit.getFullMessage()).contains(assigneeIdentToFix);
String expectedFixedIdent = getValidIdentAsString(changeOwner.getAccount());
assertThat(fixedUpdateCommit.getFullMessage()).contains(expectedFixedIdent);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -9 +9 @@\n"
+ "-Assignee: Change Owner <1@gerrit>\n"
+ "+Assignee: Gerrit User 1 <1@gerrit>\n");
}
@Test
public void fixAssigneeChangeMessage() throws Exception {
Change c = newChange();
ImmutableList<RevCommit> commitsToFix =
new ImmutableList.Builder<RevCommit>()
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
"Assignee added: " + changeOwner.getNameEmail(),
"Assignee: " + getValidIdentAsString(changeOwner.getAccount())),
getAuthorIdent(changeOwner.getAccount())))
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
String.format(
"Assignee changed from: %s to: %s",
changeOwner.getNameEmail(), otherUser.getNameEmail()),
"Assignee: " + getValidIdentAsString(otherUser.getAccount())),
getAuthorIdent(changeOwner.getAccount())))
.add(
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c, "Assignee deleted: " + otherUser.getNameEmail(), "Assignee:"),
getAuthorIdent(changeOwner.getAccount())))
.build();
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
ImmutableList<Integer> invalidCommits =
commitsToFix.stream()
.map(commit -> commitsBeforeRewrite.indexOf(commit))
.collect(toImmutableList());
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(notesBeforeRewrite.getPastAssignees())
.containsExactly(changeOwner.getAccountId(), otherUser.getAccountId());
assertThat(notesBeforeRewrite.getChange().getAssignee()).isNull();
assertThat(changeMessages(notesBeforeRewrite))
.containsExactly(
"Assignee added: Change Owner <change@owner.com>",
"Assignee changed from: Change Owner <change@owner.com> to: Other Account <other@account.com>",
"Assignee deleted: Other Account <other@account.com>");
assertThat(notesAfterRewrite.getPastAssignees())
.containsExactly(changeOwner.getAccountId(), otherUser.getAccountId());
assertThat(notesAfterRewrite.getChange().getAssignee()).isNull();
assertThat(changeMessages(notesAfterRewrite))
.containsExactly(
"Assignee added: " + AccountTemplateUtil.getAccountTemplate(changeOwner.getAccountId()),
String.format(
"Assignee changed from: %s to: %s",
AccountTemplateUtil.getAccountTemplate(changeOwner.getAccountId()),
AccountTemplateUtil.getAccountTemplate(otherUser.getAccountId())),
"Assignee deleted: "
+ AccountTemplateUtil.getAccountTemplate(otherUser.getAccountId()));
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(commitsBeforeRewrite, commitsAfterRewrite, invalidCommits);
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n"
+ "-Assignee added: Change Owner <change@owner.com>\n"
+ "+Assignee added: <GERRIT_ACCOUNT_1>\n",
"@@ -6 +6 @@\n"
+ "-Assignee changed from: Change Owner <change@owner.com> to: Other Account <other@account.com>\n"
+ "+Assignee changed from: <GERRIT_ACCOUNT_1> to: <GERRIT_ACCOUNT_2>\n",
"@@ -6 +6 @@\n"
+ "-Assignee deleted: Other Account <other@account.com>\n"
+ "+Assignee deleted: <GERRIT_ACCOUNT_2>\n"
// Both empty value and space are parsed as deleted assignee anyway.
+ "@@ -9 +9 @@\n"
+ "-Assignee:\n"
+ "+Assignee: \n");
}
@Test
public void fixAssigneeChangeMessageNoAssigneeFooter() throws Exception {
Change c = newChange();
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, "Assignee added: " + changeOwner.getName()),
getAuthorIdent(changeOwner.getAccount()));
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
String.format(
"Assignee changed from: %s to: %s", changeOwner.getName(), otherUser.getName())),
getAuthorIdent(otherUser.getAccount()));
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, "Assignee deleted: " + otherUser.getName()),
getAuthorIdent(changeOwner.getAccount()));
Account reviewer =
Account.builder(Account.id(3), TimeUtil.nowTs())
.setFullName("Reviewer User")
.setPreferredEmail("reviewer@account.com")
.build();
accountCache.put(reviewer);
// Even though account is present in the cache, it won't be used because it does not appear in
// the history of this change.
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, "Assignee added: " + reviewer.getName()),
getAuthorIdent(changeOwner.getAccount()));
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(c, "Assignee deleted: Gerrit Account"),
getAuthorIdent(changeOwner.getAccount()));
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff)
.containsExactly(
"@@ -6 +6 @@\n"
+ "-Assignee added: Change Owner\n"
+ "+Assignee added: <GERRIT_ACCOUNT_1>\n",
"@@ -6 +6 @@\n"
+ "-Assignee changed from: Change Owner to: Other Account\n"
+ "+Assignee changed from: <GERRIT_ACCOUNT_1> to: <GERRIT_ACCOUNT_2>\n",
"@@ -6 +6 @@\n"
+ "-Assignee deleted: Other Account\n"
+ "+Assignee deleted: <GERRIT_ACCOUNT_2>\n",
"@@ -6 +6 @@\n"
+ "-Assignee added: Reviewer User\n"
+ "+Assignee added: Gerrit Account\n");
}
@Test
public void singleRunFixesAll() throws Exception {
Change c = newChange();
Timestamp when = TimeUtil.nowTs();
String assigneeIdentToFix = getAccountIdentToFix(otherUser.getAccount());
PersonIdent authorIdentToFix =
new PersonIdent(
changeOwner.getName(),
changeNoteUtil.getAccountIdAsEmailAddress(changeOwner.getAccountId()),
when,
serverIdent.getTimeZone());
RevCommit invalidUpdateCommit =
writeUpdate(
RefNames.changeMetaRef(c.getId()),
getChangeUpdateBody(
c,
"Assignee added: Other Account <other@account.com>",
"Assignee: " + assigneeIdentToFix),
authorIdentToFix);
Ref metaRefBeforeRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
ImmutableList<RevCommit> commitsBeforeRewrite = logMetaRef(repo, metaRefBeforeRewrite);
int invalidCommitIndex = commitsBeforeRewrite.indexOf(invalidUpdateCommit);
ChangeNotes notesBeforeRewrite = newNotes(c);
RunOptions options = new RunOptions();
options.dryRun = false;
BackfillResult result = rewriter.backfillProject(project, repo, options);
assertThat(result.fixedRefDiff.keySet()).containsExactly(RefNames.changeMetaRef(c.getId()));
ChangeNotes notesAfterRewrite = newNotes(c);
assertThat(notesBeforeRewrite.getChange().getAssignee()).isEqualTo(otherUserId);
assertThat(notesAfterRewrite.getChange().getAssignee()).isEqualTo(otherUserId);
Ref metaRefAfterRewrite = repo.exactRef(RefNames.changeMetaRef(c.getId()));
assertThat(metaRefAfterRewrite.getObjectId()).isNotEqualTo(metaRefBeforeRewrite.getObjectId());
ImmutableList<RevCommit> commitsAfterRewrite = logMetaRef(repo, metaRefAfterRewrite);
assertValidCommits(
commitsBeforeRewrite, commitsAfterRewrite, ImmutableList.of(invalidCommitIndex));
RevCommit fixedUpdateCommit = commitsAfterRewrite.get(invalidCommitIndex);
assertThat(invalidUpdateCommit.getAuthorIdent())
.isNotEqualTo(fixedUpdateCommit.getAuthorIdent());
assertThat(invalidUpdateCommit.getFullMessage()).contains(otherUser.getName());
assertThat(fixedUpdateCommit.getFullMessage()).doesNotContain(changeOwner.getName());
assertThat(fixedUpdateCommit.getFullMessage()).doesNotContain(otherUser.getName());
List<String> commitHistoryDiff = result.fixedRefDiff.get(RefNames.changeMetaRef(c.getId()));
assertThat(commitHistoryDiff).hasSize(1);
assertThat(commitHistoryDiff.get(0)).contains("-author Change Owner <1@gerrit>");
assertThat(commitHistoryDiff.get(0)).contains("+author Gerrit User 1 <1@gerrit>");
assertThat(commitHistoryDiff.get(0))
.contains(
"@@ -6 +6 @@\n"
+ "-Assignee added: Other Account <other@account.com>\n"
+ "+Assignee added: <GERRIT_ACCOUNT_2>\n"
+ "@@ -9 +9 @@\n"
+ "-Assignee: Other Account <2@gerrit>\n"
+ "+Assignee: Gerrit User 2 <2@gerrit>");
}
private RevCommit writeUpdate(String metaRef, String body, PersonIdent author) throws Exception {
return tr.branch(metaRef).commit().message(body).author(author).committer(serverIdent).create();
}
private String getChangeUpdateBody(Change change, String changeMessage, String... footers) {
StringBuilder commitBody = new StringBuilder();
commitBody.append("Update patch set ").append(change.currentPatchSetId().get());
commitBody.append("\n\n");
if (changeMessage != null) {
commitBody.append(changeMessage);
commitBody.append("\n\n");
}
commitBody.append("Patch-set: " + change.currentPatchSetId().get());
commitBody.append("\n");
for (String footer : footers) {
commitBody.append(footer);
commitBody.append("\n");
}
return commitBody.toString();
}
private ImmutableList<RevCommit> logMetaRef(Repository repo, Ref metaRef) throws Exception {
try (RevWalk rw = new RevWalk(repo)) {
rw.sort(RevSort.TOPO);
rw.sort(RevSort.REVERSE);
if (metaRef == null) {
return ImmutableList.of();
}
rw.markStart(rw.parseCommit(metaRef.getObjectId()));
return ImmutableList.copyOf(rw);
}
}
private void assertValidCommits(
ImmutableList<RevCommit> commitsBeforeRewrite,
ImmutableList<RevCommit> commitsAfterRewrite,
ImmutableList<Integer> invalidCommits) {
ImmutableList<RevCommit> validCommitsBeforeRewrite =
IntStream.range(0, commitsBeforeRewrite.size())
.filter(i -> !invalidCommits.contains(i))
.mapToObj(commitsBeforeRewrite::get)
.collect(toImmutableList());
ImmutableList<RevCommit> validCommitsAfterRewrite =
IntStream.range(0, commitsAfterRewrite.size())
.filter(i -> !invalidCommits.contains(i))
.mapToObj(commitsAfterRewrite::get)
.collect(toImmutableList());
assertThat(validCommitsBeforeRewrite).hasSize(validCommitsAfterRewrite.size());
for (int i = 0; i < validCommitsAfterRewrite.size(); i++) {
RevCommit actual = validCommitsAfterRewrite.get(i);
RevCommit expected = validCommitsBeforeRewrite.get(i);
assertThat(actual.getAuthorIdent()).isEqualTo(expected.getAuthorIdent());
assertThat(actual.getCommitterIdent()).isEqualTo(expected.getCommitterIdent());
assertThat(actual.getFullMessage()).isEqualTo(expected.getFullMessage());
}
}
private String getAccountIdentToFix(Account account) {
return String.format("%s <%s>", account.getName(), account.id().get() + "@" + serverId);
}
private String getValidIdentAsString(Account account) {
return String.format(
"%s <%s>",
ChangeNoteUtil.getAccountIdAsUsername(account.id()), account.id().get() + "@" + serverId);
}
private ImmutableList<String> changeMessages(ChangeNotes changeNotes) {
return changeNotes.getChangeMessages().stream()
.map(ChangeMessage::getMessage)
.collect(toImmutableList());
}
private PersonIdent getAuthorIdent(Account account) {
Timestamp when = TimeUtil.nowTs();
return changeNoteUtil.newAccountIdIdent(account.id(), when, serverIdent);
}
}
|
package org.firstinspires.ftc.teamcode.robot;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import org.firstinspires.ftc.teamcode.buttons.BUTTON_TYPE;
import org.firstinspires.ftc.teamcode.buttons.ButtonHandler;
import org.firstinspires.ftc.teamcode.buttons.PAD_BUTTON;
import org.firstinspires.ftc.teamcode.config.BOT;
import org.firstinspires.ftc.teamcode.driveto.AutoDriver;
import org.firstinspires.ftc.teamcode.robot.common.Common;
import org.firstinspires.ftc.teamcode.sensors.led_matrix.driver.BLINKING_MODE;
import org.firstinspires.ftc.teamcode.utils.RateLimit;
@Disabled
@com.qualcomm.robotcore.eventloop.opmode.TeleOp(name = "TeleOp - Test", group = "Test")
public class TestTeleOp extends OpMode {
// Devices and subsystems
private Robot robot = null;
private Common common = null;
private ButtonHandler buttons;
private AutoDriver driver = new AutoDriver();
private byte[] FUCK = {
(byte) 0b11111111, (byte) 0b00011000,
(byte) 0b10000001, (byte) 0b00011000,
(byte) 0b10000001, (byte) 0b00011000,
(byte) 0b10000001, (byte) 0b11111111,
(byte) 0b10000001, (byte) 0b11111111,
(byte) 0b10000001, (byte) 0b00011000,
(byte) 0b10000001, (byte) 0b00011000,
(byte) 0b11111111, (byte) 0b00011000
};
@Override
public void init() {
// Placate drivers
telemetry.addData(">", "NOT READY");
telemetry.update();
// Init the common tasks elements
robot = new Robot(hardwareMap, telemetry);
common = robot.common;
robot.wheels.setTeleop(true);
// Check robot
if (robot.bot != BOT.TEST) {
telemetry.log().add("Opmode not compatible with bot " + robot.bot);
requestOpModeStop();
return;
}
// make the brightness bearable
robot.matrix.setBrightness(16);
robot.matrix.setBlinking(BLINKING_MODE.OFF);
robot.matrix.setDisplayBuffer(FUCK);
robot.matrix.write();
// Wait for the game to begin
telemetry.addData(">", "Ready for game start");
telemetry.update();
}
@Override
public void init_loop() {
}
@Override
public void start() {
}
@Override
public void loop() {
}
public void stop() {
robot.matrix.reset();
}
}
|
package net.lightoze.jooq.postgresql.json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import org.jooq.JSONB;
import java.io.IOException;
public class JacksonJsonbConverter<T> extends AbstractJacksonConverter<JSONB, T, T> {
public JacksonJsonbConverter() {
}
public JacksonJsonbConverter(JavaType userType, JavaType elementType) {
super(userType, elementType);
}
@Override
public T from(JSONB json) {
if (json == null || json.data().equals("null")) {
return getNull();
} else {
try {
return getObjectReader().readValue(json.data());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public JSONB to(T value) {
if (value == null || isNull(value)) {
return null;
} else {
try {
return JSONB.valueOf(getObjectWriter().writeValueAsString(value));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
@Override
public Class<JSONB> fromType() {
return JSONB.class;
}
}
|
package org.bavand.sharedElement.ui.Splash;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.widget.ImageView;
import org.bavand.R;
import org.bavand.sharedElement.ui.login.LoginActivity;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityOptionsCompat;
public class SplashActivity extends AppCompatActivity {
/*
make a thread to end splash activity after 5 sec
*/
private ImageView imageViewLogo;
Thread splash = new Thread() {
@Override
public void run() {
try {
Looper.prepare();
sleep(5000);
runOnUiThread(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
/*
make a scene transition for image view and add transition name. you must enter transition name for image view in xml
file.
*/
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(SplashActivity.this, imageViewLogo, "logo");
startActivity(i, optionsCompat.toBundle());
getWindow().setExitTransition(null);
}
});
} catch (Exception e) {
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
LoginActivity.changeStatusBarColor(this);
imageViewLogo = findViewById(R.id.imageViewLogo);
splash.start();
}
/*
finish activity after transition commit. if you finish activity just after
strart activity the activity will blinking.
*/
@Override
protected void onStop() {
super.onStop();
finish();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.