text
stringlengths 7
1.01M
|
|---|
/*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*******************************************************************************/
package com.sproutlife.model.seed.patterns;
import java.awt.Point;
import com.sproutlife.model.seed.BitPattern;
import com.sproutlife.model.seed.SeedSproutPattern;
public class Square2RpPattern extends SeedSproutPattern {
public Square2RpPattern() {
this.seedPattern = new BitPattern(new int[][]
{{1,1},
{1,1}},
true);
this.sproutPattern = new BitPattern(new int[][]
{{0,1,1},
{1,1,0},
{0,1,0}},
true);
this.sproutOffset = new Point(-1,0);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.test.sql.parser.parameterized.asserts.statement.distsql.rdl.alter.impl;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.sharding.distsql.parser.statement.AlterShardingBroadcastTableRulesStatement;
import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.SQLCaseAssertContext;
import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.statement.distsql.rdl.alter.AlterShardingBroadcastTableRulesStatementTestCase;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
/**
* Alter sharding broadcast table rule statement assert.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class AlterShardingBroadcastTableRulesStatementAssert {
/**
* Assert alter sharding broadcast table rule statement is correct with expected parser result.
*
* @param assertContext assert context
* @param actual actual alter sharding broadcast table rule statement
* @param expected expected alter sharding broadcast table rule statement test case
*/
public static void assertIs(final SQLCaseAssertContext assertContext, final AlterShardingBroadcastTableRulesStatement actual, final AlterShardingBroadcastTableRulesStatementTestCase expected) {
if (null == expected) {
assertNull(assertContext.getText("Actual should not exist."), actual);
} else {
assertNotNull(assertContext.getText("Actual should exist."), actual);
assertThat(assertContext.getText("sharding broadcast table rule assertion error : "), actual.getTables(), is(expected.getTables()));
}
}
}
|
/*
* Copyright (C) 2013 DroidDriver committers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appium.uiautomator2.utils;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state.
*/
public final class Preconditions {
private Preconditions() {}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
}
|
package net.rfs.smartadmin.module.business.notice;
import net.rfs.smartadmin.common.anno.NoValidPrivilege;
import net.rfs.smartadmin.common.domain.PageParamDTO;
import net.rfs.smartadmin.common.domain.PageResultDTO;
import net.rfs.smartadmin.common.domain.ResponseDTO;
import net.rfs.smartadmin.constant.SwaggerTagConst;
import net.rfs.smartadmin.module.business.notice.domain.dto.*;
import net.rfs.smartadmin.util.SmartRequestTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.rfs.smartadmin.module.business.notice.domain.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* [ ]
*
* @author yandanyang
* @version 1.0
* @company 1024lab.net
* @copyright (c) 2019 1024lab.netInc. All rights reserved.
* @date 2019-07-11 16:19:48
* @since JDK1.8
*/
@RestController
@Api(tags = {SwaggerTagConst.Admin.MANAGER_NOTICE})
public class NoticeController {
@Autowired
private NoticeService noticeService;
@ApiOperation(value = "分页查询全部消息", notes = "@author yandanyang")
@PostMapping("/notice/page/query")
@NoValidPrivilege
public ResponseDTO<PageResultDTO<NoticeVO>> queryByPage(@RequestBody NoticeQueryDTO queryDTO) {
return noticeService.queryByPage(queryDTO);
}
@ApiOperation(value = "获取已收取的所有消息", notes = "@author yandanyang")
@PostMapping("/notice/receive/page/query")
@NoValidPrivilege
public ResponseDTO<PageResultDTO<NoticeReceiveDTO>> queryReceiveByPage(@RequestBody NoticeReceiveQueryDTO queryDTO) {
return noticeService.queryReceiveByPage(queryDTO, SmartRequestTokenUtil.getRequestUser());
}
@ApiOperation(value = "分页查询未读消息", notes = "@author yandanyang")
@PostMapping("/notice/unread/page/query")
@NoValidPrivilege
public ResponseDTO<PageResultDTO<NoticeVO>> queryUnreadByPage(@RequestBody PageParamDTO queryDTO) {
return noticeService.queryUnreadByPage(queryDTO, SmartRequestTokenUtil.getRequestUser());
}
@ApiOperation(value = "添加", notes = "@author yandanyang")
@PostMapping("/notice/add")
@NoValidPrivilege
public ResponseDTO<String> add(@RequestBody @Valid NoticeAddDTO addTO) {
return noticeService.add(addTO, SmartRequestTokenUtil.getRequestUser());
}
@ApiOperation(value = "修改", notes = "@author yandanyang")
@PostMapping("/notice/update")
@NoValidPrivilege
public ResponseDTO<String> update(@RequestBody @Valid NoticeUpdateDTO updateDTO) {
return noticeService.update(updateDTO);
}
@ApiOperation(value = "删除", notes = "@author yandanyang")
@GetMapping("/notice/delete/{id}")
@NoValidPrivilege
public ResponseDTO<String> delete(@PathVariable("id") Long id) {
return noticeService.delete(id);
}
@ApiOperation(value = "详情", notes = "@author yandanyang")
@GetMapping("/notice/detail/{id}")
@NoValidPrivilege
public ResponseDTO<NoticeDetailVO> detail(@PathVariable("id") Long id) {
return noticeService.detail(id);
}
@ApiOperation(value = "发送", notes = "@author yandanyang")
@GetMapping("/notice/send/{id}")
@NoValidPrivilege
public ResponseDTO<NoticeDetailVO> send(@PathVariable("id") Long id) {
return noticeService.send(id, SmartRequestTokenUtil.getRequestUser());
}
@ApiOperation(value = "读取消息", notes = "@author yandanyang")
@GetMapping("/notice/read/{id}")
@NoValidPrivilege
public ResponseDTO<NoticeDetailVO> read(@PathVariable("id") Long id) {
return noticeService.read(id, SmartRequestTokenUtil.getRequestUser());
}
}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.inject.internal;
import org.opensearch.common.inject.Binder;
import org.opensearch.common.inject.Key;
import org.opensearch.common.inject.binder.AnnotatedElementBuilder;
import java.lang.annotation.Annotation;
import java.util.Objects;
/**
* For private binder's expose() method.
*
* @opensearch.internal
*/
public class ExposureBuilder<T> implements AnnotatedElementBuilder {
private final Binder binder;
private final Object source;
private Key<T> key;
public ExposureBuilder(Binder binder, Object source, Key<T> key) {
this.binder = binder;
this.source = source;
this.key = key;
}
protected void checkNotAnnotated() {
if (key.getAnnotationType() != null) {
binder.addError(AbstractBindingBuilder.ANNOTATION_ALREADY_SPECIFIED);
}
}
@Override
public void annotatedWith(Class<? extends Annotation> annotationType) {
Objects.requireNonNull(annotationType, "annotationType");
checkNotAnnotated();
key = Key.get(key.getTypeLiteral(), annotationType);
}
@Override
public void annotatedWith(Annotation annotation) {
Objects.requireNonNull(annotation, "annotation");
checkNotAnnotated();
key = Key.get(key.getTypeLiteral(), annotation);
}
public Key<?> getKey() {
return key;
}
public Object getSource() {
return source;
}
@Override
public String toString() {
return "AnnotatedElementBuilder";
}
}
|
package com.facebook.react.cxxbridge;
import android.os.Bundle;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import java.lang.reflect.Array;
import java.util.AbstractList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Arguments {
private static Object makeNativeObject(Object object) {
if (object == null) {
return null;
}
if ((object instanceof Float) || (object instanceof Long) || (object instanceof Byte) || (object instanceof Short)) {
return new Double(((Number) object).doubleValue());
}
if (object.getClass().isArray()) {
return makeNativeArray(object);
}
if (object instanceof List) {
return makeNativeArray((List) object);
}
if (object instanceof Map) {
return makeNativeMap((Map) object);
}
if (object instanceof Bundle) {
return makeNativeMap((Bundle) object);
}
return object;
}
public static WritableNativeArray makeNativeArray(List objects) {
WritableNativeArray nativeArray = new WritableNativeArray();
if (objects != null) {
for (Object elem : objects) {
Object elem2 = makeNativeObject(elem2);
if (elem2 == null) {
nativeArray.pushNull();
} else if (elem2 instanceof Boolean) {
nativeArray.pushBoolean(((Boolean) elem2).booleanValue());
} else if (elem2 instanceof Integer) {
nativeArray.pushInt(((Integer) elem2).intValue());
} else if (elem2 instanceof Double) {
nativeArray.pushDouble(((Double) elem2).doubleValue());
} else if (elem2 instanceof String) {
nativeArray.pushString((String) elem2);
} else if (elem2 instanceof WritableNativeArray) {
nativeArray.pushArray((WritableNativeArray) elem2);
} else if (elem2 instanceof WritableNativeMap) {
nativeArray.pushMap((WritableNativeMap) elem2);
} else {
throw new IllegalArgumentException("Could not convert " + elem2.getClass());
}
}
}
return nativeArray;
}
public static <T> WritableNativeArray makeNativeArray(final Object objects) {
if (objects == null) {
return new WritableNativeArray();
}
return makeNativeArray(new AbstractList() {
public int size() {
return Array.getLength(objects);
}
public Object get(int index) {
return Array.get(objects, index);
}
});
}
private static void addEntry(WritableNativeMap nativeMap, String key, Object value) {
value = makeNativeObject(value);
if (value == null) {
nativeMap.putNull(key);
} else if (value instanceof Boolean) {
nativeMap.putBoolean(key, ((Boolean) value).booleanValue());
} else if (value instanceof Integer) {
nativeMap.putInt(key, ((Integer) value).intValue());
} else if (value instanceof Number) {
nativeMap.putDouble(key, ((Number) value).doubleValue());
} else if (value instanceof String) {
nativeMap.putString(key, (String) value);
} else if (value instanceof WritableNativeArray) {
nativeMap.putArray(key, (WritableNativeArray) value);
} else if (value instanceof WritableNativeMap) {
nativeMap.putMap(key, (WritableNativeMap) value);
} else {
throw new IllegalArgumentException("Could not convert " + value.getClass());
}
}
public static WritableNativeMap makeNativeMap(Map<String, Object> objects) {
WritableNativeMap nativeMap = new WritableNativeMap();
if (objects != null) {
for (Entry<String, Object> entry : objects.entrySet()) {
addEntry(nativeMap, (String) entry.getKey(), entry.getValue());
}
}
return nativeMap;
}
public static WritableNativeMap makeNativeMap(Bundle bundle) {
WritableNativeMap nativeMap = new WritableNativeMap();
if (bundle != null) {
for (String key : bundle.keySet()) {
addEntry(nativeMap, key, bundle.get(key));
}
}
return nativeMap;
}
}
|
package org.simple.binary.system.digit;
import org.simple.binary.system.value.BinaryValue;
public interface UnsignedDigit<VALUE extends BinaryValue>
extends MultipleDigit<VALUE> {
}
|
/*
* 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.servicemodel.channels;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.servicemodel.channels.Message;
import system.xml.xpath.XPathNavigator;
import system.xml.XmlSpace;
import system.io.Stream;
import system.IDisposable;
import system.IDisposableImplementation;
/**
* The base .NET class managing System.ServiceModel.Channels.MessageBuffer, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.ServiceModel.Channels.MessageBuffer" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.ServiceModel.Channels.MessageBuffer</a>
*/
public class MessageBuffer extends NetObject implements system.IDisposable, AutoCloseable {
/**
* Fully assembly qualified name: System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
*/
public static final String assemblyFullName = "System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
/**
* Assembly name: System.ServiceModel
*/
public static final String assemblyShortName = "System.ServiceModel";
/**
* Qualified class name: System.ServiceModel.Channels.MessageBuffer
*/
public static final String className = "System.ServiceModel.Channels.MessageBuffer";
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);
}
}
/**
* Internal constructor. Use with caution
*/
public MessageBuffer(java.lang.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 java.lang.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 MessageBuffer}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link MessageBuffer} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static MessageBuffer cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new MessageBuffer(from.getJCOInstance());
}
// Constructors section
public MessageBuffer() throws Throwable {
}
// Methods section
public Message CreateMessage() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objCreateMessage = (JCObject)classInstance.Invoke("CreateMessage");
return new Message(objCreateMessage);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XPathNavigator CreateNavigator() throws Throwable, system.ArgumentException, system.IndexOutOfRangeException, system.MulticastNotSupportedException, system.ArgumentNullException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.configuration.ConfigurationErrorsException, system.OverflowException, system.security.SecurityException, system.OutOfMemoryException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objCreateNavigator = (JCObject)classInstance.Invoke("CreateNavigator");
return new XPathNavigator(objCreateNavigator);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XPathNavigator CreateNavigator(int nodeQuota) throws Throwable, system.ArgumentException, system.IndexOutOfRangeException, system.MulticastNotSupportedException, system.ArgumentNullException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.configuration.ConfigurationErrorsException, system.OverflowException, system.security.SecurityException, system.OutOfMemoryException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objCreateNavigator = (JCObject)classInstance.Invoke("CreateNavigator", nodeQuota);
return new XPathNavigator(objCreateNavigator);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XPathNavigator CreateNavigator(int nodeQuota, XmlSpace space) throws Throwable, system.ArgumentException, system.IndexOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.NotSupportedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.FormatException, system.OverflowException, system.OutOfMemoryException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objCreateNavigator = (JCObject)classInstance.Invoke("CreateNavigator", nodeQuota, space == null ? null : space.getJCOInstance());
return new XPathNavigator(objCreateNavigator);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public XPathNavigator CreateNavigator(XmlSpace space) throws Throwable, system.ArgumentException, system.IndexOutOfRangeException, system.MulticastNotSupportedException, system.ArgumentNullException, system.InvalidOperationException, system.MissingMethodException, system.reflection.TargetInvocationException, system.NotImplementedException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.configuration.ConfigurationErrorsException, system.OverflowException, system.security.SecurityException, system.OutOfMemoryException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objCreateNavigator = (JCObject)classInstance.Invoke("CreateNavigator", space == null ? null : space.getJCOInstance());
return new XPathNavigator(objCreateNavigator);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void Close() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Close");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public void WriteMessage(Stream stream) throws Throwable, system.ArgumentException, system.IndexOutOfRangeException, system.ArgumentNullException, system.ArgumentOutOfRangeException, system.FormatException, system.NotImplementedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.OverflowException, system.OutOfMemoryException, system.xml.XmlException, system.NotSupportedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("WriteMessage", stream == null ? null : stream.getJCOInstance());
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* @deprecated Not for public use because the method is implemented in .NET with an explicit interface.
* Use the static ToIDisposable method available in IDisposable to obtain an object with an invocable method
*/
@Deprecated
public void Dispose() throws Throwable {
throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIDisposable to obtain the full interface.");
}
public void close() throws Exception {
try {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
classInstance.Invoke("Dispose");
}
catch (JCNativeException jcne) {
throw translateException(jcne);
}
} catch (Throwable t) {
throw new Exception(t);
}
}
// Properties section
public int getBufferSize() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (int)classInstance.Get("BufferSize");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public java.lang.String getMessageContentType() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
return (java.lang.String)classInstance.Get("MessageContentType");
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.runners.flink.examples.streaming;
import java.io.IOException;
import org.apache.beam.runners.flink.FlinkRunner;
import org.apache.beam.runners.flink.translation.wrappers.streaming.io.UnboundedSocketSource;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Aggregator;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Sum;
import org.apache.beam.sdk.transforms.windowing.AfterWatermark;
import org.apache.beam.sdk.transforms.windowing.SlidingWindows;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* To run the example, first open a socket on a terminal by executing the command:
* <ul>
* <li><code>nc -lk 9999</code>
* </ul>
* and then launch the example. Now whatever you type in the terminal is going to be
* the input to the program.
* */
public class WindowedWordCount {
private static final Logger LOG = LoggerFactory.getLogger(WindowedWordCount.class);
static final long WINDOW_SIZE = 10; // Default window duration in seconds
static final long SLIDE_SIZE = 5; // Default window slide in seconds
static class FormatAsStringFn extends DoFn<KV<String, Long>, String> {
@ProcessElement
public void processElement(ProcessContext c) {
String row = c.element().getKey() + " - " + c.element().getValue() + " @ "
+ c.timestamp().toString();
c.output(row);
}
}
static class ExtractWordsFn extends DoFn<String, String> {
private final Aggregator<Long, Long> emptyLines =
createAggregator("emptyLines", Sum.ofLongs());
@ProcessElement
public void processElement(ProcessContext c) {
if (c.element().trim().isEmpty()) {
emptyLines.addValue(1L);
}
// Split the line into words.
String[] words = c.element().split("[^a-zA-Z']+");
// Output each word encountered into the output PCollection.
for (String word : words) {
if (!word.isEmpty()) {
c.output(word);
}
}
}
}
/**
* Pipeline options.
*/
public interface StreamingWordCountOptions
extends org.apache.beam.runners.flink.examples.WordCount.Options {
@Description("Sliding window duration, in seconds")
@Default.Long(WINDOW_SIZE)
Long getWindowSize();
void setWindowSize(Long value);
@Description("Window slide, in seconds")
@Default.Long(SLIDE_SIZE)
Long getSlide();
void setSlide(Long value);
}
public static void main(String[] args) throws IOException {
StreamingWordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
.as(StreamingWordCountOptions.class);
options.setStreaming(true);
options.setWindowSize(10L);
options.setSlide(5L);
options.setCheckpointingInterval(1000L);
options.setNumberOfExecutionRetries(5);
options.setExecutionRetryDelay(3000L);
options.setRunner(FlinkRunner.class);
LOG.info("Windpwed WordCount with Sliding Windows of " + options.getWindowSize()
+ " sec. and a slide of " + options.getSlide());
Pipeline pipeline = Pipeline.create(options);
PCollection<String> words = pipeline
.apply("StreamingWordCount",
Read.from(new UnboundedSocketSource<>("localhost", 9999, '\n', 3)))
.apply(ParDo.of(new ExtractWordsFn()))
.apply(Window.<String>into(SlidingWindows.of(
Duration.standardSeconds(options.getWindowSize()))
.every(Duration.standardSeconds(options.getSlide())))
.triggering(AfterWatermark.pastEndOfWindow()).withAllowedLateness(Duration.ZERO)
.discardingFiredPanes());
PCollection<KV<String, Long>> wordCounts =
words.apply(Count.<String>perElement());
wordCounts.apply(ParDo.of(new FormatAsStringFn()))
.apply(TextIO.Write.to("./outputWordCount.txt"));
pipeline.run();
}
}
|
package com.walmartlabs.concord.agentoperator.processqueue;
/*-
* *****
* Concord
* -----
* Copyright (C) 2017 - 2019 Walmart Inc.
* -----
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =====
*/
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProcessQueueClient {
private static final TypeReference<List<ProcessQueueEntry>> LIST_OF_PROCESS_QUEUE_ENTRIES = new TypeReference<List<ProcessQueueEntry>>() {
};
private final String baseUrl;
private final String apiToken;
private final OkHttpClient client;
private final ObjectMapper objectMapper;
public ProcessQueueClient(String baseUrl, String apiToken) {
this.baseUrl = baseUrl;
this.apiToken = apiToken;
this.client = initClient();
this.objectMapper = new ObjectMapper();
}
public List<ProcessQueueEntry> query(String processStatus, int limit, String flavor) throws IOException {
String queryUrl = baseUrl + "/api/v2/process/requirements?status=" + processStatus + "&limit=" + limit + "&startAt.len=";
if (flavor != null) {
queryUrl = queryUrl + "&requirements.agent.flavor.eq=" + flavor;
}
Request req = new Request.Builder()
.url(queryUrl)
.header("Authorization", apiToken)
.addHeader("User-Agent", "k8s-agent-operator")
.build();
Call call = client.newCall(req);
try (Response resp = call.execute()) {
if (!resp.isSuccessful()) {
throw new IOException("Error while fetching the process queue data: " + resp.code());
}
ResponseBody body = resp.body();
if (body == null) {
throw new IOException("Error while fetching the process queue data: empty response");
}
return objectMapper.readValue(body.byteStream(), LIST_OF_PROCESS_QUEUE_ENTRIES);
}
}
private static OkHttpClient initClient() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier((hostname, session) -> true);
Map<String, String> cookieJar = new HashMap<>();
builder.addInterceptor(new AddCookiesInterceptor(cookieJar));
builder.addInterceptor(new ReceivedCookiesInterceptor(cookieJar));
return builder.build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static class AddCookiesInterceptor implements Interceptor {
private final Map<String, String> cookieJar;
private AddCookiesInterceptor(Map<String, String> cookieJar) {
this.cookieJar = cookieJar;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
for (Map.Entry<String, String> cookie : cookieJar.entrySet()) {
builder.addHeader("Cookie", cookie.getValue());
}
return chain.proceed(builder.build());
}
}
private static class ReceivedCookiesInterceptor implements Interceptor {
private static final String SESSION_COOKIE_NAME = "JSESSIONID";
private final Map<String, String> cookieJar;
private ReceivedCookiesInterceptor(Map<String, String> cookieJar) {
this.cookieJar = cookieJar;
}
@Override
public Response intercept(Chain chain) throws IOException {
Response resp = chain.proceed(chain.request());
List<String> cookies = resp.headers("Set-Cookie");
if (cookies.isEmpty()) {
return resp;
}
for (String cookie : cookies) {
if (cookie.startsWith(SESSION_COOKIE_NAME)) {
cookieJar.put(SESSION_COOKIE_NAME, cookie);
}
}
return resp;
}
}
}
|
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.amqp.rabbit.connection;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.AmqpIOException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.transaction.support.ResourceHolderSupport;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import com.rabbitmq.client.Channel;
/**
* Rabbit resource holder, wrapping a RabbitMQ Connection and Channel. RabbitTransactionManager binds instances of this
* class to the thread, for a given Rabbit ConnectionFactory.
*
* <p>
* Note: This is an SPI class, not intended to be used by applications.
*
* @author Mark Fisher
* @author Dave Syer
* @author Gary Russell
*
* @see RabbitTransactionManager
* @see RabbitTemplate
*/
public class RabbitResourceHolder extends ResourceHolderSupport {
private static final Log logger = LogFactory.getLog(RabbitResourceHolder.class);
private boolean frozen = false;
private final List<Connection> connections = new LinkedList<Connection>();
private final List<Channel> channels = new LinkedList<Channel>();
private final Map<Connection, List<Channel>> channelsPerConnection = new HashMap<Connection, List<Channel>>();
private final MultiValueMap<Channel, Long> deliveryTags = new LinkedMultiValueMap<Channel, Long>();
private boolean transactional;
private boolean releaseAfterCompletion = true;
/**
* Create a new RabbitResourceHolder that is open for resources to be added.
*/
public RabbitResourceHolder() {
}
/**
* @param channel a channel to add
*/
public RabbitResourceHolder(Channel channel, boolean releaseAfterCompletion) {
this();
addChannel(channel);
this.releaseAfterCompletion = releaseAfterCompletion;
}
public final boolean isFrozen() {
return this.frozen;
}
/**
* Whether the resources should be released after transaction completion.
* Default true. Listener containers set to false because the listener continues
* to use the channel.
*/
public boolean isReleaseAfterCompletion() {
return releaseAfterCompletion;
}
public final void addConnection(Connection connection) {
Assert.isTrue(!this.frozen, "Cannot add Connection because RabbitResourceHolder is frozen");
Assert.notNull(connection, "Connection must not be null");
if (!this.connections.contains(connection)) {
this.connections.add(connection);
}
}
public final void addChannel(Channel channel) {
addChannel(channel, null);
}
public final void addChannel(Channel channel, Connection connection) {
Assert.isTrue(!this.frozen, "Cannot add Channel because RabbitResourceHolder is frozen");
Assert.notNull(channel, "Channel must not be null");
if (!this.channels.contains(channel)) {
this.channels.add(channel);
if (connection != null) {
List<Channel> channels = this.channelsPerConnection.get(connection);
if (channels == null) {
channels = new LinkedList<Channel>();
this.channelsPerConnection.put(connection, channels);
}
channels.add(channel);
}
}
}
public boolean containsChannel(Channel channel) {
return this.channels.contains(channel);
}
public Connection getConnection() {
return (!this.connections.isEmpty() ? this.connections.get(0) : null);
}
public Connection getConnection(Class<? extends Connection> connectionType) {
return CollectionUtils.findValueOfType(this.connections, connectionType);
}
public Channel getChannel() {
return (!this.channels.isEmpty() ? this.channels.get(0) : null);
}
public void commitAll() throws AmqpException {
try {
for (Channel channel : this.channels) {
if (deliveryTags.containsKey(channel)) {
for (Long deliveryTag : deliveryTags.get(channel)) {
channel.basicAck(deliveryTag, false);
}
}
channel.txCommit();
}
} catch (IOException e) {
throw new AmqpException("failed to commit RabbitMQ transaction", e);
}
}
public void closeAll() {
for (Channel channel : this.channels) {
try {
if (channel != ConsumerChannelRegistry.getConsumerChannel()) {
channel.close();
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping close of consumer channel: " + channel.toString());
}
}
} catch (Throwable ex) {
logger.debug("Could not close synchronized Rabbit Channel after transaction", ex);
}
}
for (Connection con : this.connections) {
RabbitUtils.closeConnection(con);
}
this.connections.clear();
this.channels.clear();
this.channelsPerConnection.clear();
}
public void addDeliveryTag(Channel channel, long deliveryTag) {
this.deliveryTags.add(channel, deliveryTag);
}
public void rollbackAll() {
for (Channel channel : this.channels) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back messages to channel: " + channel);
}
RabbitUtils.rollbackIfNecessary(channel);
if (deliveryTags.containsKey(channel)) {
for (Long deliveryTag : deliveryTags.get(channel)) {
try {
channel.basicReject(deliveryTag, true);
} catch (IOException ex) {
throw new AmqpIOException(ex);
}
}
// Need to commit the reject (=nack)
RabbitUtils.commitIfNecessary(channel);
}
}
}
/**
* @return true if the channels in this holder are transactional
*/
public boolean isChannelTransactional() {
return this.transactional;
}
}
|
package org.springframework.boot.autoconfigure.data.tarantool;
import io.tarantool.driver.api.TarantoolClient;
import io.tarantool.driver.api.TarantoolResult;
import io.tarantool.driver.api.tuple.TarantoolTuple;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.tarantool.core.ReactiveTarantoolOperations;
import org.springframework.data.tarantool.core.ReactiveTarantoolTemplate;
import org.springframework.data.tarantool.core.TarantoolExceptionTranslator;
import org.springframework.data.tarantool.core.convert.TarantoolConverter;
import reactor.core.publisher.Flux;
/**
* {@link EnableAutoConfiguration Auto-configuration} for Spring Data's reactive Tarantool support.
* <p>
* Registers {@link ReactiveTarantoolTemplate} bean if no other bean of the same type is configured.
*
* @author Tatiana Blinova
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({TarantoolClient.class, ReactiveTarantoolTemplate.class, Flux.class})
@ConditionalOnBean(TarantoolClient.class)
@Import(TarantoolDataConfiguration.class)
@AutoConfigureAfter({TarantoolAutoConfiguration.class, TarantoolConversionAutoConfiguration.class})
public class TarantoolReactiveDataAutoConfiguration {
@Bean
@ConditionalOnMissingBean(ReactiveTarantoolOperations.class)
public ReactiveTarantoolTemplate reactiveTarantoolTemplate(TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> tarantoolClient,
TarantoolConverter tarantoolConverter,
TarantoolExceptionTranslator tarantoolExceptionTranslator) {
return new ReactiveTarantoolTemplate(tarantoolClient, tarantoolConverter, tarantoolExceptionTranslator);
}
}
|
package org.mns237.controller;
import java.util.List;
import org.mns237.service.SubscriberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.*;
import org.mns237.entity.Subscribers;
import org.mns237.dao.SubscribersRepository;
@RestController
@CrossOrigin(origins = "http://localhost:4200") // this is the link to the frontend
public class SubscribersController{
// standard constructors
@Autowired
private final SubscribersRepository subscribersRepository;
@Autowired
private final SubscriberService subscriberService;
public SubscribersController(SubscribersRepository subscribersRepository, SubscriberService subscriberService) {
this.subscribersRepository = subscribersRepository;
this.subscriberService = subscriberService;
}
// showing the list of users from the DB
@GetMapping("/admin/abonnement")
public List<Subscribers> getAllSubscribers(){
return subscriberService.getAllUsers();
}
// showing the user with id
@GetMapping("/admin/abonnement/{id}")
public Subscribers getUserById(@PathVariable("id") long id){
return subscriberService.getUserById(id);
}
// save subscribers
@PostMapping("/newsletter")
public void addSubscribers(@RequestBody Subscribers subscribers) {
subscribersRepository.save(subscribers);
}
// delete subscriber(s)
@RequestMapping("/admin/abonnement/delete/{id}")
public String delete(@PathVariable Long id){
subscriberService.deleteUser(id);
return "successfully deleted user id number "+ id;
}
}
|
// Staircase program
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the staircase function below.
static void staircase(int n) {
for (int i=1; i <= n; i++){
for(int space=0; space < n-i; space++){
System.out.print(" ");
}
for(int j=0; j<i;j++){
System.out.print("#");
}
System.out.println();
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
staircase(n);
scanner.close();
}
}
|
package jetbrains.mps.samples.Shapes.editor;
/*Generated by MPS */
import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Indent;
import org.jetbrains.mps.openapi.language.SReferenceLink;
import jetbrains.mps.lang.editor.cellProviders.SReferenceCellProvider;
import jetbrains.mps.editor.runtime.impl.CellUtil;
import jetbrains.mps.nodeEditor.cells.EditorCell_Error;
import jetbrains.mps.openapi.editor.cells.CellActionType;
import jetbrains.mps.nodeEditor.cellActions.CellAction_DeleteNode;
import jetbrains.mps.nodeEditor.cellMenu.SReferenceSubstituteInfoSmartReferenceDecorator;
import jetbrains.mps.nodeEditor.cellMenu.SReferenceSubstituteInfo;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.IAttributeDescriptor;
import jetbrains.mps.internal.collections.runtime.Sequence;
import jetbrains.mps.internal.collections.runtime.IWhereFilter;
import java.util.Objects;
import jetbrains.mps.lang.core.behavior.LinkAttribute__BehaviorDescriptor;
import jetbrains.mps.nodeEditor.EditorManager;
import jetbrains.mps.openapi.editor.update.AttributeKind;
import org.jetbrains.mps.openapi.language.SProperty;
import jetbrains.mps.openapi.editor.menus.transformation.SPropertyInfo;
import jetbrains.mps.nodeEditor.cells.EditorCell_Property;
import jetbrains.mps.nodeEditor.cells.SPropertyAccessor;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.editor.runtime.style.StyleAttributes;
import jetbrains.mps.nodeEditor.cellMenu.SPropertySubstituteInfo;
import jetbrains.mps.lang.core.behavior.PropertyAttribute__BehaviorDescriptor;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SConcept;
/*package*/ class ColorReference_EditorBuilder_a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
public ColorReference_EditorBuilder_a(@NotNull EditorContext context, @NotNull SNode node) {
super(context);
myNode = node;
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
/*package*/ EditorCell createCell() {
return createCollection_0();
}
private EditorCell createCollection_0() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_m0piq_a");
editorCell.setBig(true);
setCellContext(editorCell);
editorCell.addEditorCell(createRefCell_0());
return editorCell;
}
private EditorCell createRefCell_0() {
final SReferenceLink referenceLink = LINKS.target$hpcG;
SReferenceCellProvider provider = new SReferenceCellProvider(getNode(), referenceLink, getEditorContext()) {
protected EditorCell createReferenceCell(final SNode targetNode) {
EditorCell cell = getUpdateSession().updateReferencedNodeCell(() -> new Inline_Builder0(getEditorContext(), getNode(), targetNode).createCell(), targetNode, LINKS.target$hpcG);
CellUtil.setupIDeprecatableStyles(targetNode, cell);
setSemanticNodeToCells(cell, getNode());
installDeleteActions_notnull_smartReference(cell);
return cell;
}
@Override
protected EditorCell createErrorCell(String error) {
EditorCell_Error cell = new EditorCell_Error(getEditorContext(), getNode(), error, true);
cell.setAction(CellActionType.DELETE, new CellAction_DeleteNode(getNode(), CellAction_DeleteNode.DeleteDirection.FORWARD));
cell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteNode(getNode(), CellAction_DeleteNode.DeleteDirection.BACKWARD));
return cell;
}
};
provider.setNoTargetText("<no target>");
EditorCell editorCell = provider.createCell();
if (editorCell.getSRole() == null) {
editorCell.setReferenceCell(true);
editorCell.setSRole(LINKS.target$hpcG);
}
editorCell.setSubstituteInfo(new SReferenceSubstituteInfoSmartReferenceDecorator(new SReferenceSubstituteInfo(editorCell, referenceLink)));
Iterable<SNode> referenceAttributes = SNodeOperations.ofConcept(new IAttributeDescriptor.AllAttributes().list(myNode), CONCEPTS.LinkAttribute$v_);
Iterable<SNode> currentReferenceAttributes = Sequence.fromIterable(referenceAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(LinkAttribute__BehaviorDescriptor.getLink_id1avfQ4BEFo6.invoke(it), referenceLink);
}
});
if (Sequence.fromIterable(currentReferenceAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentReferenceAttributes).first(), AttributeKind.REFERENCE, editorCell);
} else
return editorCell;
}
/*package*/ static class Inline_Builder0 extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
private SNode myReferencingNode;
/*package*/ Inline_Builder0(@NotNull EditorContext context, SNode referencingNode, @NotNull SNode node) {
super(context);
myReferencingNode = referencingNode;
myNode = node;
}
/*package*/ EditorCell createCell() {
return createProperty_0();
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
private EditorCell createProperty_0() {
getCellFactory().pushCellContext();
try {
final SProperty property = PROPS.name$MnvL;
getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property));
EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, true, false), myNode);
editorCell.setDefaultText("<no name>");
editorCell.setCellId("property_name");
Style style = new StyleImpl();
style.set(StyleAttributes.AUTO_DELETABLE, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SPropertySubstituteInfo(editorCell, property));
setCellContext(editorCell);
Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(new IAttributeDescriptor.AllAttributes().list(myNode), CONCEPTS.PropertyAttribute$Gb);
Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property);
}
});
if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell);
} else
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
}
private static final class LINKS {
/*package*/ static final SReferenceLink target$hpcG = MetaAdapterFactory.getReferenceLink(0x16bafbb4c6cd4cc5L, 0x83327c6de8729b3fL, 0x3a2b0182df2201afL, 0x3a2b0182df22029aL, "target");
}
private static final class CONCEPTS {
/*package*/ static final SConcept LinkAttribute$v_ = MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da51L, "jetbrains.mps.lang.core.structure.LinkAttribute");
/*package*/ static final SConcept PropertyAttribute$Gb = MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute");
}
private static final class PROPS {
/*package*/ static final SProperty name$MnvL = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
}
}
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.formatting;
import com.intellij.openapi.editor.Document;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.Set;
/**
* Stands for block alignment strategy (e.g. we may want to use different strategies for the different
* {@link Alignment.Anchor alignment acnhors}).
*
* @author Denis Zhdanov
*/
public interface BlockAlignmentProcessor {
enum Result {
/**
* This value should be used to indicate that alignment of the target block can't be performed because it doesn't have
* a counterparty (e.g. we want to align two blocks and this value is returned after processing the first of them).
*/
TARGET_BLOCK_PROCESSED_NOT_ALIGNED,
/** Alignment is performed for the target block. */
TARGET_BLOCK_ALIGNED,
/** Already processed block was realigned because of {@link AlignmentImpl#isAllowBackwardShift() backward alignment}. */
BACKWARD_BLOCK_ALIGNED,
/** Detected that backward alignment dependency graph is cycled. */
RECURSION_DETECTED,
/**
* It was necessary to align already processed block because of {@link AlignmentImpl#isAllowBackwardShift() backward alignment}
* but that can't be done (e.g. that backward block {@link AbstractBlockWrapper#getWhiteSpace() white space} is read-only).
*/
UNABLE_TO_ALIGN_BACKWARD_BLOCK
}
/**
* Asks current processor to perform alignment processing for the parameters encapsulated at the given context.
*
* @param context target parameters holder
* @return processing result
*/
Result applyAlignment(@NotNull Context context);
class Context {
@NotNull public final Document document;
@NotNull public final AlignmentImpl alignment;
@NotNull public final LeafBlockWrapper targetBlock;
@NotNull public final Map<AbstractBlockWrapper, Set<AbstractBlockWrapper>> alignmentMappings;
@NotNull public final Map<LeafBlockWrapper, Set<LeafBlockWrapper>> backwardShiftedAlignedBlocks;
@NotNull public final CommonCodeStyleSettings.IndentOptions indentOptions;
public Context(@NotNull Document document,
@NotNull AlignmentImpl alignment,
@NotNull LeafBlockWrapper targetBlock,
@NotNull Map<AbstractBlockWrapper, Set<AbstractBlockWrapper>> alignmentMappings,
@NotNull Map<LeafBlockWrapper, Set<LeafBlockWrapper>> backwardShiftedAlignedBlocks,
@NotNull CommonCodeStyleSettings.IndentOptions indentOptions)
{
this.document = document;
this.alignment = alignment;
this.targetBlock = targetBlock;
this.alignmentMappings = alignmentMappings;
this.backwardShiftedAlignedBlocks = backwardShiftedAlignedBlocks;
this.indentOptions = indentOptions;
}
}
}
|
/**
* Time Complexity: O(N^2)
*
*/
public class WeightedQuickUnionUF {
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in subtree rooted at i
private int count; // number of components
public WeightedQuickUnionUF(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int count() {
return count;
}
public int find(int p) {
validate(p);
while (p != parent[p])
p = parent[p];
return p;
}
// validate that p is a valid index
private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n - 1));
}
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
} else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
}
|
package apimodels;
import com.google.gson.annotations.SerializedName;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel()
public class SpaceStationDetailed {
@SerializedName("id")
private Integer id = null;
@SerializedName("url")
private String url = null;
@SerializedName("name")
private String name = null;
@SerializedName("status")
private SpaceStationStatus status = null;
@SerializedName("type")
private SpaceStationType type = null;
@SerializedName("founded")
private Date founded = null;
@SerializedName("deorbited")
private Date deorbited = null;
@SerializedName("height")
private BigDecimal height = null;
@SerializedName("width")
private BigDecimal width = null;
@SerializedName("mass")
private BigDecimal mass = null;
@SerializedName("volume")
private Integer volume = null;
@SerializedName("description")
private String description = null;
@SerializedName("orbit")
private String orbit = null;
@SerializedName("onboard_crew")
private String onboardCrew = null;
@SerializedName("owners")
private List<Agency> owners = null;
@SerializedName("active_expeditions")
private List<ExpeditionDetailedSerializerForSpacestation> activeExpeditions = null;
@SerializedName("docking_location")
private List<DockingLocationSerializerForSpacestation> dockingLocation = null;
@SerializedName("image_url")
private String imageUrl = null;
/**
**/
@ApiModelProperty()
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
/**
**/
@ApiModelProperty()
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
/**
**/
@ApiModelProperty(required = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
**/
@ApiModelProperty()
public SpaceStationStatus getStatus() {
return status;
}
public void setStatus(SpaceStationStatus status) {
this.status = status;
}
/**
**/
@ApiModelProperty()
public SpaceStationType getType() {
return type;
}
public void setType(SpaceStationType type) {
this.type = type;
}
/**
**/
@ApiModelProperty(required = true)
public Date getFounded() {
return founded;
}
public void setFounded(Date founded) {
this.founded = founded;
}
/**
**/
@ApiModelProperty()
public Date getDeorbited() {
return deorbited;
}
public void setDeorbited(Date deorbited) {
this.deorbited = deorbited;
}
/**
**/
@ApiModelProperty()
public BigDecimal getHeight() {
return height;
}
public void setHeight(BigDecimal height) {
this.height = height;
}
/**
**/
@ApiModelProperty()
public BigDecimal getWidth() {
return width;
}
public void setWidth(BigDecimal width) {
this.width = width;
}
/**
**/
@ApiModelProperty()
public BigDecimal getMass() {
return mass;
}
public void setMass(BigDecimal mass) {
this.mass = mass;
}
/**
* minimum: -2147483648
* maximum: 2147483647
**/
@ApiModelProperty()
public Integer getVolume() {
return volume;
}
public void setVolume(Integer volume) {
this.volume = volume;
}
/**
**/
@ApiModelProperty(required = true)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
**/
@ApiModelProperty()
public String getOrbit() {
return orbit;
}
public void setOrbit(String orbit) {
this.orbit = orbit;
}
/**
**/
@ApiModelProperty()
public String getOnboardCrew() {
return onboardCrew;
}
public void setOnboardCrew(String onboardCrew) {
this.onboardCrew = onboardCrew;
}
/**
**/
@ApiModelProperty()
public List<Agency> getOwners() {
return owners;
}
public void setOwners(List<Agency> owners) {
this.owners = owners;
}
/**
**/
@ApiModelProperty()
public List<ExpeditionDetailedSerializerForSpacestation> getActiveExpeditions() {
return activeExpeditions;
}
public void setActiveExpeditions(List<ExpeditionDetailedSerializerForSpacestation> activeExpeditions) {
this.activeExpeditions = activeExpeditions;
}
/**
**/
@ApiModelProperty()
public List<DockingLocationSerializerForSpacestation> getDockingLocation() {
return dockingLocation;
}
public void setDockingLocation(List<DockingLocationSerializerForSpacestation> dockingLocation) {
this.dockingLocation = dockingLocation;
}
/**
**/
@ApiModelProperty()
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SpaceStationDetailed spaceStationDetailed = (SpaceStationDetailed) o;
return (Objects.equals(this.id, spaceStationDetailed.id)) &&
(Objects.equals(this.url, spaceStationDetailed.url)) &&
(Objects.equals(this.name, spaceStationDetailed.name)) &&
(Objects.equals(this.status, spaceStationDetailed.status)) &&
(Objects.equals(this.type, spaceStationDetailed.type)) &&
(Objects.equals(this.founded, spaceStationDetailed.founded)) &&
(Objects.equals(this.deorbited, spaceStationDetailed.deorbited)) &&
(Objects.equals(this.height, spaceStationDetailed.height)) &&
(Objects.equals(this.width, spaceStationDetailed.width)) &&
(Objects.equals(this.mass, spaceStationDetailed.mass)) &&
(Objects.equals(this.volume, spaceStationDetailed.volume)) &&
(Objects.equals(this.description, spaceStationDetailed.description)) &&
(Objects.equals(this.orbit, spaceStationDetailed.orbit)) &&
(Objects.equals(this.onboardCrew, spaceStationDetailed.onboardCrew)) &&
(Objects.equals(this.owners, spaceStationDetailed.owners)) &&
(Objects.equals(this.activeExpeditions, spaceStationDetailed.activeExpeditions)) &&
(Objects.equals(this.dockingLocation, spaceStationDetailed.dockingLocation)) &&
(Objects.equals(this.imageUrl, spaceStationDetailed.imageUrl));
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (this.id == null ? 0: this.id.hashCode());
result = 31 * result + (this.url == null ? 0: this.url.hashCode());
result = 31 * result + (this.name == null ? 0: this.name.hashCode());
result = 31 * result + (this.status == null ? 0: this.status.hashCode());
result = 31 * result + (this.type == null ? 0: this.type.hashCode());
result = 31 * result + (this.founded == null ? 0: this.founded.hashCode());
result = 31 * result + (this.deorbited == null ? 0: this.deorbited.hashCode());
result = 31 * result + (this.height == null ? 0: this.height.hashCode());
result = 31 * result + (this.width == null ? 0: this.width.hashCode());
result = 31 * result + (this.mass == null ? 0: this.mass.hashCode());
result = 31 * result + (this.volume == null ? 0: this.volume.hashCode());
result = 31 * result + (this.description == null ? 0: this.description.hashCode());
result = 31 * result + (this.orbit == null ? 0: this.orbit.hashCode());
result = 31 * result + (this.onboardCrew == null ? 0: this.onboardCrew.hashCode());
result = 31 * result + (this.owners == null ? 0: this.owners.hashCode());
result = 31 * result + (this.activeExpeditions == null ? 0: this.activeExpeditions.hashCode());
result = 31 * result + (this.dockingLocation == null ? 0: this.dockingLocation.hashCode());
result = 31 * result + (this.imageUrl == null ? 0: this.imageUrl.hashCode());
return result;
}
@Override
public String toString() {
return "class SpaceStationDetailed {\n" +
" id: " + id + "\n" +
" url: " + url + "\n" +
" name: " + name + "\n" +
" status: " + status + "\n" +
" type: " + type + "\n" +
" founded: " + founded + "\n" +
" deorbited: " + deorbited + "\n" +
" height: " + height + "\n" +
" width: " + width + "\n" +
" mass: " + mass + "\n" +
" volume: " + volume + "\n" +
" description: " + description + "\n" +
" orbit: " + orbit + "\n" +
" onboardCrew: " + onboardCrew + "\n" +
" owners: " + owners + "\n" +
" activeExpeditions: " + activeExpeditions + "\n" +
" dockingLocation: " + dockingLocation + "\n" +
" imageUrl: " + imageUrl + "\n" +
"}\n";
}
}
|
/*
* 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.directory.api.ldap.schema.loader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.directory.api.asn1.util.Oid;
import org.apache.directory.api.i18n.I18n;
import org.apache.directory.api.ldap.model.constants.MetaSchemaConstants;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.DefaultAttribute;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Value;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.ldap.model.exception.LdapSchemaException;
import org.apache.directory.api.ldap.model.exception.LdapUnwillingToPerformException;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.api.ldap.model.schema.LdapComparator;
import org.apache.directory.api.ldap.model.schema.LdapSyntax;
import org.apache.directory.api.ldap.model.schema.LoadableSchemaObject;
import org.apache.directory.api.ldap.model.schema.MatchingRule;
import org.apache.directory.api.ldap.model.schema.MutableAttributeType;
import org.apache.directory.api.ldap.model.schema.MutableMatchingRule;
import org.apache.directory.api.ldap.model.schema.MutableObjectClass;
import org.apache.directory.api.ldap.model.schema.Normalizer;
import org.apache.directory.api.ldap.model.schema.ObjectClass;
import org.apache.directory.api.ldap.model.schema.ObjectClassTypeEnum;
import org.apache.directory.api.ldap.model.schema.SchemaManager;
import org.apache.directory.api.ldap.model.schema.SchemaObject;
import org.apache.directory.api.ldap.model.schema.SyntaxChecker;
import org.apache.directory.api.ldap.model.schema.SyntaxChecker.SCBuilder;
import org.apache.directory.api.ldap.model.schema.UsageEnum;
import org.apache.directory.api.ldap.model.schema.parsers.LdapComparatorDescription;
import org.apache.directory.api.ldap.model.schema.parsers.NormalizerDescription;
import org.apache.directory.api.ldap.model.schema.parsers.SyntaxCheckerDescription;
import org.apache.directory.api.ldap.model.schema.registries.DefaultSchema;
import org.apache.directory.api.ldap.model.schema.registries.Registries;
import org.apache.directory.api.ldap.model.schema.registries.Schema;
import org.apache.directory.api.util.Base64;
import org.apache.directory.api.util.StringConstants;
import org.apache.directory.api.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Showing how it's done ...
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SchemaEntityFactory implements EntityFactory
{
/** Slf4j logger */
private static final Logger LOG = LoggerFactory.getLogger( SchemaEntityFactory.class );
/** The empty string list. */
private static final List<String> EMPTY_LIST = new ArrayList<>();
/** The empty string array. */
private static final String[] EMPTY_ARRAY = new String[]
{};
/** A special ClassLoader that loads a class from the bytecode attribute */
private final AttributeClassLoader classLoader;
/**
* Instantiates a new schema entity factory.
*/
public SchemaEntityFactory()
{
this.classLoader = AccessController.doPrivileged( new PrivilegedAction<AttributeClassLoader>()
{
@Override
public AttributeClassLoader run()
{
return new AttributeClassLoader();
}
} );
}
/**
* Get an OID from an entry. Handles the bad cases (null OID,
* not a valid OID, ...)
*
* @param entry The entry to process
* @param objectType The type of processed SchemaObject
* @param strict If we want a strict control of the OID
* @return The found OID
* @throws LdapInvalidAttributeValueException If the OID is not valid
*/
private String getOid( Entry entry, String objectType, boolean strict ) throws LdapInvalidAttributeValueException
{
// The OID
Attribute mOid = entry.get( MetaSchemaConstants.M_OID_AT );
if ( mOid == null )
{
String msg = I18n.err( I18n.ERR_16011_NULL_ATTRIBUTE, objectType, MetaSchemaConstants.M_OID_AT );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new IllegalArgumentException( msg );
}
String oid = mOid.getString();
if ( strict && !Oid.isOid( oid ) )
{
String msg = I18n.err( I18n.ERR_16012_INVALID_COMPARATOR_OID, oid );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapInvalidAttributeValueException( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, msg );
}
return oid;
}
/**
* Get an OID from an entry. Handles the bad cases (null OID,
* not a valid OID, ...)
*
* @param description The schemaObject description
* @param objectType The type of SchemaObject being processed
* @return The found OID
* @throws LdapInvalidAttributeValueException If the OID is invalid
*/
private String getOid( SchemaObject description, String objectType ) throws LdapInvalidAttributeValueException
{
// The OID
String oid = description.getOid();
if ( oid == null )
{
String msg = I18n.err( I18n.ERR_16011_NULL_ATTRIBUTE, objectType, MetaSchemaConstants.M_OID_AT );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new IllegalArgumentException( msg );
}
if ( !Oid.isOid( oid ) )
{
String msg = I18n.err( I18n.ERR_16012_INVALID_COMPARATOR_OID, oid );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapInvalidAttributeValueException( ResultCodeEnum.INVALID_ATTRIBUTE_SYNTAX, msg );
}
return oid;
}
/**
* Check that the Entry is not null
*
* @param entry The entry to check
* @param schemaEntity The message to log if the entry is invalid
*/
private void checkEntry( Entry entry, String schemaEntity )
{
if ( entry == null )
{
String msg = I18n.err( I18n.ERR_16013_NULL_ENTRY, schemaEntity );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new IllegalArgumentException( msg );
}
}
/**
* Check that the Description is not null
*
* @param description description entry to check
* @param schemaEntity The message to log if the description is invalid
*/
private void checkDescription( SchemaObject description, String schemaEntity )
{
if ( description == null )
{
String msg = I18n.err( I18n.ERR_16014_NULL_SCHEMA_DESC, schemaEntity );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new IllegalArgumentException( msg );
}
}
/**
* Get the schema from its name. Return the Other reference if there
* is no schema name. Throws a NPE if the schema is not loaded.
*
* @param schemaName The schema name to fetch
* @param registries The registries where we get the schema from
* @return the found Schema
*/
private Schema getSchema( String schemaName, Registries registries )
{
if ( Strings.isEmpty( schemaName ) )
{
schemaName = MetaSchemaConstants.SCHEMA_OTHER;
}
Schema schema = registries.getLoadedSchema( schemaName );
if ( schema == null )
{
String msg = I18n.err( I18n.ERR_16015_NON_EXISTENT_SCHEMA, schemaName );
LOG.error( msg );
}
return schema;
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema( Entry entry ) throws LdapException
{
String name;
String owner;
String[] dependencies = EMPTY_ARRAY;
boolean isDisabled = false;
if ( entry == null )
{
throw new IllegalArgumentException( I18n.err( I18n.ERR_16016_NULL_ENTRY ) );
}
if ( entry.get( SchemaConstants.CN_AT ) == null )
{
throw new IllegalArgumentException( I18n.err( I18n.ERR_16017_INVALID_CN_AT ) );
}
name = entry.get( SchemaConstants.CN_AT ).getString();
if ( entry.get( SchemaConstants.CREATORS_NAME_AT ) == null )
{
throw new IllegalArgumentException( I18n.err( I18n.ERR_16018_INVALID_AT, SchemaConstants.CREATORS_NAME_AT ) );
}
owner = entry.get( SchemaConstants.CREATORS_NAME_AT ).getString();
if ( entry.get( MetaSchemaConstants.M_DISABLED_AT ) != null )
{
String value = entry.get( MetaSchemaConstants.M_DISABLED_AT ).getString();
value = Strings.upperCase( value );
isDisabled = "TRUE".equalsIgnoreCase( value );
}
if ( entry.get( MetaSchemaConstants.M_DEPENDENCIES_AT ) != null )
{
Set<String> depsSet = new HashSet<>();
Attribute depsAttr = entry.get( MetaSchemaConstants.M_DEPENDENCIES_AT );
for ( Value value : depsAttr )
{
depsSet.add( value.getValue() );
}
dependencies = depsSet.toArray( EMPTY_ARRAY );
}
return new DefaultSchema( null, name, owner, dependencies, isDisabled );
}
/**
* Class load a SyntaxChecker instance
*
* @param schemaManager The SchemaManager
* @param oid The SyntaxChecker OID
* @param className The class name associated with the SyntaxChecker
* @param byteCode The SyntaxChecker class bytecode
* @return The loaded SyntaxChecker
* @throws LdapException If the SyntaxChecker cannot be loaded
*/
private SyntaxChecker classLoadSyntaxChecker( SchemaManager schemaManager, String oid, String className,
Attribute byteCode ) throws LdapException
{
// Try to class load the syntaxChecker
Class<?> clazz;
SyntaxChecker syntaxChecker;
String byteCodeStr = StringConstants.EMPTY;
if ( byteCode == null )
{
try
{
clazz = Class.forName( className );
}
catch ( ClassNotFoundException cnfe )
{
LOG.error( I18n.err( I18n.ERR_16048_CANNOT_FIND_SC_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16049_CANNOT_FIND_SC_CLASS, cnfe.getMessage() ) );
}
}
else
{
classLoader.setAttribute( byteCode );
try
{
clazz = classLoader.loadClass( className );
}
catch ( ClassNotFoundException cnfe )
{
LOG.error( I18n.err( I18n.ERR_16050_CANNOT_LOAD_SC_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16051_CANNOT_LOAD_SC_CLASS, cnfe.getMessage() ) );
}
byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) );
}
// Create the syntaxChecker instance
try
{
Method builder = clazz.getMethod( "builder", ( Class<?>[] ) null );
syntaxChecker = ( SyntaxChecker ) ( ( SCBuilder ) builder.invoke( null, ( Object[] ) null ) ).setOid( oid ).build();
}
catch ( NoSuchMethodException nsme )
{
LOG.error( I18n.err( I18n.ERR_16052_CANNOT_INST_SC_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16053_CANNOT_INST_SC_CLASS, nsme.getMessage() ) );
}
catch ( InvocationTargetException | IllegalAccessException e )
{
LOG.error( I18n.err( I18n.ERR_16054_CANNOT_ACCESS_SC_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16055_CANNOT_ACCESS_SC_CLASS, e.getMessage() ) );
}
// Update the common fields
syntaxChecker.setBytecode( byteCodeStr );
syntaxChecker.setFqcn( className );
// Inject the SchemaManager for the comparator who needs it
syntaxChecker.setSchemaManager( schemaManager );
return syntaxChecker;
}
/**
* {@inheritDoc}
*/
@Override
public SyntaxChecker getSyntaxChecker( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
String schemaName ) throws LdapException
{
checkEntry( entry, SchemaConstants.SYNTAX_CHECKER );
// The SyntaxChecker OID
String oid = getOid( entry, SchemaConstants.SYNTAX_CHECKER, schemaManager.isStrict() );
// Get the schema
if ( !schemaManager.isSchemaLoaded( schemaName ) )
{
// The schema is not loaded. We can't create the requested Normalizer
String msg = I18n.err( I18n.ERR_16019_CANNOT_ADD_SC, entry.getDn().getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is disabled. We still have to update the backend
if ( LOG.isInfoEnabled() )
{
LOG.info( I18n.err( I18n.ERR_16020_CANNOT_ADD_SC_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
}
schema = schemaManager.getLoadedSchema( schemaName );
}
// The FQCN
String className = getFqcn( entry, SchemaConstants.SYNTAX_CHECKER );
// The ByteCode
Attribute byteCode = entry.get( MetaSchemaConstants.M_BYTECODE_AT );
try
{
// Class load the syntaxChecker
SyntaxChecker syntaxChecker = classLoadSyntaxChecker( schemaManager, oid, className, byteCode );
// Update the common fields
setSchemaObjectProperties( syntaxChecker, entry, schema );
// return the resulting syntaxChecker
return syntaxChecker;
}
catch ( Exception e )
{
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, e.getMessage(), e );
}
}
/**
* {@inheritDoc}
*/
@Override
public SyntaxChecker getSyntaxChecker( SchemaManager schemaManager,
SyntaxCheckerDescription syntaxCheckerDescription, Registries targetRegistries, String schemaName )
throws LdapException
{
checkDescription( syntaxCheckerDescription, SchemaConstants.SYNTAX_CHECKER );
// The Comparator OID
String oid = getOid( syntaxCheckerDescription, SchemaConstants.SYNTAX_CHECKER );
// Get the schema
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is not loaded. We can't create the requested SyntaxChecker
String msg = I18n.err( I18n.ERR_16019_CANNOT_ADD_SC, syntaxCheckerDescription.getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
// The FQCN
String fqcn = getFqcn( syntaxCheckerDescription, SchemaConstants.SYNTAX_CHECKER );
// get the byteCode
Attribute byteCode = getByteCode( syntaxCheckerDescription, SchemaConstants.SYNTAX_CHECKER );
// Class load the SyntaxChecker
SyntaxChecker syntaxChecker = classLoadSyntaxChecker( schemaManager, oid, fqcn, byteCode );
// Update the common fields
setSchemaObjectProperties( syntaxChecker, syntaxCheckerDescription, schema );
return syntaxChecker;
}
/**
* Class load a comparator instances
*
* @param schemaManager The SchemaManager
* @param oid The comparator OID
* @param className The class name associated with the comparator
* @param byteCode The comparator class bytecode
* @return The loaded comparator
* @throws LdapException If the comparator cannot be loaded
*/
private LdapComparator<?> classLoadComparator( SchemaManager schemaManager, String oid, String className,
Attribute byteCode ) throws LdapException
{
// Try to class load the comparator
LdapComparator<?> comparator;
Class<?> clazz;
String byteCodeStr = StringConstants.EMPTY;
if ( byteCode == null )
{
try
{
clazz = Class.forName( className );
}
catch ( ClassNotFoundException cnfe )
{
LOG.error( I18n.err( I18n.ERR_16056_CANNOT_FIND_CMP_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16057_CANNOT_FIND_CMP_CLASS, cnfe.getMessage() ) );
}
}
else
{
classLoader.setAttribute( byteCode );
try
{
clazz = classLoader.loadClass( className );
}
catch ( ClassNotFoundException cnfe )
{
LOG.error( I18n.err( I18n.ERR_16058_CANNOT_LOAD_CMP_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16059_CANNOT_LOAD_CMP_CLASS, cnfe.getMessage() ) );
}
byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) );
}
// Create the comparator instance. Either we have a no argument constructor,
// or we have one which takes an OID. Lets try the one with an OID argument first
try
{
Constructor<?> constructor = clazz.getConstructor( new Class[]
{ String.class } );
try
{
comparator = ( LdapComparator<?> ) constructor.newInstance( oid );
}
catch ( InvocationTargetException ite )
{
LOG.error( I18n.err( I18n.ERR_16060_CANNOT_INVOKE_CMP_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16061_CANNOT_INVOKE_CMP_CLASS, ite.getMessage() ) );
}
catch ( InstantiationException ie )
{
LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) );
}
catch ( IllegalAccessException ie )
{
LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, ie.getMessage() ) );
}
}
catch ( NoSuchMethodException nsme )
{
// Ok, let's try with the constructor without argument.
// In this case, we will have to check that the OID is the same than
// the one we got in the Comparator entry
try
{
clazz.getConstructor();
}
catch ( NoSuchMethodException nsme2 )
{
LOG.error( I18n.err( I18n.ERR_16066_CANNOT_FIND_CMP_CTOR_METH_CLASS, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16067_CANNOT_FIND_CMP_CTOR_METH, nsme2.getMessage() ) );
}
try
{
comparator = ( LdapComparator<?> ) clazz.newInstance();
}
catch ( InstantiationException ie )
{
LOG.error( I18n.err( I18n.ERR_16062_CANNOT_INST_CMP_CTOR_CLASS, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16063_CANNOT_INST_CMP_CLASS, ie.getMessage() ) );
}
catch ( IllegalAccessException iae )
{
LOG.error( I18n.err( I18n.ERR_16064_CANNOT_ACCESS_CMP_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16065_CANNOT_ACCESS_CMP_CLASS, iae.getMessage() ) );
}
if ( !comparator.getOid().equals( oid ) )
{
String msg = I18n.err( I18n.ERR_16021_DIFFERENT_COMPARATOR_OID, oid, comparator.getOid() );
throw new LdapInvalidAttributeValueException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg, nsme );
}
}
// Update the loadable fields
comparator.setBytecode( byteCodeStr );
comparator.setFqcn( className );
// Inject the SchemaManager for the comparator who needs it
comparator.setSchemaManager( schemaManager );
return comparator;
}
/**
* {@inheritDoc}
*/
@Override
public LdapComparator<?> getLdapComparator( SchemaManager schemaManager,
LdapComparatorDescription comparatorDescription, Registries targetRegistries, String schemaName )
throws LdapException
{
checkDescription( comparatorDescription, SchemaConstants.COMPARATOR );
// The Comparator OID
String oid = getOid( comparatorDescription, SchemaConstants.COMPARATOR );
// Get the schema
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is not loaded. We can't create the requested Comparator
String msg = I18n.err( I18n.ERR_16022_CANNOT_ADD_CMP, comparatorDescription.getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
// The FQCN
String fqcn = getFqcn( comparatorDescription, SchemaConstants.COMPARATOR );
// get the byteCode
Attribute byteCode = getByteCode( comparatorDescription, SchemaConstants.COMPARATOR );
// Class load the comparator
LdapComparator<?> comparator = classLoadComparator( schemaManager, oid, fqcn, byteCode );
// Update the common fields
setSchemaObjectProperties( comparator, comparatorDescription, schema );
return comparator;
}
/**
* {@inheritDoc}
*/
@Override
public LdapComparator<?> getLdapComparator( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
String schemaName ) throws LdapException
{
checkEntry( entry, SchemaConstants.COMPARATOR );
// The Comparator OID
String oid = getOid( entry, SchemaConstants.COMPARATOR, schemaManager.isStrict() );
// Get the schema
if ( !schemaManager.isSchemaLoaded( schemaName ) )
{
// The schema is not loaded. We can't create the requested Comparator
String msg = I18n.err( I18n.ERR_16022_CANNOT_ADD_CMP, entry.getDn().getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is disabled. We still have to update the backend
if ( LOG.isInfoEnabled() )
{
LOG.info( I18n.err( I18n.ERR_16023_CANNOT_ADD_CMP_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
}
schema = schemaManager.getLoadedSchema( schemaName );
}
// The FQCN
String fqcn = getFqcn( entry, SchemaConstants.COMPARATOR );
// The ByteCode
Attribute byteCode = entry.get( MetaSchemaConstants.M_BYTECODE_AT );
try
{
// Class load the comparator
LdapComparator<?> comparator = classLoadComparator( schemaManager, oid, fqcn, byteCode );
// Update the common fields
setSchemaObjectProperties( comparator, entry, schema );
// return the resulting comparator
return comparator;
}
catch ( Exception e )
{
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, e.getMessage(), e );
}
}
/**
* Class load a normalizer instances
*
* @param schemaManager The SchemaManager
* @param oid The normalizer OID
* @param className The class name associated with the normalizer
* @param byteCode The normalizer class bytecode
* @return The loaded normalizer
* @throws LdapException If the normalizer cannot be loaded
*/
private Normalizer classLoadNormalizer( SchemaManager schemaManager, String oid, String className,
Attribute byteCode ) throws LdapException
{
// Try to class load the normalizer
Class<?> clazz;
Normalizer normalizer;
String byteCodeStr = StringConstants.EMPTY;
if ( byteCode == null )
{
try
{
clazz = Class.forName( className );
}
catch ( ClassNotFoundException cnfe )
{
LOG.error( I18n.err( I18n.ERR_16068_CANNOT_FIND_NORM_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16069_CANNOT_FIND_NORM_CLASS, cnfe.getMessage() ) );
}
}
else
{
classLoader.setAttribute( byteCode );
try
{
clazz = classLoader.loadClass( className );
}
catch ( ClassNotFoundException cnfe )
{
LOG.error( I18n.err( I18n.ERR_16070_CANNOT_LOAD_NORM_CTOR, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16071_CANNOT_LOAD_NORM_CLASS, cnfe.getMessage() ) );
}
byteCodeStr = new String( Base64.encode( byteCode.getBytes() ) );
}
// Create the normalizer instance
try
{
normalizer = ( Normalizer ) clazz.newInstance();
}
catch ( InstantiationException ie )
{
LOG.error( I18n.err( I18n.ERR_16072_CANNOT_INST_NORM_CTOR_CLASS, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16073_CANNOT_INST_NORM_CLASS, ie.getMessage() ) );
}
catch ( IllegalAccessException iae )
{
LOG.error( I18n.err( I18n.ERR_16074_CANNOT_ACCESS_NORM_CTOR_CLASS, className ) );
throw new LdapSchemaException( I18n.err( I18n.ERR_16075_CANNOT_ACCESS_NORM_CTOR, iae.getMessage() ) );
}
// Update the common fields
normalizer.setBytecode( byteCodeStr );
normalizer.setFqcn( className );
// Inject the new OID, as the loaded normalizer might have its own
normalizer.setOid( oid );
// Inject the SchemaManager for the normalizer who needs it
normalizer.setSchemaManager( schemaManager );
return normalizer;
}
/**
* {@inheritDoc}
*/
@Override
public Normalizer getNormalizer( SchemaManager schemaManager, NormalizerDescription normalizerDescription,
Registries targetRegistries, String schemaName ) throws LdapException
{
checkDescription( normalizerDescription, SchemaConstants.NORMALIZER );
// The Comparator OID
String oid = getOid( normalizerDescription, SchemaConstants.NORMALIZER );
// Get the schema
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is not loaded. We can't create the requested Normalizer
String msg = I18n.err( I18n.ERR_16024_CANNOT_ADD_NORMALIZER, normalizerDescription.getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
// The FQCN
String fqcn = getFqcn( normalizerDescription, SchemaConstants.NORMALIZER );
// get the byteCode
Attribute byteCode = getByteCode( normalizerDescription, SchemaConstants.NORMALIZER );
// Class load the normalizer
Normalizer normalizer = classLoadNormalizer( schemaManager, oid, fqcn, byteCode );
// Update the common fields
setSchemaObjectProperties( normalizer, normalizerDescription, schema );
return normalizer;
}
/**
* {@inheritDoc}
*/
@Override
public Normalizer getNormalizer( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
String schemaName ) throws LdapException
{
checkEntry( entry, SchemaConstants.NORMALIZER );
// The Normalizer OID
String oid = getOid( entry, SchemaConstants.NORMALIZER, schemaManager.isStrict() );
// Get the schema
if ( !schemaManager.isSchemaLoaded( schemaName ) )
{
// The schema is not loaded. We can't create the requested Normalizer
String msg = I18n.err( I18n.ERR_16024_CANNOT_ADD_NORMALIZER, entry.getDn().getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is disabled. We still have to update the backend
if ( LOG.isInfoEnabled() )
{
LOG.info( I18n.err( I18n.ERR_16025_CANNOT_ADD_NORMALIZER_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
}
schema = schemaManager.getLoadedSchema( schemaName );
}
// The FQCN
String className = getFqcn( entry, SchemaConstants.NORMALIZER );
// The ByteCode
Attribute byteCode = entry.get( MetaSchemaConstants.M_BYTECODE_AT );
try
{
// Class load the Normalizer
Normalizer normalizer = classLoadNormalizer( schemaManager, oid, className, byteCode );
// Update the common fields
setSchemaObjectProperties( normalizer, entry, schema );
// return the resulting Normalizer
return normalizer;
}
catch ( Exception e )
{
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, e.getMessage(), e );
}
}
/**
* {@inheritDoc}
* @throws LdapInvalidAttributeValueException If the Syntax does not exist
* @throws LdapUnwillingToPerformException If the schema is not loaded
*/
@Override
public LdapSyntax getSyntax( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
String schemaName ) throws LdapInvalidAttributeValueException, LdapUnwillingToPerformException
{
checkEntry( entry, SchemaConstants.SYNTAX );
// The Syntax OID
String oid = getOid( entry, SchemaConstants.SYNTAX, schemaManager.isStrict() );
// Get the schema
if ( !schemaManager.isSchemaLoaded( schemaName ) )
{
// The schema is not loaded. We can't create the requested Syntax
String msg = I18n.err( I18n.ERR_16026_CANNOT_ADD_SYNTAX, entry.getDn().getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is disabled. We still have to update the backend
if ( LOG.isInfoEnabled() )
{
LOG.info( I18n.err( I18n.ERR_16027_CANNOT_ADD_SYNTAX_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
}
schema = schemaManager.getLoadedSchema( schemaName );
}
// Create the new LdapSyntax instance
LdapSyntax syntax = new LdapSyntax( oid );
// Common properties
setSchemaObjectProperties( syntax, entry, schema );
return syntax;
}
/**
* {@inheritDoc}
* @throws LdapInvalidAttributeValueException If the MatchingRule does not exist
* @throws LdapUnwillingToPerformException If the schema is not loaded
*/
@Override
public MatchingRule getMatchingRule( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
String schemaName ) throws LdapUnwillingToPerformException, LdapInvalidAttributeValueException
{
checkEntry( entry, SchemaConstants.MATCHING_RULE );
// The MatchingRule OID
String oid = getOid( entry, SchemaConstants.MATCHING_RULE, schemaManager.isStrict() );
// Get the schema
if ( !schemaManager.isSchemaLoaded( schemaName ) )
{
// The schema is not loaded. We can't create the requested MatchingRule
String msg = I18n.err( I18n.ERR_16028_CANNOT_ADD_MR, entry.getDn().getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is disabled. We still have to update the backend
if ( LOG.isInfoEnabled() )
{
LOG.info( I18n.err( I18n.ERR_16029_CANNOT_ADD_MR_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
}
schema = schemaManager.getLoadedSchema( schemaName );
}
MutableMatchingRule matchingRule = new MutableMatchingRule( oid );
// The syntax field
Attribute mSyntax = entry.get( MetaSchemaConstants.M_SYNTAX_AT );
if ( mSyntax != null )
{
matchingRule.setSyntaxOid( mSyntax.getString() );
}
// The normalizer and comparator fields will be updated when we will
// apply the registry
// Common properties
setSchemaObjectProperties( matchingRule, entry, schema );
return matchingRule;
}
/**
* Create a list of string from a multivalued attribute's values
*
* @param attr The Attribute to read
* @return The list of values as Strings
*/
private List<String> getStrings( Attribute attr )
{
if ( attr == null )
{
return EMPTY_LIST;
}
List<String> strings = new ArrayList<>( attr.size() );
for ( Value value : attr )
{
strings.add( value.getValue() );
}
return strings;
}
/**
* {@inheritDoc}
*/
@Override
public ObjectClass getObjectClass( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
String schemaName ) throws LdapException
{
checkEntry( entry, SchemaConstants.OBJECT_CLASS );
// The ObjectClass OID
String oid = getOid( entry, SchemaConstants.OBJECT_CLASS, schemaManager.isStrict() );
// Get the schema
if ( !schemaManager.isSchemaLoaded( schemaName ) )
{
// The schema is not loaded. We can't create the requested ObjectClass
String msg = I18n.err( I18n.ERR_16030_CANNOT_ADD_OC, entry.getDn().getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is disabled. We still have to update the backend
if ( LOG.isInfoEnabled() )
{
LOG.info( I18n.err( I18n.ERR_16031_CANNOT_ADD_OC_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
}
schema = schemaManager.getLoadedSchema( schemaName );
}
// Create the ObjectClass instance
MutableObjectClass oc = new MutableObjectClass( oid );
// The Sup field
Attribute mSuperiors = entry.get( MetaSchemaConstants.M_SUP_OBJECT_CLASS_AT );
if ( mSuperiors != null )
{
oc.setSuperiorOids( getStrings( mSuperiors ) );
}
// The May field
Attribute mMay = entry.get( MetaSchemaConstants.M_MAY_AT );
if ( mMay != null )
{
oc.setMayAttributeTypeOids( getStrings( mMay ) );
}
// The Must field
Attribute mMust = entry.get( MetaSchemaConstants.M_MUST_AT );
if ( mMust != null )
{
oc.setMustAttributeTypeOids( getStrings( mMust ) );
}
// The objectClassType field
Attribute mTypeObjectClass = entry.get( MetaSchemaConstants.M_TYPE_OBJECT_CLASS_AT );
if ( mTypeObjectClass != null )
{
String type = mTypeObjectClass.getString();
oc.setType( ObjectClassTypeEnum.getClassType( type ) );
}
// Common properties
setSchemaObjectProperties( oc, entry, schema );
return oc;
}
/**
* {@inheritDoc}
* @throws LdapInvalidAttributeValueException If the AttributeType does not exist
* @throws LdapUnwillingToPerformException If the schema is not loaded
*/
@Override
public AttributeType getAttributeType( SchemaManager schemaManager, Entry entry, Registries targetRegistries,
String schemaName ) throws LdapInvalidAttributeValueException, LdapUnwillingToPerformException
{
checkEntry( entry, SchemaConstants.ATTRIBUTE_TYPE );
// The AttributeType OID
String oid = getOid( entry, SchemaConstants.ATTRIBUTE_TYPE, schemaManager.isStrict() );
// Get the schema
if ( !schemaManager.isSchemaLoaded( schemaName ) )
{
// The schema is not loaded, this is an error
String msg = I18n.err( I18n.ERR_16032_CANNOT_ADD_AT, entry.getDn().getName(), schemaName );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, msg );
}
Schema schema = getSchema( schemaName, targetRegistries );
if ( schema == null )
{
// The schema is disabled. We still have to update the backend
if ( LOG.isInfoEnabled() )
{
LOG.info( I18n.err( I18n.ERR_16033_CANNOT_ADD_AT_IN_REGISTRY, entry.getDn().getName(), schemaName ) );
}
schema = schemaManager.getLoadedSchema( schemaName );
}
// Create the new AttributeType
MutableAttributeType attributeType = new MutableAttributeType( oid );
if ( schemaManager.isRelaxed() )
{
attributeType.setRelaxed( true );
}
// Syntax
Attribute mSyntax = entry.get( MetaSchemaConstants.M_SYNTAX_AT );
if ( ( mSyntax != null ) && ( mSyntax.get() != null ) )
{
attributeType.setSyntaxOid( mSyntax.getString() );
}
// Syntax Length
Attribute mSyntaxLength = entry.get( MetaSchemaConstants.M_LENGTH_AT );
if ( mSyntaxLength != null )
{
attributeType.setSyntaxLength( Integer.parseInt( mSyntaxLength.getString() ) );
}
// Equality
Attribute mEquality = entry.get( MetaSchemaConstants.M_EQUALITY_AT );
if ( mEquality != null )
{
attributeType.setEqualityOid( mEquality.getString() );
}
// Ordering
Attribute mOrdering = entry.get( MetaSchemaConstants.M_ORDERING_AT );
if ( mOrdering != null )
{
attributeType.setOrderingOid( mOrdering.getString() );
}
// Substr
Attribute mSubstr = entry.get( MetaSchemaConstants.M_SUBSTR_AT );
if ( mSubstr != null )
{
attributeType.setSubstringOid( mSubstr.getString() );
}
Attribute mSupAttributeType = entry.get( MetaSchemaConstants.M_SUP_ATTRIBUTE_TYPE_AT );
// Sup
if ( mSupAttributeType != null )
{
attributeType.setSuperiorOid( mSupAttributeType.getString() );
}
// isCollective
Attribute mCollective = entry.get( MetaSchemaConstants.M_COLLECTIVE_AT );
if ( mCollective != null )
{
String val = mCollective.getString();
attributeType.setCollective( "TRUE".equalsIgnoreCase( val ) );
}
// isSingleValued
Attribute mSingleValued = entry.get( MetaSchemaConstants.M_SINGLE_VALUE_AT );
if ( mSingleValued != null )
{
String val = mSingleValued.getString();
attributeType.setSingleValued( "TRUE".equalsIgnoreCase( val ) );
}
// isReadOnly
Attribute mNoUserModification = entry.get( MetaSchemaConstants.M_NO_USER_MODIFICATION_AT );
if ( mNoUserModification != null )
{
String val = mNoUserModification.getString();
attributeType.setUserModifiable( !"TRUE".equalsIgnoreCase( val ) );
}
// Usage
Attribute mUsage = entry.get( MetaSchemaConstants.M_USAGE_AT );
if ( mUsage != null )
{
attributeType.setUsage( UsageEnum.getUsage( mUsage.getString() ) );
}
// Common properties
setSchemaObjectProperties( attributeType, entry, schema );
return attributeType;
}
/**
* Process the FQCN attribute
*
* @param entry The entry to read
* @param objectType The type of schema object
* @return The schema object FQCN
* @throws LdapInvalidAttributeValueException If the attribute does not contain a valid value
*/
private String getFqcn( Entry entry, String objectType ) throws LdapInvalidAttributeValueException
{
// The FQCN
Attribute mFqcn = entry.get( MetaSchemaConstants.M_FQCN_AT );
if ( mFqcn == null )
{
String msg = I18n.err( I18n.ERR_16034_ENTRY_WITHOUT_VALID_AT, objectType, MetaSchemaConstants.M_FQCN_AT );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new IllegalArgumentException( msg );
}
return mFqcn.getString();
}
/**
* Process the FQCN attribute
*
* @param description The Schema Object description
* @param objectType The SchemaObject type
* @return The SchemaObject FQCN
*/
private String getFqcn( LoadableSchemaObject description, String objectType )
{
// The FQCN
String mFqcn = description.getFqcn();
if ( mFqcn == null )
{
String msg = I18n.err( I18n.ERR_16034_ENTRY_WITHOUT_VALID_AT, objectType, MetaSchemaConstants.M_FQCN_AT );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new IllegalArgumentException( msg );
}
return mFqcn;
}
/**
* Process the ByteCode attribute
*
* @param description The SchemaObject description
* @param objectType The SchemaObject type
* @return The Attribute containing the byteCode
*/
private Attribute getByteCode( LoadableSchemaObject description, String objectType )
{
String byteCodeString = description.getBytecode();
if ( byteCodeString == null )
{
String msg = I18n.err( I18n.ERR_16034_ENTRY_WITHOUT_VALID_AT, objectType, MetaSchemaConstants.M_BYTECODE_AT );
if ( LOG.isWarnEnabled() )
{
LOG.warn( msg );
}
throw new IllegalArgumentException( msg );
}
byte[] bytecode = Base64.decode( byteCodeString.toCharArray() );
return new DefaultAttribute( MetaSchemaConstants.M_BYTECODE_AT, bytecode );
}
/**
* Return a String value, from the given Value, even if it's a binary value
*
* @param attribute The Attribute to process
* @return The Attribute value as a String
*/
private String getStringValue( Attribute attribute )
{
Value value = attribute.get();
return value.getValue();
}
/**
* Process the common attributes to all SchemaObjects :
* - obsolete
* - description
* - names
* - schemaName
* - specification (if any)
* - extensions
* - isReadOnly
* - isEnabled
*
* @param schemaObject The SchemaObject to set
* @param entry The entry containing the SchemaObject properties
* @param schema the updated Schema
* @throws LdapInvalidAttributeValueException If some of the properties are invalid
*/
private void setSchemaObjectProperties( SchemaObject schemaObject, Entry entry, Schema schema )
throws LdapInvalidAttributeValueException
{
// The isObsolete field
Attribute mObsolete = entry.get( MetaSchemaConstants.M_OBSOLETE_AT );
if ( mObsolete != null )
{
String val = mObsolete.getString();
schemaObject.setObsolete( "TRUE".equalsIgnoreCase( val ) );
}
// The description field
Attribute mDescription = entry.get( MetaSchemaConstants.M_DESCRIPTION_AT );
if ( mDescription != null )
{
schemaObject.setDescription( getStringValue( mDescription ) );
}
// The names field
Attribute names = entry.get( MetaSchemaConstants.M_NAME_AT );
if ( names != null )
{
List<String> values = new ArrayList<>();
for ( Value name : names )
{
values.add( name.getValue() );
}
schemaObject.setNames( values );
}
// The isEnabled field
Attribute mDisabled = entry.get( MetaSchemaConstants.M_DISABLED_AT );
// If the SchemaObject has an explicit m-disabled attribute, then use it.
// Otherwise, inherit it from the schema
if ( mDisabled != null )
{
String val = mDisabled.getString();
schemaObject.setEnabled( !"TRUE".equalsIgnoreCase( val ) );
}
else
{
schemaObject.setEnabled( schema.isEnabled() );
}
// The specification field
/*
* TODO : create the M_SPECIFICATION_AT
EntryAttribute mSpecification = entry.get( MetaSchemaConstants.M_SPECIFICATION_AT );
if ( mSpecification != null )
{
so.setSpecification( mSpecification.getString() );
}
*/
// The schemaName field
schemaObject.setSchemaName( schema.getSchemaName() );
// The extensions fields
// X-SCHEMA
Attribute xSchema = entry.get( MetaSchemaConstants.X_SCHEMA_AT );
if ( xSchema != null )
{
String schemaName = xSchema.getString();
if ( !schema.getSchemaName().equalsIgnoreCase( schemaName ) )
{
if ( LOG.isWarnEnabled() )
{
LOG.warn( I18n.msg( I18n.MSG_16011_SCHEMA_XSCHEMA_DIFF, schema.getSchemaName(), schemaName, entry ) );
}
}
schemaObject.addExtension( MetaSchemaConstants.X_SCHEMA_AT, schemaName );
}
// X-NOT-HUMAN-READABLE
Attribute xNotHumanReadable = entry.get( MetaSchemaConstants.X_NOT_HUMAN_READABLE_AT );
if ( xNotHumanReadable != null )
{
String value = xNotHumanReadable.getString();
schemaObject.addExtension( MetaSchemaConstants.X_NOT_HUMAN_READABLE_AT, value );
}
// X-READ-ONLY
Attribute xReadOnly = entry.get( MetaSchemaConstants.X_READ_ONLY_AT );
if ( xReadOnly != null )
{
String value = xReadOnly.getString();
schemaObject.addExtension( MetaSchemaConstants.X_READ_ONLY_AT, value );
}
}
/**
* Process the common attributes to all SchemaObjects :
* - obsolete
* - description
* - names
* - schemaName
* - specification (if any)
* - extensions
* - isReadOnly
* - isEnabled
*
* @param schemaObject The SchemaObject to set
* @param description The SchemaObjetc description
* @param schema the updated Schema
*/
private void setSchemaObjectProperties( SchemaObject schemaObject, SchemaObject description, Schema schema )
{
// The isObsolete field
schemaObject.setObsolete( description.isObsolete() );
// The description field
schemaObject.setDescription( description.getDescription() );
// The names field
schemaObject.setNames( description.getNames() );
// The isEnabled field. Has the description does not hold a
// Disable field, we will inherit from the schema enable field
schemaObject.setEnabled( schema.isEnabled() );
// The isReadOnly field. We don't have this data in the description,
// so set it to false
// TODO : should it be a X-READONLY extension ?
schemaObject.setReadOnly( false );
// The specification field
schemaObject.setSpecification( description.getSpecification() );
// The schemaName field
schemaObject.setSchemaName( schema.getSchemaName() );
// The extensions field
schemaObject.setExtensions( description.getExtensions() );
}
}
|
package it.linksmt.cts2.plugin.sti.db.model;
// Generated 24.10.2011 10:08:21 by Hibernate Tools 3.2.1.GA
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "code_system_entity_version"
)
public class CodeSystemEntityVersion implements java.io.Serializable
{
private Long versionId;
private CodeSystemEntity codeSystemEntity;
private Long previousVersionId;
private Integer statusVisibility;
private Date statusVisibilityDate;
private Integer statusDeactivated;
private Date statusDeactivatedDate;
private Integer statusWorkflow;
private Date statusWorkflowDate;
private Date effectiveDate;
private Integer majorRevision;
private Integer minorRevision;
private Date insertTimestamp;
private Boolean isLeaf;
private Set<CodeSystemEntityVersionAssociation> codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1 = new HashSet<CodeSystemEntityVersionAssociation>(0);
private Set<CodeSystemConcept> codeSystemConcepts = new HashSet<CodeSystemConcept>(0);
private Set<CodeSystemEntityVersionAssociation> codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2 = new HashSet<CodeSystemEntityVersionAssociation>(0);
private Set<ConceptValueSetMembership> conceptValueSetMemberships = new HashSet<ConceptValueSetMembership>(0);
private Set<CodeSystemMetadataValue> codeSystemMetadataValues = new HashSet<CodeSystemMetadataValue>(0);
private Set<ValueSetMetadataValue> valueSetMetadataValues = new HashSet<ValueSetMetadataValue>(0);
public CodeSystemEntityVersion()
{
}
public CodeSystemEntityVersion cloneObject()
{
CodeSystemEntityVersion csev = new CodeSystemEntityVersion(versionId, previousVersionId, statusVisibility, statusVisibilityDate, statusDeactivated, statusDeactivatedDate, statusWorkflow, statusWorkflowDate, effectiveDate, majorRevision, minorRevision, insertTimestamp, isLeaf);
if(csev.getStatusDeactivatedDate() == null) {
csev.setStatusDeactivatedDate(new Date());
}
if(csev.getStatusWorkflowDate()== null) {
csev.setStatusWorkflowDate(new Date());
}
return csev;
}
public CodeSystemEntityVersion(final Long versionId, final Long previousVersionId, final Integer statusVisibility, final Date statusVisibilityDate, final Integer statusDeactivated, final Date statusDeactivatedDate, final Integer statusWorkflow, final Date statusWorkflowDate, final Date effectiveDate, final Integer majorRevision, final Integer minorRevision, final Date insertTimestamp, final Boolean isLeaf)
{
this.versionId = versionId;
this.previousVersionId = previousVersionId;
this.statusVisibility = statusVisibility;
this.statusVisibilityDate = statusVisibilityDate;
this.statusDeactivated = statusDeactivated;
this.statusDeactivatedDate = statusDeactivatedDate;
this.statusWorkflow = statusWorkflow;
this.statusWorkflowDate = statusWorkflowDate;
this.effectiveDate = effectiveDate;
this.majorRevision = majorRevision;
this.minorRevision = minorRevision;
this.insertTimestamp = insertTimestamp;
this.isLeaf = isLeaf;
}
public CodeSystemEntityVersion(final CodeSystemEntity codeSystemEntity, final Integer status, final Date statusDate, final Date insertTimestamp)
{
this.codeSystemEntity = codeSystemEntity;
this.statusVisibility = status;
this.statusVisibilityDate = statusDate;
this.insertTimestamp = insertTimestamp;
}
public CodeSystemEntityVersion(final CodeSystemEntity codeSystemEntity, final Long previousVersionId, final Integer status, final Date statusDate, final Date effectiveDate, final Integer majorRevision, final Integer minorRevision, final Date insertTimestamp, final Set<CodeSystemEntityVersionAssociation> codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1, final Set<CodeSystemConcept> codeSystemConcepts, final Set<CodeSystemEntityVersionAssociation> codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2, final Set<ConceptValueSetMembership> conceptValueSetMemberships, final Set<CodeSystemMetadataValue> codeSystemMetadataValues)
{
this.codeSystemEntity = codeSystemEntity;
this.previousVersionId = previousVersionId;
this.statusVisibility = status;
this.statusVisibilityDate = statusDate;
this.effectiveDate = effectiveDate;
this.majorRevision = majorRevision;
this.minorRevision = minorRevision;
this.insertTimestamp = insertTimestamp;
this.codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1 = codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1;
this.codeSystemConcepts = codeSystemConcepts;
this.codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2 = codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2;
this.conceptValueSetMemberships = conceptValueSetMemberships;
this.codeSystemMetadataValues = codeSystemMetadataValues;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "versionId", unique = true, nullable = false)
public Long getVersionId()
{
return this.versionId;
}
public void setVersionId(final Long versionId)
{
this.versionId = versionId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "codeSystemEntityId", nullable = false)
public CodeSystemEntity getCodeSystemEntity()
{
return this.codeSystemEntity;
}
public void setCodeSystemEntity(final CodeSystemEntity codeSystemEntity)
{
this.codeSystemEntity = codeSystemEntity;
}
@Column(name = "isLeaf")
public Boolean getIsLeaf()
{
return this.isLeaf;
}
public void setIsLeaf(final Boolean isLeaf)
{
this.isLeaf = isLeaf;
}
@Column(name = "previousVersionId")
public Long getPreviousVersionId()
{
return this.previousVersionId;
}
public void setPreviousVersionId(final Long previousVersionId)
{
this.previousVersionId = previousVersionId;
}
@Column(name = "statusVisibility", nullable = false)
public Integer getStatusVisibility()
{
return this.statusVisibility;
}
public void setStatusVisibility(final Integer status)
{
this.statusVisibility = status;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "statusVisibilityDate", nullable = false, length = 19)
public Date getStatusVisibilityDate()
{
return this.statusVisibilityDate;
}
public void setStatusVisibilityDate(final Date statusDate)
{
this.statusVisibilityDate = statusDate;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "effectiveDate", length = 19)
public Date getEffectiveDate()
{
return this.effectiveDate;
}
public void setEffectiveDate(final Date effectiveDate)
{
this.effectiveDate = effectiveDate;
}
@Column(name = "majorRevision")
public Integer getMajorRevision()
{
return this.majorRevision;
}
public void setMajorRevision(final Integer majorRevision)
{
this.majorRevision = majorRevision;
}
@Column(name = "minorRevision")
public Integer getMinorRevision()
{
return this.minorRevision;
}
public void setMinorRevision(final Integer minorRevision)
{
this.minorRevision = minorRevision;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "insertTimestamp", nullable = false, length = 19)
public Date getInsertTimestamp()
{
return this.insertTimestamp;
}
public void setInsertTimestamp(final Date insertTimestamp)
{
this.insertTimestamp = insertTimestamp;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "codeSystemEntityVersionByCodeSystemEntityVersionId1")
public Set<CodeSystemEntityVersionAssociation> getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1()
{
return this.codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1;
}
public void setCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1(final Set<CodeSystemEntityVersionAssociation> codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1)
{
this.codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1 = codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId1;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "codeSystemEntityVersion")
public Set<CodeSystemConcept> getCodeSystemConcepts()
{
return this.codeSystemConcepts;
}
public void setCodeSystemConcepts(final Set<CodeSystemConcept> codeSystemConcepts)
{
this.codeSystemConcepts = codeSystemConcepts;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "codeSystemEntityVersionByCodeSystemEntityVersionId2")
public Set<CodeSystemEntityVersionAssociation> getCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2()
{
return this.codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2;
}
public void setCodeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2(final Set<CodeSystemEntityVersionAssociation> codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2)
{
this.codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2 = codeSystemEntityVersionAssociationsForCodeSystemEntityVersionId2;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "codeSystemEntityVersion")
public Set<ConceptValueSetMembership> getConceptValueSetMemberships()
{
return this.conceptValueSetMemberships;
}
public void setConceptValueSetMemberships(final Set<ConceptValueSetMembership> conceptValueSetMemberships)
{
this.conceptValueSetMemberships = conceptValueSetMemberships;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "codeSystemEntityVersion")
public Set<CodeSystemMetadataValue> getCodeSystemMetadataValues()
{
return this.codeSystemMetadataValues;
}
public void setCodeSystemMetadataValues(final Set<CodeSystemMetadataValue> codeSystemMetadataValues)
{
this.codeSystemMetadataValues = codeSystemMetadataValues;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "codeSystemEntityVersion")
public Set<ValueSetMetadataValue> getValueSetMetadataValues()
{
return this.valueSetMetadataValues;
}
public void setValueSetMetadataValues(final Set<ValueSetMetadataValue> valueSetMetadataValues)
{
this.valueSetMetadataValues = valueSetMetadataValues;
}
@Column(name = "statusDeactivated", nullable = false)
public Integer getStatusDeactivated()
{
return this.statusDeactivated;
}
public void setStatusDeactivated(final Integer status)
{
this.statusDeactivated = status;
}
@Column(name = "statusWorkflow", nullable = false)
public Integer getStatusWorkflow()
{
return this.statusWorkflow;
}
public void setStatusWorkflow(final Integer status)
{
this.statusWorkflow = status;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "statusDeactivatedDate", nullable = false, length = 19)
public Date getStatusDeactivatedDate()
{
return this.statusDeactivatedDate;
}
public void setStatusDeactivatedDate(final Date statusDate)
{
this.statusDeactivatedDate = statusDate;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "statusWorkflowDate", nullable = false, length = 19)
public Date getStatusWorkflowDate()
{
return this.statusWorkflowDate;
}
public void setStatusWorkflowDate(final Date statusDate)
{
this.statusWorkflowDate = statusDate;
}
}
|
package xyz.mengnan.MNSockets.patch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.mengnan.MNSockets.utils.JsonUtil;
import java.sql.SQLException;
@ControllerAdvice
@Slf4j
public class SysExceptionHandler {
@ExceptionHandler(value = NullPointerException.class)
@ResponseBody
public JsonUtil exceptionHandler(NullPointerException e) {
log.error(e.getMessage(), e);
return JsonUtil.err("服务器错误", e);
}
@ExceptionHandler(value = SQLException.class)
@ResponseBody
public JsonUtil exceptionHandler(SQLException e) {
log.error(e.getMessage(), e);
return JsonUtil.err("服务器错误", e);
}
}
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 com.google.ads.googleads.v3.services;
import com.google.ads.googleads.v3.resources.FeedPlaceholderView;
import com.google.ads.googleads.v3.services.FeedPlaceholderViewServiceGrpc.FeedPlaceholderViewServiceImplBase;
import com.google.api.core.BetaApi;
import com.google.protobuf.AbstractMessage;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
@javax.annotation.Generated("by GAPIC")
@BetaApi
public class MockFeedPlaceholderViewServiceImpl extends FeedPlaceholderViewServiceImplBase {
private List<AbstractMessage> requests;
private Queue<Object> responses;
public MockFeedPlaceholderViewServiceImpl() {
requests = new ArrayList<>();
responses = new LinkedList<>();
}
public List<AbstractMessage> getRequests() {
return requests;
}
public void addResponse(AbstractMessage response) {
responses.add(response);
}
public void setResponses(List<AbstractMessage> responses) {
this.responses = new LinkedList<Object>(responses);
}
public void addException(Exception exception) {
responses.add(exception);
}
public void reset() {
requests = new ArrayList<>();
responses = new LinkedList<>();
}
@Override
public void getFeedPlaceholderView(
GetFeedPlaceholderViewRequest request, StreamObserver<FeedPlaceholderView> responseObserver) {
Object response = responses.remove();
if (response instanceof FeedPlaceholderView) {
requests.add(request);
responseObserver.onNext((FeedPlaceholderView) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
}
|
/**
* 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.yarn.server.resourcemanager.scheduler.capacity;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueInfo;
import org.apache.hadoop.yarn.api.records.QueueState;
import org.apache.hadoop.yarn.api.records.QueueStatistics;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.security.AccessType;
import org.apache.hadoop.yarn.security.PrivilegedEntity;
import org.apache.hadoop.yarn.security.PrivilegedEntity.EntityType;
import org.apache.hadoop.yarn.security.YarnAuthorizationProvider;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceUsage;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;
import com.google.common.collect.Sets;
public abstract class AbstractCSQueue implements CSQueue {
private static final Log LOG = LogFactory.getLog(AbstractCSQueue.class);
CSQueue parent;
final String queueName;
volatile int numContainers;
final Resource minimumAllocation;
volatile Resource maximumAllocation;
QueueState state;
final CSQueueMetrics metrics;
protected final PrivilegedEntity queueEntity;
final ResourceCalculator resourceCalculator;
Set<String> accessibleLabels;
RMNodeLabelsManager labelManager;
String defaultLabelExpression;
Map<AccessType, AccessControlList> acls =
new HashMap<AccessType, AccessControlList>();
volatile boolean reservationsContinueLooking;
private boolean preemptionDisabled;
// Track resource usage-by-label like used-resource/pending-resource, etc.
ResourceUsage queueUsage;
// Track capacities like used-capcity/abs-used-capacity/capacity/abs-capacity,
// etc.
QueueCapacities queueCapacities;
private final RecordFactory recordFactory =
RecordFactoryProvider.getRecordFactory(null);
protected CapacitySchedulerContext csContext;
protected YarnAuthorizationProvider authorizer = null;
public AbstractCSQueue(CapacitySchedulerContext cs,
String queueName, CSQueue parent, CSQueue old) throws IOException {
this.labelManager = cs.getRMContext().getNodeLabelManager();
this.parent = parent;
this.queueName = queueName;
this.resourceCalculator = cs.getResourceCalculator();
// must be called after parent and queueName is set
this.metrics =
old != null ? (CSQueueMetrics) old.getMetrics() : CSQueueMetrics
.forQueue(getQueuePath(), parent, cs.getConfiguration()
.getEnableUserMetrics(), cs.getConf());
this.csContext = cs;
this.minimumAllocation = csContext.getMinimumResourceCapability();
// initialize ResourceUsage
queueUsage = new ResourceUsage();
queueEntity = new PrivilegedEntity(EntityType.QUEUE, getQueuePath());
// initialize QueueCapacities
queueCapacities = new QueueCapacities(parent == null);
}
protected void setupConfigurableCapacities() {
CSQueueUtils.loadUpdateAndCheckCapacities(
getQueuePath(),
csContext.getConfiguration(),
queueCapacities,
parent == null ? null : parent.getQueueCapacities());
}
@Override
public synchronized float getCapacity() {
return queueCapacities.getCapacity();
}
@Override
public synchronized float getAbsoluteCapacity() {
return queueCapacities.getAbsoluteCapacity();
}
@Override
public float getAbsoluteMaximumCapacity() {
return queueCapacities.getAbsoluteMaximumCapacity();
}
@Override
public synchronized float getAbsoluteUsedCapacity() {
return queueCapacities.getAbsoluteUsedCapacity();
}
@Override
public float getMaximumCapacity() {
return queueCapacities.getMaximumCapacity();
}
@Override
public synchronized float getUsedCapacity() {
return queueCapacities.getUsedCapacity();
}
@Override
public Resource getUsedResources() {
return queueUsage.getUsed();
}
public synchronized int getNumContainers() {
return numContainers;
}
@Override
public synchronized QueueState getState() {
return state;
}
@Override
public CSQueueMetrics getMetrics() {
return metrics;
}
@Override
public String getQueueName() {
return queueName;
}
public PrivilegedEntity getPrivilegedEntity() {
return queueEntity;
}
@Override
public synchronized CSQueue getParent() {
return parent;
}
@Override
public synchronized void setParent(CSQueue newParentQueue) {
this.parent = (ParentQueue)newParentQueue;
}
public Set<String> getAccessibleNodeLabels() {
return accessibleLabels;
}
@Override
public boolean hasAccess(QueueACL acl, UserGroupInformation user) {
return authorizer.checkPermission(SchedulerUtils.toAccessType(acl),
queueEntity, user);
}
@Override
public synchronized void setUsedCapacity(float usedCapacity) {
queueCapacities.setUsedCapacity(usedCapacity);
}
@Override
public synchronized void setAbsoluteUsedCapacity(float absUsedCapacity) {
queueCapacities.setAbsoluteUsedCapacity(absUsedCapacity);
}
/**
* Set maximum capacity - used only for testing.
* @param maximumCapacity new max capacity
*/
synchronized void setMaxCapacity(float maximumCapacity) {
// Sanity check
CSQueueUtils.checkMaxCapacity(getQueueName(),
queueCapacities.getCapacity(), maximumCapacity);
float absMaxCapacity =
CSQueueUtils.computeAbsoluteMaximumCapacity(maximumCapacity, parent);
CSQueueUtils.checkAbsoluteCapacity(getQueueName(),
queueCapacities.getAbsoluteCapacity(),
absMaxCapacity);
queueCapacities.setMaximumCapacity(maximumCapacity);
queueCapacities.setAbsoluteMaximumCapacity(absMaxCapacity);
}
@Override
public String getDefaultNodeLabelExpression() {
return defaultLabelExpression;
}
synchronized void setupQueueConfigs(Resource clusterResource)
throws IOException {
// get labels
this.accessibleLabels =
csContext.getConfiguration().getAccessibleNodeLabels(getQueuePath());
this.defaultLabelExpression = csContext.getConfiguration()
.getDefaultNodeLabelExpression(getQueuePath());
// inherit from parent if labels not set
if (this.accessibleLabels == null && parent != null) {
this.accessibleLabels = parent.getAccessibleNodeLabels();
}
// inherit from parent if labels not set
if (this.defaultLabelExpression == null && parent != null
&& this.accessibleLabels.containsAll(parent.getAccessibleNodeLabels())) {
this.defaultLabelExpression = parent.getDefaultNodeLabelExpression();
}
// After we setup labels, we can setup capacities
setupConfigurableCapacities();
this.maximumAllocation =
csContext.getConfiguration().getMaximumAllocationPerQueue(
getQueuePath());
authorizer = YarnAuthorizationProvider.getInstance(csContext.getConf());
this.state = csContext.getConfiguration().getState(getQueuePath());
this.acls = csContext.getConfiguration().getAcls(getQueuePath());
// Update metrics
CSQueueUtils.updateQueueStatistics(resourceCalculator, clusterResource,
minimumAllocation, this, labelManager, null);
// Check if labels of this queue is a subset of parent queue, only do this
// when we not root
if (parent != null && parent.getParent() != null) {
if (parent.getAccessibleNodeLabels() != null
&& !parent.getAccessibleNodeLabels().contains(RMNodeLabelsManager.ANY)) {
// if parent isn't "*", child shouldn't be "*" too
if (this.getAccessibleNodeLabels().contains(RMNodeLabelsManager.ANY)) {
throw new IOException("Parent's accessible queue is not ANY(*), "
+ "but child's accessible queue is *");
} else {
Set<String> diff =
Sets.difference(this.getAccessibleNodeLabels(),
parent.getAccessibleNodeLabels());
if (!diff.isEmpty()) {
throw new IOException("Some labels of child queue is not a subset "
+ "of parent queue, these labels=["
+ StringUtils.join(diff, ",") + "]");
}
}
}
}
this.reservationsContinueLooking = csContext.getConfiguration()
.getReservationContinueLook();
this.preemptionDisabled = isQueueHierarchyPreemptionDisabled(this);
}
protected QueueInfo getQueueInfo() {
QueueInfo queueInfo = recordFactory.newRecordInstance(QueueInfo.class);
queueInfo.setQueueName(queueName);
queueInfo.setAccessibleNodeLabels(accessibleLabels);
queueInfo.setCapacity(queueCapacities.getCapacity());
queueInfo.setMaximumCapacity(queueCapacities.getMaximumCapacity());
queueInfo.setQueueState(state);
queueInfo.setDefaultNodeLabelExpression(defaultLabelExpression);
queueInfo.setCurrentCapacity(getUsedCapacity());
queueInfo.setQueueStatistics(getQueueStatistics());
return queueInfo;
}
public QueueStatistics getQueueStatistics() {
QueueStatistics stats =
recordFactory.newRecordInstance(QueueStatistics.class);
stats.setNumAppsSubmitted(getMetrics().getAppsSubmitted());
stats.setNumAppsRunning(getMetrics().getAppsRunning());
stats.setNumAppsPending(getMetrics().getAppsPending());
stats.setNumAppsCompleted(getMetrics().getAppsCompleted());
stats.setNumAppsKilled(getMetrics().getAppsKilled());
stats.setNumAppsFailed(getMetrics().getAppsFailed());
stats.setNumActiveUsers(getMetrics().getActiveUsers());
stats.setAvailableMemoryMB(getMetrics().getAvailableMB());
stats.setAllocatedMemoryMB(getMetrics().getAllocatedMB());
stats.setPendingMemoryMB(getMetrics().getPendingMB());
stats.setReservedMemoryMB(getMetrics().getReservedMB());
stats.setAvailableVCores(getMetrics().getAvailableVirtualCores());
stats.setAllocatedVCores(getMetrics().getAllocatedVirtualCores());
stats.setPendingVCores(getMetrics().getPendingVirtualCores());
stats.setReservedVCores(getMetrics().getReservedVirtualCores());
stats.setPendingContainers(getMetrics().getPendingContainers());
stats.setAllocatedContainers(getMetrics().getAllocatedContainers());
stats.setReservedContainers(getMetrics().getReservedContainers());
return stats;
}
@Private
public Resource getMaximumAllocation() {
return maximumAllocation;
}
@Private
public Resource getMinimumAllocation() {
return minimumAllocation;
}
synchronized void allocateResource(Resource clusterResource,
Resource resource, String nodePartition) {
queueUsage.incUsed(nodePartition, resource);
++numContainers;
CSQueueUtils.updateQueueStatistics(resourceCalculator, clusterResource,
minimumAllocation, this, labelManager, nodePartition);
}
protected synchronized void releaseResource(Resource clusterResource,
Resource resource, String nodePartition) {
queueUsage.decUsed(nodePartition, resource);
CSQueueUtils.updateQueueStatistics(resourceCalculator, clusterResource,
minimumAllocation, this, labelManager, nodePartition);
--numContainers;
}
@Private
public boolean getReservationContinueLooking() {
return reservationsContinueLooking;
}
@Private
public Map<AccessType, AccessControlList> getACLs() {
return acls;
}
@Private
public boolean getPreemptionDisabled() {
return preemptionDisabled;
}
@Private
public QueueCapacities getQueueCapacities() {
return queueCapacities;
}
@Private
public ResourceUsage getQueueResourceUsage() {
return queueUsage;
}
/**
* The specified queue is preemptable if system-wide preemption is turned on
* unless any queue in the <em>qPath</em> hierarchy has explicitly turned
* preemption off.
* NOTE: Preemptability is inherited from a queue's parent.
*
* @return true if queue has preemption disabled, false otherwise
*/
private boolean isQueueHierarchyPreemptionDisabled(CSQueue q) {
CapacitySchedulerConfiguration csConf = csContext.getConfiguration();
boolean systemWidePreemption =
csConf.getBoolean(YarnConfiguration.RM_SCHEDULER_ENABLE_MONITORS,
YarnConfiguration.DEFAULT_RM_SCHEDULER_ENABLE_MONITORS);
CSQueue parentQ = q.getParent();
// If the system-wide preemption switch is turned off, all of the queues in
// the qPath hierarchy have preemption disabled, so return true.
if (!systemWidePreemption) return true;
// If q is the root queue and the system-wide preemption switch is turned
// on, then q does not have preemption disabled (default=false, below)
// unless the preemption_disabled property is explicitly set.
if (parentQ == null) {
return csConf.getPreemptionDisabled(q.getQueuePath(), false);
}
// If this is not the root queue, inherit the default value for the
// preemption_disabled property from the parent. Preemptability will be
// inherited from the parent's hierarchy unless explicitly overridden at
// this level.
return csConf.getPreemptionDisabled(q.getQueuePath(),
parentQ.getPreemptionDisabled());
}
private Resource getCurrentLimitResource(String nodePartition,
Resource clusterResource, ResourceLimits currentResourceLimits,
SchedulingMode schedulingMode) {
if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY) {
/*
* Current limit resource: For labeled resource: limit = queue-max-resource
* (TODO, this part need update when we support labeled-limit) For
* non-labeled resource: limit = min(queue-max-resource,
* limit-set-by-parent)
*/
Resource queueMaxResource =
Resources.multiplyAndNormalizeDown(resourceCalculator,
labelManager.getResourceByLabel(nodePartition, clusterResource),
queueCapacities.getAbsoluteMaximumCapacity(nodePartition), minimumAllocation);
if (nodePartition.equals(RMNodeLabelsManager.NO_LABEL)) {
return Resources.min(resourceCalculator, clusterResource,
queueMaxResource, currentResourceLimits.getLimit());
}
return queueMaxResource;
} else if (schedulingMode == SchedulingMode.IGNORE_PARTITION_EXCLUSIVITY) {
// When we doing non-exclusive resource allocation, maximum capacity of
// all queues on this label equals to total resource with the label.
return labelManager.getResourceByLabel(nodePartition, clusterResource);
}
return Resources.none();
}
synchronized boolean canAssignToThisQueue(Resource clusterResource,
String nodePartition, ResourceLimits currentResourceLimits, Resource resourceCouldBeUnreserved,
SchedulingMode schedulingMode) {
// Get current limited resource:
// - When doing RESPECT_PARTITION_EXCLUSIVITY allocation, we will respect
// queues' max capacity.
// - When doing IGNORE_PARTITION_EXCLUSIVITY allocation, we will not respect
// queue's max capacity, queue's max capacity on the partition will be
// considered to be 100%. Which is a queue can use all resource in the
// partition.
// Doing this because: for non-exclusive allocation, we make sure there's
// idle resource on the partition, to avoid wastage, such resource will be
// leveraged as much as we can, and preemption policy will reclaim it back
// when partitoned-resource-request comes back.
Resource currentLimitResource =
getCurrentLimitResource(nodePartition, clusterResource,
currentResourceLimits, schedulingMode);
Resource nowTotalUsed = queueUsage.getUsed(nodePartition);
// Set headroom for currentResourceLimits
currentResourceLimits.setHeadroom(Resources.subtract(currentLimitResource,
nowTotalUsed));
if (Resources.greaterThanOrEqual(resourceCalculator, clusterResource,
nowTotalUsed, currentLimitResource)) {
// if reservation continous looking enabled, check to see if could we
// potentially use this node instead of a reserved node if the application
// has reserved containers.
// TODO, now only consider reservation cases when the node has no label
if (this.reservationsContinueLooking
&& nodePartition.equals(RMNodeLabelsManager.NO_LABEL)
&& Resources.greaterThan(resourceCalculator, clusterResource,
resourceCouldBeUnreserved, Resources.none())) {
// resource-without-reserved = used - reserved
Resource newTotalWithoutReservedResource =
Resources.subtract(nowTotalUsed, resourceCouldBeUnreserved);
// when total-used-without-reserved-resource < currentLimit, we still
// have chance to allocate on this node by unreserving some containers
if (Resources.lessThan(resourceCalculator, clusterResource,
newTotalWithoutReservedResource, currentLimitResource)) {
if (LOG.isDebugEnabled()) {
LOG.debug("try to use reserved: " + getQueueName()
+ " usedResources: " + queueUsage.getUsed()
+ ", clusterResources: " + clusterResource
+ ", reservedResources: " + resourceCouldBeUnreserved
+ ", capacity-without-reserved: "
+ newTotalWithoutReservedResource + ", maxLimitCapacity: "
+ currentLimitResource);
}
return true;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug(getQueueName()
+ "Check assign to queue, nodePartition="
+ nodePartition
+ " usedResources: "
+ queueUsage.getUsed(nodePartition)
+ " clusterResources: "
+ clusterResource
+ " currentUsedCapacity "
+ Resources.divide(resourceCalculator, clusterResource,
queueUsage.getUsed(nodePartition),
labelManager.getResourceByLabel(nodePartition, clusterResource))
+ " max-capacity: "
+ queueCapacities.getAbsoluteMaximumCapacity(nodePartition) + ")");
}
return false;
}
return true;
}
@Override
public void incPendingResource(String nodeLabel, Resource resourceToInc) {
if (nodeLabel == null) {
nodeLabel = RMNodeLabelsManager.NO_LABEL;
}
// ResourceUsage has its own lock, no addition lock needs here.
queueUsage.incPending(nodeLabel, resourceToInc);
if (null != parent) {
parent.incPendingResource(nodeLabel, resourceToInc);
}
}
@Override
public void decPendingResource(String nodeLabel, Resource resourceToDec) {
if (nodeLabel == null) {
nodeLabel = RMNodeLabelsManager.NO_LABEL;
}
// ResourceUsage has its own lock, no addition lock needs here.
queueUsage.decPending(nodeLabel, resourceToDec);
if (null != parent) {
parent.decPendingResource(nodeLabel, resourceToDec);
}
}
/**
* Return if the queue has pending resource on given nodePartition and
* schedulingMode.
*/
boolean hasPendingResourceRequest(String nodePartition,
Resource cluster, SchedulingMode schedulingMode) {
return SchedulerUtils.hasPendingResourceRequest(resourceCalculator,
queueUsage, nodePartition, cluster, schedulingMode);
}
public boolean accessibleToPartition(String nodePartition) {
// if queue's label is *, it can access any node
if (accessibleLabels != null
&& accessibleLabels.contains(RMNodeLabelsManager.ANY)) {
return true;
}
// any queue can access to a node without label
if (nodePartition == null
|| nodePartition.equals(RMNodeLabelsManager.NO_LABEL)) {
return true;
}
// a queue can access to a node only if it contains any label of the node
if (accessibleLabels != null && accessibleLabels.contains(nodePartition)) {
return true;
}
// sorry, you cannot access
return false;
}
@Override
public Priority getDefaultApplicationPriority() {
// TODO add dummy implementation
return null;
}
}
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.license;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.Logger;
import org.dspace.services.ConfigurationService;
import org.jaxen.JaxenException;
import org.jaxen.jdom.JDOMXPath;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.xml.sax.InputSource;
/**
* Implementation for the Creative commons license connector service.
* This class is responsible for all the calls to the CC license API and parsing the response
*/
public class CCLicenseConnectorServiceImpl implements CCLicenseConnectorService, InitializingBean {
private Logger log = org.apache.logging.log4j.LogManager.getLogger(CCLicenseConnectorServiceImpl.class);
private CloseableHttpClient client;
protected SAXBuilder parser = new SAXBuilder();
private String postArgument = "answers";
private String postAnswerFormat =
"<answers> " +
"<locale>{1}</locale>" +
"<license-{0}>" +
"{2}" +
"</license-{0}>" +
"</answers>";
@Autowired
private ConfigurationService configurationService;
@Override
public void afterPropertiesSet() throws Exception {
HttpClientBuilder builder = HttpClientBuilder.create();
client = builder
.disableAutomaticRetries()
.setMaxConnTotal(5)
.build();
// disallow DTD parsing to ensure no XXE attacks can occur.
// See https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
}
/**
* Retrieves the CC Licenses for the provided language from the CC License API
*
* @param language - the language to retrieve the licenses for
* @return a map of licenses with the id and the license for the provided language
*/
public Map<String, CCLicense> retrieveLicenses(String language) {
String ccLicenseUrl = configurationService.getProperty("cc.api.rooturl");
String uri = ccLicenseUrl + "/?locale=" + language;
HttpGet httpGet = new HttpGet(uri);
List<String> licenses;
try (CloseableHttpResponse response = client.execute(httpGet)) {
licenses = retrieveLicenses(response);
} catch (JDOMException | JaxenException | IOException e) {
log.error("Error while retrieving the license details using url: " + uri, e);
licenses = Collections.emptyList();
}
Map<String, CCLicense> ccLicenses = new HashMap<>();
for (String license : licenses) {
String licenseUri = ccLicenseUrl + "/license/" + license;
HttpGet licenseHttpGet = new HttpGet(licenseUri);
try (CloseableHttpResponse response = client.execute(licenseHttpGet)) {
CCLicense ccLicense = retrieveLicenseObject(license, response);
ccLicenses.put(ccLicense.getLicenseId(), ccLicense);
} catch (JaxenException | JDOMException | IOException e) {
log.error("Error while retrieving the license details using url: " + licenseUri, e);
}
}
return ccLicenses;
}
/**
* Retrieve the list of licenses from the response from the CC License API and remove the licenses configured
* to be excluded
*
* @param response The response from the API
* @return a list of license identifiers for which details need to be retrieved
* @throws IOException
* @throws JaxenException
* @throws JDOMException
*/
private List<String> retrieveLicenses(CloseableHttpResponse response)
throws IOException, JaxenException, JDOMException {
List<String> domains = new LinkedList<>();
String[] excludedLicenses = configurationService.getArrayProperty("cc.license.classfilter");
String responseString = EntityUtils.toString(response.getEntity());
JDOMXPath licenseClassXpath = new JDOMXPath("//licenses/license");
try (StringReader stringReader = new StringReader(responseString)) {
InputSource is = new InputSource(stringReader);
org.jdom.Document classDoc = this.parser.build(is);
List<Element> elements = licenseClassXpath.selectNodes(classDoc);
for (Element element : elements) {
String licenseId = getSingleNodeValue(element, "@id");
if (StringUtils.isNotBlank(licenseId) && !ArrayUtils.contains(excludedLicenses, licenseId)) {
domains.add(licenseId);
}
}
}
return domains;
}
/**
* Parse the response for a single CC License and return the corresponding CC License Object
*
* @param licenseId the license id of the CC License to retrieve
* @param response for a specific CC License response
* @return the corresponding CC License Object
* @throws IOException
* @throws JaxenException
* @throws JDOMException
*/
private CCLicense retrieveLicenseObject(final String licenseId, CloseableHttpResponse response)
throws IOException, JaxenException, JDOMException {
String responseString = EntityUtils.toString(response.getEntity());
JDOMXPath licenseClassXpath = new JDOMXPath("//licenseclass");
JDOMXPath licenseFieldXpath = new JDOMXPath("field");
try (StringReader stringReader = new StringReader(responseString)) {
InputSource is = new InputSource(stringReader);
org.jdom.Document classDoc = this.parser.build(is);
Object element = licenseClassXpath.selectSingleNode(classDoc);
String licenseLabel = getSingleNodeValue(element, "label");
List<CCLicenseField> ccLicenseFields = new LinkedList<>();
List<Element> licenseFields = licenseFieldXpath.selectNodes(element);
for (Element licenseField : licenseFields) {
CCLicenseField ccLicenseField = parseLicenseField(licenseField);
ccLicenseFields.add(ccLicenseField);
}
return new CCLicense(licenseId, licenseLabel, ccLicenseFields);
}
}
private CCLicenseField parseLicenseField(final Element licenseField) throws JaxenException {
String id = getSingleNodeValue(licenseField, "@id");
String label = getSingleNodeValue(licenseField, "label");
String description = getSingleNodeValue(licenseField, "description");
JDOMXPath enumXpath = new JDOMXPath("enum");
List<Element> enums = enumXpath.selectNodes(licenseField);
List<CCLicenseFieldEnum> ccLicenseFieldEnumList = new LinkedList<>();
for (Element enumElement : enums) {
CCLicenseFieldEnum ccLicenseFieldEnum = parseEnum(enumElement);
ccLicenseFieldEnumList.add(ccLicenseFieldEnum);
}
return new CCLicenseField(id, label, description, ccLicenseFieldEnumList);
}
private CCLicenseFieldEnum parseEnum(final Element enumElement) throws JaxenException {
String id = getSingleNodeValue(enumElement, "@id");
String label = getSingleNodeValue(enumElement, "label");
String description = getSingleNodeValue(enumElement, "description");
return new CCLicenseFieldEnum(id, label, description);
}
private String getNodeValue(final Object el) {
if (el instanceof Element) {
return ((Element) el).getValue();
} else if (el instanceof Attribute) {
return ((Attribute) el).getValue();
} else if (el instanceof String) {
return (String) el;
} else {
return null;
}
}
private String getSingleNodeValue(final Object t, String query) throws JaxenException {
JDOMXPath xpath = new JDOMXPath(query);
Object singleNode = xpath.selectSingleNode(t);
return getNodeValue(singleNode);
}
/**
* Retrieve the CC License URI based on the provided license id, language and answers to the field questions from
* the CC License API
*
* @param licenseId - the ID of the license
* @param language - the language for which to retrieve the full answerMap
* @param answerMap - the answers to the different field questions
* @return the CC License URI
*/
public String retrieveRightsByQuestion(String licenseId,
String language,
Map<String, String> answerMap) {
String ccLicenseUrl = configurationService.getProperty("cc.api.rooturl");
HttpPost httpPost = new HttpPost(ccLicenseUrl + "/license/" + licenseId + "/issue");
String answers = createAnswerString(answerMap);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String text = MessageFormat.format(postAnswerFormat, licenseId, language, answers);
builder.addTextBody(postArgument, text);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try (CloseableHttpResponse response = client.execute(httpPost)) {
return retrieveLicenseUri(response);
} catch (JDOMException | JaxenException | IOException e) {
log.error("Error while retrieving the license uri for license : " + licenseId + " with answers "
+ answerMap.toString(), e);
}
return null;
}
/**
* Parse the response for the CC License URI request and return the corresponding CC License URI
*
* @param response for a specific CC License URI response
* @return the corresponding CC License URI as a string
* @throws IOException
* @throws JaxenException
* @throws JDOMException
*/
private String retrieveLicenseUri(final CloseableHttpResponse response)
throws IOException, JaxenException, JDOMException {
String responseString = EntityUtils.toString(response.getEntity());
JDOMXPath licenseClassXpath = new JDOMXPath("//result/license-uri");
try (StringReader stringReader = new StringReader(responseString)) {
InputSource is = new InputSource(stringReader);
org.jdom.Document classDoc = this.parser.build(is);
Object node = licenseClassXpath.selectSingleNode(classDoc);
String nodeValue = getNodeValue(node);
if (StringUtils.isNotBlank(nodeValue)) {
return nodeValue;
}
}
return null;
}
private String createAnswerString(final Map<String, String> parameterMap) {
StringBuilder sb = new StringBuilder();
for (String key : parameterMap.keySet()) {
sb.append("<");
sb.append(key);
sb.append(">");
sb.append(parameterMap.get(key));
sb.append("</");
sb.append(key);
sb.append(">");
}
return sb.toString();
}
/**
* Retrieve the license RDF document based on the license URI
*
* @param licenseURI - The license URI for which to retrieve the license RDF document
* @return the license RDF document
* @throws IOException
*/
@Override
public Document retrieveLicenseRDFDoc(String licenseURI) throws IOException {
String ccLicenseUrl = configurationService.getProperty("cc.api.rooturl");
String issueUrl = ccLicenseUrl + "/details?license-uri=" + licenseURI;
URL request_url;
try {
request_url = new URL(issueUrl);
} catch (MalformedURLException e) {
return null;
}
URLConnection connection = request_url.openConnection();
connection.setDoOutput(true);
try {
// parsing document from input stream
InputStream stream = connection.getInputStream();
Document doc = parser.build(stream);
return doc;
} catch (Exception e) {
log.error("Error while retrieving the license document for URI: " + licenseURI, e);
}
return null;
}
/**
* Retrieve the license Name from the license document
*
* @param doc - The license document from which to retrieve the license name
* @return the license name
*/
public String retrieveLicenseName(final Document doc) {
try {
return getSingleNodeValue(doc, "//result/license-name");
} catch (JaxenException e) {
log.error("Error while retrieving the license name from the license document", e);
}
return null;
}
}
|
package student_course;
public class Student {
private long rollnumber;
private String name;
public Student(String name)
{
this(name,0L);
}
public Student(String name, long number) {
this.name=name;
rollnumber=number;
}
@Override
public String toString() {
return "Student [rollnumber=" + rollnumber + ", name=" + name + "]";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public long getRollnumber() {
return rollnumber;
}
public void setRollnumber(long rollnumber) {
this.rollnumber = rollnumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.CashOnline.services;
import com.CashOnline.dto.UserCreateRequestDto;
import com.CashOnline.exceptions.UserAlreadyExistsException;
import com.CashOnline.exceptions.UserNotFoundException;
import com.CashOnline.model.User;
import com.CashOnline.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collection;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getById(Long id) throws UserNotFoundException {
return userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException("User with id " + id + " not found"));
}
public Collection<User> getAll() {
return userRepository.findAll();
}
public User create(UserCreateRequestDto userCreateRequestDto) throws UserAlreadyExistsException {
if (userRepository.findByEmail(userCreateRequestDto.getEmail()).isPresent()) {
throw new UserAlreadyExistsException("User with email " + userCreateRequestDto.getEmail() + " already exists");
}
return userRepository.save(new User(userCreateRequestDto.getEmail(),
userCreateRequestDto.getFirstName(),
userCreateRequestDto.getLastName()));
}
public void deleteById(Long id) throws UserNotFoundException {
if (userRepository.findById(id).isEmpty()) {
throw new UserNotFoundException("User with id " + id + " not found");
}
userRepository.deleteById(id);
}
}
|
package CustomExceptionClass;
import java.util.Scanner;
public class PhoneTest {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
boolean loop=true;
while(loop==true)
{
System.out.println("Vendos emrin");
String emer=in.next();
System.out.println("Vendos numrin e telefonit");
String nrTelefoni=in.next();
try {
Phone telefon=new Phone(emer, nrTelefoni);
}
catch(ValidationException ve){
System.out.printf("Ndodhi nje gabim %s%n", ve);
}
finally {
}
System.out.println("\nVendos true nese do te vazhdosh perndryshe false");
loop=in.nextBoolean();
}
}
}
|
package com.vladsch.clionarduinoplugin.serial;
import org.jetbrains.annotations.NotNull;
public interface BuildListener {
void beforeBuildStarted(@NotNull final String targetName);
void afterBuildFinished(final boolean buildSuccess);
}
|
package cn.xpbootcamp.locker_robot;
import lombok.extern.java.Log;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@Log
public class LockerTest {
@Test
public void should_return_ticket_when_saving_given_locker_is_not_available() {
Locker locker = new Locker(1);
locker.save();
assertThrows(LockerFullException.class, locker::save);
}
@Test
public void should_return_ticket_when_saving_given_available_is_available() {
Locker locker = new Locker(10);
assertNotNull(locker.save());
}
@Test
public void should_return_true_when_fetching_given_ticket_is_valid() {
Locker locker = new Locker(10);
Ticket ticket = locker.save();
assertTrue(locker.fetch(ticket));
}
@Test
public void should_return_exception_when_fetching_given_ticket_is_not_valid() {
Locker locker = new Locker(10);
Ticket ticket = new Ticket();
assertThrows(InvalidTicketException.class, () -> locker.fetch(ticket));
}
@Test
public void should_return_exception_when_fetching_given_ticket_is_used() {
Locker locker = new Locker(10);
Ticket ticket = locker.save();
locker.fetch(ticket);
assertThrows(InvalidTicketException.class, () -> locker.fetch(ticket));
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pt.ips.pa.fase1.tads.interfaces;
import java.io.Serializable;
/**
* O Comparador descreve a maneira como são ordenados os dados de um certo tipo
* de elementos.
*
* @author Ricardo José Horta Morais
* @param <E> Tipo de elemento a ordenar
*/
public interface Comparador<E> extends Serializable {
/**
* Diz se estão ordenados de acordo com este tipo de ordenação
*
* @param esquerdo elemento do lado esquerdo
* @param direito elemento do lado direito
* @return true se os elementos devem ser trocados e false senão
*
*/
public boolean comparar(E esquerdo, E direito);
}
|
/*
* 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.geode.cache.client.internal;
import java.util.Arrays;
import org.apache.geode.SerializationException;
import org.apache.geode.cache.client.ServerOperationException;
import org.apache.geode.cache.query.SelectResults;
import org.apache.geode.cache.query.internal.QueryUtils;
import org.apache.geode.cache.query.internal.StructImpl;
import org.apache.geode.cache.query.internal.types.StructTypeImpl;
import org.apache.geode.cache.query.internal.types.TypeUtils;
import org.apache.geode.cache.query.types.CollectionType;
import org.apache.geode.cache.query.types.ObjectType;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.cache.tier.MessageType;
import org.apache.geode.internal.cache.tier.sockets.ChunkedMessage;
import org.apache.geode.internal.cache.tier.sockets.Message;
import org.apache.geode.internal.cache.tier.sockets.ObjectPartList;
import org.apache.geode.internal.cache.tier.sockets.Part;
/**
* Does a region query on a server
*
* @since GemFire 5.7
*/
public class QueryOp {
/**
* Does a region query on a server using connections from the given pool to communicate with the
* server.
*
* @param pool the pool to use to communicate with the server.
* @param queryPredicate A query language boolean query predicate
* @return A <code>SelectResults</code> containing the values that match the
* <code>queryPredicate</code>.
*/
public static SelectResults execute(ExecutablePool pool, String queryPredicate,
Object[] queryParams) {
AbstractOp op = null;
if (queryParams != null && queryParams.length > 0) {
op = new QueryOpImpl(queryPredicate, queryParams);
} else {
op = new QueryOpImpl(queryPredicate);
}
return (SelectResults) pool.execute(op);
}
private QueryOp() {
// no instances allowed
}
/**
* Note: this class is extended by CreateCQWithIROpImpl.
*/
public static class QueryOpImpl extends AbstractOp {
/**
* @throws org.apache.geode.SerializationException if serialization fails
*/
public QueryOpImpl(String queryPredicate) {
super(MessageType.QUERY, 1);
getMessage().addStringPart(queryPredicate);
}
/**
* @throws org.apache.geode.SerializationException if serialization fails
*/
public QueryOpImpl(String queryPredicate, Object[] queryParams) {
super(MessageType.QUERY_WITH_PARAMETERS, 2 + queryParams.length);
getMessage().addStringPart(queryPredicate);
getMessage().addIntPart(queryParams.length);
for (Object param : queryParams) {
getMessage().addObjPart(param);
}
}
/**
* This constructor is used by our subclass CreateCQWithIROpImpl
*
* @throws org.apache.geode.SerializationException if serialization fails
*/
protected QueryOpImpl(int msgType, int numParts) {
super(msgType, numParts);
}
@Override
protected Message createResponseMessage() {
return new ChunkedMessage(2, Version.CURRENT);
}
@Override
protected Object processResponse(Message msg) throws Exception {
final SelectResults[] resultRef = new SelectResults[1];
final Exception[] exceptionRef = new Exception[1];
ChunkHandler ch = new ChunkHandler() {
public void handle(ChunkedMessage cm) throws Exception {
Part collectionTypePart = cm.getPart(0);
Object o = collectionTypePart.getObject();
if (o instanceof Throwable) {
String s = "While performing a remote " + getOpName();
exceptionRef[0] = new ServerOperationException(s, (Throwable) o);
return;
}
CollectionType collectionType = (CollectionType) o;
Part resultPart = cm.getPart(1);
Object queryResult = null;
try {
queryResult = resultPart.getObject();
} catch (Exception e) {
String s = "While deserializing " + getOpName() + " result";
exceptionRef[0] = new SerializationException(s, e);
return;
}
if (queryResult instanceof Throwable) {
String s = "While performing a remote " + getOpName();
exceptionRef[0] = new ServerOperationException(s, (Throwable) queryResult);
return;
} else if (queryResult instanceof Integer) {
// Create the appropriate SelectResults instance if necessary
if (resultRef[0] == null) {
resultRef[0] = QueryUtils.getEmptySelectResults(TypeUtils.OBJECT_TYPE, null);
}
resultRef[0].add(queryResult);
} else { // typical query result
// Create the appropriate SelectResults instance if necessary
if (resultRef[0] == null) {
resultRef[0] = QueryUtils.getEmptySelectResults(collectionType, null);
}
SelectResults selectResults = resultRef[0];
ObjectType objectType = collectionType.getElementType();
Object[] resultArray;
// for select * queries, the serialized object byte arrays are
// returned as part of ObjectPartList
boolean isObjectPartList = false;
if (queryResult instanceof ObjectPartList) {
isObjectPartList = true;
resultArray = ((ObjectPartList) queryResult).getObjects().toArray();
} else {
// Add the results to the SelectResults
resultArray = (Object[]) queryResult;
}
if (objectType.isStructType()) {
for (int i = 0; i < resultArray.length; i++) {
if (isObjectPartList) {
selectResults.add(new StructImpl((StructTypeImpl) objectType,
((ObjectPartList) resultArray[i]).getObjects().toArray()));
} else {
selectResults
.add(new StructImpl((StructTypeImpl) objectType, (Object[]) resultArray[i]));
}
}
} else {
selectResults.addAll(Arrays.asList(resultArray));
}
}
}
};
processChunkedResponse((ChunkedMessage) msg, getOpName(), ch);
if (exceptionRef[0] != null) {
throw exceptionRef[0];
} else {
return resultRef[0];
}
}
protected String getOpName() {
return "query";
}
@Override
protected boolean isErrorResponse(int msgType) {
return msgType == MessageType.QUERY_DATA_ERROR || msgType == MessageType.CQDATAERROR_MSG_TYPE
|| msgType == MessageType.CQ_EXCEPTION_TYPE;
}
@Override
protected long startAttempt(ConnectionStats stats) {
return stats.startQuery();
}
@Override
protected void endSendAttempt(ConnectionStats stats, long start) {
stats.endQuerySend(start, hasFailed());
}
@Override
protected void endAttempt(ConnectionStats stats, long start) {
stats.endQuery(start, hasTimedOut(), hasFailed());
}
}
}
|
package org.linlinjava.litemall.db.domain;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class LitemallAdminOrderExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public LitemallAdminOrderExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public LitemallAdminOrderExample orderBy(String orderByClause) {
this.setOrderByClause(orderByClause);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public LitemallAdminOrderExample orderBy(String ... orderByClauses) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < orderByClauses.length; i++) {
sb.append(orderByClauses[i]);
if (i < orderByClauses.length - 1) {
sb.append(" , ");
}
}
this.setOrderByClause(sb.toString());
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria(this);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public static Criteria newAndCreateCriteria() {
LitemallAdminOrderExample example = new LitemallAdminOrderExample();
return example.createCriteria();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public LitemallAdminOrderExample when(boolean condition, IExampleWhen then) {
if (condition) {
then.example(this);
}
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public LitemallAdminOrderExample when(boolean condition, IExampleWhen then, IExampleWhen otherwise) {
if (condition) {
then.example(this);
} else {
otherwise.example(this);
}
return this;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
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 andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andIdEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("id = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andIdNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("id <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andIdGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("id > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andIdGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("id >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andIdLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("id < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andIdLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("id <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andAdminIdIsNull() {
addCriterion("admin_id is null");
return (Criteria) this;
}
public Criteria andAdminIdIsNotNull() {
addCriterion("admin_id is not null");
return (Criteria) this;
}
public Criteria andAdminIdEqualTo(Integer value) {
addCriterion("admin_id =", value, "adminId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAdminIdEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("admin_id = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAdminIdNotEqualTo(Integer value) {
addCriterion("admin_id <>", value, "adminId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAdminIdNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("admin_id <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAdminIdGreaterThan(Integer value) {
addCriterion("admin_id >", value, "adminId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAdminIdGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("admin_id > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAdminIdGreaterThanOrEqualTo(Integer value) {
addCriterion("admin_id >=", value, "adminId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAdminIdGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("admin_id >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAdminIdLessThan(Integer value) {
addCriterion("admin_id <", value, "adminId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAdminIdLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("admin_id < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAdminIdLessThanOrEqualTo(Integer value) {
addCriterion("admin_id <=", value, "adminId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAdminIdLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("admin_id <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAdminIdIn(List<Integer> values) {
addCriterion("admin_id in", values, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdNotIn(List<Integer> values) {
addCriterion("admin_id not in", values, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdBetween(Integer value1, Integer value2) {
addCriterion("admin_id between", value1, value2, "adminId");
return (Criteria) this;
}
public Criteria andAdminIdNotBetween(Integer value1, Integer value2) {
addCriterion("admin_id not between", value1, value2, "adminId");
return (Criteria) this;
}
public Criteria andUsernameIsNull() {
addCriterion("userName is null");
return (Criteria) this;
}
public Criteria andUsernameIsNotNull() {
addCriterion("userName is not null");
return (Criteria) this;
}
public Criteria andUsernameEqualTo(String value) {
addCriterion("userName =", value, "username");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUsernameEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("userName = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUsernameNotEqualTo(String value) {
addCriterion("userName <>", value, "username");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUsernameNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("userName <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUsernameGreaterThan(String value) {
addCriterion("userName >", value, "username");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUsernameGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("userName > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUsernameGreaterThanOrEqualTo(String value) {
addCriterion("userName >=", value, "username");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUsernameGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("userName >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUsernameLessThan(String value) {
addCriterion("userName <", value, "username");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUsernameLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("userName < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUsernameLessThanOrEqualTo(String value) {
addCriterion("userName <=", value, "username");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUsernameLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("userName <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUsernameLike(String value) {
addCriterion("userName like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotLike(String value) {
addCriterion("userName not like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameIn(List<String> values) {
addCriterion("userName in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameNotIn(List<String> values) {
addCriterion("userName not in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameBetween(String value1, String value2) {
addCriterion("userName between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andUsernameNotBetween(String value1, String value2) {
addCriterion("userName not between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andShopIdIsNull() {
addCriterion("shop_id is null");
return (Criteria) this;
}
public Criteria andShopIdIsNotNull() {
addCriterion("shop_id is not null");
return (Criteria) this;
}
public Criteria andShopIdEqualTo(Integer value) {
addCriterion("shop_id =", value, "shopId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopIdEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_id = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopIdNotEqualTo(Integer value) {
addCriterion("shop_id <>", value, "shopId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopIdNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_id <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopIdGreaterThan(Integer value) {
addCriterion("shop_id >", value, "shopId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopIdGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_id > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopIdGreaterThanOrEqualTo(Integer value) {
addCriterion("shop_id >=", value, "shopId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopIdGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_id >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopIdLessThan(Integer value) {
addCriterion("shop_id <", value, "shopId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopIdLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_id < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopIdLessThanOrEqualTo(Integer value) {
addCriterion("shop_id <=", value, "shopId");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopIdLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_id <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopIdIn(List<Integer> values) {
addCriterion("shop_id in", values, "shopId");
return (Criteria) this;
}
public Criteria andShopIdNotIn(List<Integer> values) {
addCriterion("shop_id not in", values, "shopId");
return (Criteria) this;
}
public Criteria andShopIdBetween(Integer value1, Integer value2) {
addCriterion("shop_id between", value1, value2, "shopId");
return (Criteria) this;
}
public Criteria andShopIdNotBetween(Integer value1, Integer value2) {
addCriterion("shop_id not between", value1, value2, "shopId");
return (Criteria) this;
}
public Criteria andShopNameIsNull() {
addCriterion("shop_name is null");
return (Criteria) this;
}
public Criteria andShopNameIsNotNull() {
addCriterion("shop_name is not null");
return (Criteria) this;
}
public Criteria andShopNameEqualTo(String value) {
addCriterion("shop_name =", value, "shopName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopNameEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_name = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopNameNotEqualTo(String value) {
addCriterion("shop_name <>", value, "shopName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopNameNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_name <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopNameGreaterThan(String value) {
addCriterion("shop_name >", value, "shopName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopNameGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_name > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopNameGreaterThanOrEqualTo(String value) {
addCriterion("shop_name >=", value, "shopName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopNameGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_name >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopNameLessThan(String value) {
addCriterion("shop_name <", value, "shopName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopNameLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_name < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopNameLessThanOrEqualTo(String value) {
addCriterion("shop_name <=", value, "shopName");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShopNameLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("shop_name <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShopNameLike(String value) {
addCriterion("shop_name like", value, "shopName");
return (Criteria) this;
}
public Criteria andShopNameNotLike(String value) {
addCriterion("shop_name not like", value, "shopName");
return (Criteria) this;
}
public Criteria andShopNameIn(List<String> values) {
addCriterion("shop_name in", values, "shopName");
return (Criteria) this;
}
public Criteria andShopNameNotIn(List<String> values) {
addCriterion("shop_name not in", values, "shopName");
return (Criteria) this;
}
public Criteria andShopNameBetween(String value1, String value2) {
addCriterion("shop_name between", value1, value2, "shopName");
return (Criteria) this;
}
public Criteria andShopNameNotBetween(String value1, String value2) {
addCriterion("shop_name not between", value1, value2, "shopName");
return (Criteria) this;
}
public Criteria andOrderRemarkIsNull() {
addCriterion("order_remark is null");
return (Criteria) this;
}
public Criteria andOrderRemarkIsNotNull() {
addCriterion("order_remark is not null");
return (Criteria) this;
}
public Criteria andOrderRemarkEqualTo(String value) {
addCriterion("order_remark =", value, "orderRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderRemarkEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_remark = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderRemarkNotEqualTo(String value) {
addCriterion("order_remark <>", value, "orderRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderRemarkNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_remark <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderRemarkGreaterThan(String value) {
addCriterion("order_remark >", value, "orderRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderRemarkGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_remark > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderRemarkGreaterThanOrEqualTo(String value) {
addCriterion("order_remark >=", value, "orderRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderRemarkGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_remark >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderRemarkLessThan(String value) {
addCriterion("order_remark <", value, "orderRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderRemarkLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_remark < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderRemarkLessThanOrEqualTo(String value) {
addCriterion("order_remark <=", value, "orderRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderRemarkLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_remark <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderRemarkLike(String value) {
addCriterion("order_remark like", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkNotLike(String value) {
addCriterion("order_remark not like", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkIn(List<String> values) {
addCriterion("order_remark in", values, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkNotIn(List<String> values) {
addCriterion("order_remark not in", values, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkBetween(String value1, String value2) {
addCriterion("order_remark between", value1, value2, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkNotBetween(String value1, String value2) {
addCriterion("order_remark not between", value1, value2, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderSnIsNull() {
addCriterion("order_sn is null");
return (Criteria) this;
}
public Criteria andOrderSnIsNotNull() {
addCriterion("order_sn is not null");
return (Criteria) this;
}
public Criteria andOrderSnEqualTo(String value) {
addCriterion("order_sn =", value, "orderSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderSnEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_sn = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderSnNotEqualTo(String value) {
addCriterion("order_sn <>", value, "orderSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderSnNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_sn <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderSnGreaterThan(String value) {
addCriterion("order_sn >", value, "orderSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderSnGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_sn > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderSnGreaterThanOrEqualTo(String value) {
addCriterion("order_sn >=", value, "orderSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderSnGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_sn >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderSnLessThan(String value) {
addCriterion("order_sn <", value, "orderSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderSnLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_sn < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderSnLessThanOrEqualTo(String value) {
addCriterion("order_sn <=", value, "orderSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderSnLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_sn <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderSnLike(String value) {
addCriterion("order_sn like", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnNotLike(String value) {
addCriterion("order_sn not like", value, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnIn(List<String> values) {
addCriterion("order_sn in", values, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnNotIn(List<String> values) {
addCriterion("order_sn not in", values, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnBetween(String value1, String value2) {
addCriterion("order_sn between", value1, value2, "orderSn");
return (Criteria) this;
}
public Criteria andOrderSnNotBetween(String value1, String value2) {
addCriterion("order_sn not between", value1, value2, "orderSn");
return (Criteria) this;
}
public Criteria andOrderStatusIsNull() {
addCriterion("order_status is null");
return (Criteria) this;
}
public Criteria andOrderStatusIsNotNull() {
addCriterion("order_status is not null");
return (Criteria) this;
}
public Criteria andOrderStatusEqualTo(Byte value) {
addCriterion("order_status =", value, "orderStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderStatusEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_status = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderStatusNotEqualTo(Byte value) {
addCriterion("order_status <>", value, "orderStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderStatusNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_status <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderStatusGreaterThan(Byte value) {
addCriterion("order_status >", value, "orderStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderStatusGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_status > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderStatusGreaterThanOrEqualTo(Byte value) {
addCriterion("order_status >=", value, "orderStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderStatusGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_status >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderStatusLessThan(Byte value) {
addCriterion("order_status <", value, "orderStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderStatusLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_status < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderStatusLessThanOrEqualTo(Byte value) {
addCriterion("order_status <=", value, "orderStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderStatusLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_status <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderStatusIn(List<Byte> values) {
addCriterion("order_status in", values, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusNotIn(List<Byte> values) {
addCriterion("order_status not in", values, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusBetween(Byte value1, Byte value2) {
addCriterion("order_status between", value1, value2, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusNotBetween(Byte value1, Byte value2) {
addCriterion("order_status not between", value1, value2, "orderStatus");
return (Criteria) this;
}
public Criteria andConsigneeIsNull() {
addCriterion("consignee is null");
return (Criteria) this;
}
public Criteria andConsigneeIsNotNull() {
addCriterion("consignee is not null");
return (Criteria) this;
}
public Criteria andConsigneeEqualTo(String value) {
addCriterion("consignee =", value, "consignee");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConsigneeEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("consignee = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConsigneeNotEqualTo(String value) {
addCriterion("consignee <>", value, "consignee");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConsigneeNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("consignee <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConsigneeGreaterThan(String value) {
addCriterion("consignee >", value, "consignee");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConsigneeGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("consignee > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConsigneeGreaterThanOrEqualTo(String value) {
addCriterion("consignee >=", value, "consignee");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConsigneeGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("consignee >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConsigneeLessThan(String value) {
addCriterion("consignee <", value, "consignee");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConsigneeLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("consignee < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConsigneeLessThanOrEqualTo(String value) {
addCriterion("consignee <=", value, "consignee");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConsigneeLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("consignee <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConsigneeLike(String value) {
addCriterion("consignee like", value, "consignee");
return (Criteria) this;
}
public Criteria andConsigneeNotLike(String value) {
addCriterion("consignee not like", value, "consignee");
return (Criteria) this;
}
public Criteria andConsigneeIn(List<String> values) {
addCriterion("consignee in", values, "consignee");
return (Criteria) this;
}
public Criteria andConsigneeNotIn(List<String> values) {
addCriterion("consignee not in", values, "consignee");
return (Criteria) this;
}
public Criteria andConsigneeBetween(String value1, String value2) {
addCriterion("consignee between", value1, value2, "consignee");
return (Criteria) this;
}
public Criteria andConsigneeNotBetween(String value1, String value2) {
addCriterion("consignee not between", value1, value2, "consignee");
return (Criteria) this;
}
public Criteria andMobileIsNull() {
addCriterion("mobile is null");
return (Criteria) this;
}
public Criteria andMobileIsNotNull() {
addCriterion("mobile is not null");
return (Criteria) this;
}
public Criteria andMobileEqualTo(String value) {
addCriterion("mobile =", value, "mobile");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andMobileEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("mobile = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andMobileNotEqualTo(String value) {
addCriterion("mobile <>", value, "mobile");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andMobileNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("mobile <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andMobileGreaterThan(String value) {
addCriterion("mobile >", value, "mobile");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andMobileGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("mobile > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andMobileGreaterThanOrEqualTo(String value) {
addCriterion("mobile >=", value, "mobile");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andMobileGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("mobile >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andMobileLessThan(String value) {
addCriterion("mobile <", value, "mobile");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andMobileLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("mobile < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andMobileLessThanOrEqualTo(String value) {
addCriterion("mobile <=", value, "mobile");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andMobileLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("mobile <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andMobileLike(String value) {
addCriterion("mobile like", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileNotLike(String value) {
addCriterion("mobile not like", value, "mobile");
return (Criteria) this;
}
public Criteria andMobileIn(List<String> values) {
addCriterion("mobile in", values, "mobile");
return (Criteria) this;
}
public Criteria andMobileNotIn(List<String> values) {
addCriterion("mobile not in", values, "mobile");
return (Criteria) this;
}
public Criteria andMobileBetween(String value1, String value2) {
addCriterion("mobile between", value1, value2, "mobile");
return (Criteria) this;
}
public Criteria andMobileNotBetween(String value1, String value2) {
addCriterion("mobile not between", value1, value2, "mobile");
return (Criteria) this;
}
public Criteria andAddressIsNull() {
addCriterion("address is null");
return (Criteria) this;
}
public Criteria andAddressIsNotNull() {
addCriterion("address is not null");
return (Criteria) this;
}
public Criteria andAddressEqualTo(String value) {
addCriterion("address =", value, "address");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddressEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("address = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddressNotEqualTo(String value) {
addCriterion("address <>", value, "address");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddressNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("address <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddressGreaterThan(String value) {
addCriterion("address >", value, "address");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddressGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("address > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddressGreaterThanOrEqualTo(String value) {
addCriterion("address >=", value, "address");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddressGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("address >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddressLessThan(String value) {
addCriterion("address <", value, "address");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddressLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("address < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddressLessThanOrEqualTo(String value) {
addCriterion("address <=", value, "address");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddressLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("address <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddressLike(String value) {
addCriterion("address like", value, "address");
return (Criteria) this;
}
public Criteria andAddressNotLike(String value) {
addCriterion("address not like", value, "address");
return (Criteria) this;
}
public Criteria andAddressIn(List<String> values) {
addCriterion("address in", values, "address");
return (Criteria) this;
}
public Criteria andAddressNotIn(List<String> values) {
addCriterion("address not in", values, "address");
return (Criteria) this;
}
public Criteria andAddressBetween(String value1, String value2) {
addCriterion("address between", value1, value2, "address");
return (Criteria) this;
}
public Criteria andAddressNotBetween(String value1, String value2) {
addCriterion("address not between", value1, value2, "address");
return (Criteria) this;
}
public Criteria andFreightPriceIsNull() {
addCriterion("freight_price is null");
return (Criteria) this;
}
public Criteria andFreightPriceIsNotNull() {
addCriterion("freight_price is not null");
return (Criteria) this;
}
public Criteria andFreightPriceEqualTo(BigDecimal value) {
addCriterion("freight_price =", value, "freightPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andFreightPriceEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("freight_price = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andFreightPriceNotEqualTo(BigDecimal value) {
addCriterion("freight_price <>", value, "freightPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andFreightPriceNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("freight_price <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andFreightPriceGreaterThan(BigDecimal value) {
addCriterion("freight_price >", value, "freightPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andFreightPriceGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("freight_price > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andFreightPriceGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("freight_price >=", value, "freightPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andFreightPriceGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("freight_price >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andFreightPriceLessThan(BigDecimal value) {
addCriterion("freight_price <", value, "freightPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andFreightPriceLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("freight_price < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andFreightPriceLessThanOrEqualTo(BigDecimal value) {
addCriterion("freight_price <=", value, "freightPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andFreightPriceLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("freight_price <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andFreightPriceIn(List<BigDecimal> values) {
addCriterion("freight_price in", values, "freightPrice");
return (Criteria) this;
}
public Criteria andFreightPriceNotIn(List<BigDecimal> values) {
addCriterion("freight_price not in", values, "freightPrice");
return (Criteria) this;
}
public Criteria andFreightPriceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("freight_price between", value1, value2, "freightPrice");
return (Criteria) this;
}
public Criteria andFreightPriceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("freight_price not between", value1, value2, "freightPrice");
return (Criteria) this;
}
public Criteria andUnitPriceIsNull() {
addCriterion("unit_price is null");
return (Criteria) this;
}
public Criteria andUnitPriceIsNotNull() {
addCriterion("unit_price is not null");
return (Criteria) this;
}
public Criteria andUnitPriceEqualTo(BigDecimal value) {
addCriterion("unit_price =", value, "unitPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUnitPriceEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("unit_price = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUnitPriceNotEqualTo(BigDecimal value) {
addCriterion("unit_price <>", value, "unitPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUnitPriceNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("unit_price <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUnitPriceGreaterThan(BigDecimal value) {
addCriterion("unit_price >", value, "unitPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUnitPriceGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("unit_price > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUnitPriceGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("unit_price >=", value, "unitPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUnitPriceGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("unit_price >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUnitPriceLessThan(BigDecimal value) {
addCriterion("unit_price <", value, "unitPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUnitPriceLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("unit_price < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUnitPriceLessThanOrEqualTo(BigDecimal value) {
addCriterion("unit_price <=", value, "unitPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUnitPriceLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("unit_price <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUnitPriceIn(List<BigDecimal> values) {
addCriterion("unit_price in", values, "unitPrice");
return (Criteria) this;
}
public Criteria andUnitPriceNotIn(List<BigDecimal> values) {
addCriterion("unit_price not in", values, "unitPrice");
return (Criteria) this;
}
public Criteria andUnitPriceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("unit_price between", value1, value2, "unitPrice");
return (Criteria) this;
}
public Criteria andUnitPriceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("unit_price not between", value1, value2, "unitPrice");
return (Criteria) this;
}
public Criteria andOrderPriceIsNull() {
addCriterion("order_price is null");
return (Criteria) this;
}
public Criteria andOrderPriceIsNotNull() {
addCriterion("order_price is not null");
return (Criteria) this;
}
public Criteria andOrderPriceEqualTo(BigDecimal value) {
addCriterion("order_price =", value, "orderPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderPriceEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_price = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderPriceNotEqualTo(BigDecimal value) {
addCriterion("order_price <>", value, "orderPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderPriceNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_price <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderPriceGreaterThan(BigDecimal value) {
addCriterion("order_price >", value, "orderPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderPriceGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_price > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderPriceGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("order_price >=", value, "orderPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderPriceGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_price >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderPriceLessThan(BigDecimal value) {
addCriterion("order_price <", value, "orderPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderPriceLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_price < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderPriceLessThanOrEqualTo(BigDecimal value) {
addCriterion("order_price <=", value, "orderPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andOrderPriceLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("order_price <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andOrderPriceIn(List<BigDecimal> values) {
addCriterion("order_price in", values, "orderPrice");
return (Criteria) this;
}
public Criteria andOrderPriceNotIn(List<BigDecimal> values) {
addCriterion("order_price not in", values, "orderPrice");
return (Criteria) this;
}
public Criteria andOrderPriceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("order_price between", value1, value2, "orderPrice");
return (Criteria) this;
}
public Criteria andOrderPriceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("order_price not between", value1, value2, "orderPrice");
return (Criteria) this;
}
public Criteria andActualPriceIsNull() {
addCriterion("actual_price is null");
return (Criteria) this;
}
public Criteria andActualPriceIsNotNull() {
addCriterion("actual_price is not null");
return (Criteria) this;
}
public Criteria andActualPriceEqualTo(BigDecimal value) {
addCriterion("actual_price =", value, "actualPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andActualPriceEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("actual_price = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andActualPriceNotEqualTo(BigDecimal value) {
addCriterion("actual_price <>", value, "actualPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andActualPriceNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("actual_price <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andActualPriceGreaterThan(BigDecimal value) {
addCriterion("actual_price >", value, "actualPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andActualPriceGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("actual_price > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andActualPriceGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("actual_price >=", value, "actualPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andActualPriceGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("actual_price >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andActualPriceLessThan(BigDecimal value) {
addCriterion("actual_price <", value, "actualPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andActualPriceLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("actual_price < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andActualPriceLessThanOrEqualTo(BigDecimal value) {
addCriterion("actual_price <=", value, "actualPrice");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andActualPriceLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("actual_price <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andActualPriceIn(List<BigDecimal> values) {
addCriterion("actual_price in", values, "actualPrice");
return (Criteria) this;
}
public Criteria andActualPriceNotIn(List<BigDecimal> values) {
addCriterion("actual_price not in", values, "actualPrice");
return (Criteria) this;
}
public Criteria andActualPriceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("actual_price between", value1, value2, "actualPrice");
return (Criteria) this;
}
public Criteria andActualPriceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("actual_price not between", value1, value2, "actualPrice");
return (Criteria) this;
}
public Criteria andPayStatusIsNull() {
addCriterion("pay_status is null");
return (Criteria) this;
}
public Criteria andPayStatusIsNotNull() {
addCriterion("pay_status is not null");
return (Criteria) this;
}
public Criteria andPayStatusEqualTo(Byte value) {
addCriterion("pay_status =", value, "payStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayStatusEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_status = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayStatusNotEqualTo(Byte value) {
addCriterion("pay_status <>", value, "payStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayStatusNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_status <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayStatusGreaterThan(Byte value) {
addCriterion("pay_status >", value, "payStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayStatusGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_status > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayStatusGreaterThanOrEqualTo(Byte value) {
addCriterion("pay_status >=", value, "payStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayStatusGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_status >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayStatusLessThan(Byte value) {
addCriterion("pay_status <", value, "payStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayStatusLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_status < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayStatusLessThanOrEqualTo(Byte value) {
addCriterion("pay_status <=", value, "payStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayStatusLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_status <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayStatusIn(List<Byte> values) {
addCriterion("pay_status in", values, "payStatus");
return (Criteria) this;
}
public Criteria andPayStatusNotIn(List<Byte> values) {
addCriterion("pay_status not in", values, "payStatus");
return (Criteria) this;
}
public Criteria andPayStatusBetween(Byte value1, Byte value2) {
addCriterion("pay_status between", value1, value2, "payStatus");
return (Criteria) this;
}
public Criteria andPayStatusNotBetween(Byte value1, Byte value2) {
addCriterion("pay_status not between", value1, value2, "payStatus");
return (Criteria) this;
}
public Criteria andHandleRemarkIsNull() {
addCriterion("handle_remark is null");
return (Criteria) this;
}
public Criteria andHandleRemarkIsNotNull() {
addCriterion("handle_remark is not null");
return (Criteria) this;
}
public Criteria andHandleRemarkEqualTo(String value) {
addCriterion("handle_remark =", value, "handleRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andHandleRemarkEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("handle_remark = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andHandleRemarkNotEqualTo(String value) {
addCriterion("handle_remark <>", value, "handleRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andHandleRemarkNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("handle_remark <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andHandleRemarkGreaterThan(String value) {
addCriterion("handle_remark >", value, "handleRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andHandleRemarkGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("handle_remark > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andHandleRemarkGreaterThanOrEqualTo(String value) {
addCriterion("handle_remark >=", value, "handleRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andHandleRemarkGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("handle_remark >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andHandleRemarkLessThan(String value) {
addCriterion("handle_remark <", value, "handleRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andHandleRemarkLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("handle_remark < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andHandleRemarkLessThanOrEqualTo(String value) {
addCriterion("handle_remark <=", value, "handleRemark");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andHandleRemarkLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("handle_remark <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andHandleRemarkLike(String value) {
addCriterion("handle_remark like", value, "handleRemark");
return (Criteria) this;
}
public Criteria andHandleRemarkNotLike(String value) {
addCriterion("handle_remark not like", value, "handleRemark");
return (Criteria) this;
}
public Criteria andHandleRemarkIn(List<String> values) {
addCriterion("handle_remark in", values, "handleRemark");
return (Criteria) this;
}
public Criteria andHandleRemarkNotIn(List<String> values) {
addCriterion("handle_remark not in", values, "handleRemark");
return (Criteria) this;
}
public Criteria andHandleRemarkBetween(String value1, String value2) {
addCriterion("handle_remark between", value1, value2, "handleRemark");
return (Criteria) this;
}
public Criteria andHandleRemarkNotBetween(String value1, String value2) {
addCriterion("handle_remark not between", value1, value2, "handleRemark");
return (Criteria) this;
}
public Criteria andPayTimeIsNull() {
addCriterion("pay_time is null");
return (Criteria) this;
}
public Criteria andPayTimeIsNotNull() {
addCriterion("pay_time is not null");
return (Criteria) this;
}
public Criteria andPayTimeEqualTo(LocalDateTime value) {
addCriterion("pay_time =", value, "payTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayTimeEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_time = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayTimeNotEqualTo(LocalDateTime value) {
addCriterion("pay_time <>", value, "payTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayTimeNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_time <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayTimeGreaterThan(LocalDateTime value) {
addCriterion("pay_time >", value, "payTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayTimeGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_time > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayTimeGreaterThanOrEqualTo(LocalDateTime value) {
addCriterion("pay_time >=", value, "payTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayTimeGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_time >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayTimeLessThan(LocalDateTime value) {
addCriterion("pay_time <", value, "payTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayTimeLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_time < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayTimeLessThanOrEqualTo(LocalDateTime value) {
addCriterion("pay_time <=", value, "payTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andPayTimeLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("pay_time <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andPayTimeIn(List<LocalDateTime> values) {
addCriterion("pay_time in", values, "payTime");
return (Criteria) this;
}
public Criteria andPayTimeNotIn(List<LocalDateTime> values) {
addCriterion("pay_time not in", values, "payTime");
return (Criteria) this;
}
public Criteria andPayTimeBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("pay_time between", value1, value2, "payTime");
return (Criteria) this;
}
public Criteria andPayTimeNotBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("pay_time not between", value1, value2, "payTime");
return (Criteria) this;
}
public Criteria andShipStatusIsNull() {
addCriterion("ship_status is null");
return (Criteria) this;
}
public Criteria andShipStatusIsNotNull() {
addCriterion("ship_status is not null");
return (Criteria) this;
}
public Criteria andShipStatusEqualTo(Byte value) {
addCriterion("ship_status =", value, "shipStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipStatusEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_status = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipStatusNotEqualTo(Byte value) {
addCriterion("ship_status <>", value, "shipStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipStatusNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_status <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipStatusGreaterThan(Byte value) {
addCriterion("ship_status >", value, "shipStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipStatusGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_status > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipStatusGreaterThanOrEqualTo(Byte value) {
addCriterion("ship_status >=", value, "shipStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipStatusGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_status >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipStatusLessThan(Byte value) {
addCriterion("ship_status <", value, "shipStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipStatusLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_status < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipStatusLessThanOrEqualTo(Byte value) {
addCriterion("ship_status <=", value, "shipStatus");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipStatusLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_status <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipStatusIn(List<Byte> values) {
addCriterion("ship_status in", values, "shipStatus");
return (Criteria) this;
}
public Criteria andShipStatusNotIn(List<Byte> values) {
addCriterion("ship_status not in", values, "shipStatus");
return (Criteria) this;
}
public Criteria andShipStatusBetween(Byte value1, Byte value2) {
addCriterion("ship_status between", value1, value2, "shipStatus");
return (Criteria) this;
}
public Criteria andShipStatusNotBetween(Byte value1, Byte value2) {
addCriterion("ship_status not between", value1, value2, "shipStatus");
return (Criteria) this;
}
public Criteria andShipSnIsNull() {
addCriterion("ship_sn is null");
return (Criteria) this;
}
public Criteria andShipSnIsNotNull() {
addCriterion("ship_sn is not null");
return (Criteria) this;
}
public Criteria andShipSnEqualTo(String value) {
addCriterion("ship_sn =", value, "shipSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipSnEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_sn = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipSnNotEqualTo(String value) {
addCriterion("ship_sn <>", value, "shipSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipSnNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_sn <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipSnGreaterThan(String value) {
addCriterion("ship_sn >", value, "shipSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipSnGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_sn > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipSnGreaterThanOrEqualTo(String value) {
addCriterion("ship_sn >=", value, "shipSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipSnGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_sn >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipSnLessThan(String value) {
addCriterion("ship_sn <", value, "shipSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipSnLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_sn < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipSnLessThanOrEqualTo(String value) {
addCriterion("ship_sn <=", value, "shipSn");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipSnLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_sn <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipSnLike(String value) {
addCriterion("ship_sn like", value, "shipSn");
return (Criteria) this;
}
public Criteria andShipSnNotLike(String value) {
addCriterion("ship_sn not like", value, "shipSn");
return (Criteria) this;
}
public Criteria andShipSnIn(List<String> values) {
addCriterion("ship_sn in", values, "shipSn");
return (Criteria) this;
}
public Criteria andShipSnNotIn(List<String> values) {
addCriterion("ship_sn not in", values, "shipSn");
return (Criteria) this;
}
public Criteria andShipSnBetween(String value1, String value2) {
addCriterion("ship_sn between", value1, value2, "shipSn");
return (Criteria) this;
}
public Criteria andShipSnNotBetween(String value1, String value2) {
addCriterion("ship_sn not between", value1, value2, "shipSn");
return (Criteria) this;
}
public Criteria andShipChannelIsNull() {
addCriterion("ship_channel is null");
return (Criteria) this;
}
public Criteria andShipChannelIsNotNull() {
addCriterion("ship_channel is not null");
return (Criteria) this;
}
public Criteria andShipChannelEqualTo(String value) {
addCriterion("ship_channel =", value, "shipChannel");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipChannelEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_channel = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipChannelNotEqualTo(String value) {
addCriterion("ship_channel <>", value, "shipChannel");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipChannelNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_channel <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipChannelGreaterThan(String value) {
addCriterion("ship_channel >", value, "shipChannel");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipChannelGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_channel > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipChannelGreaterThanOrEqualTo(String value) {
addCriterion("ship_channel >=", value, "shipChannel");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipChannelGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_channel >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipChannelLessThan(String value) {
addCriterion("ship_channel <", value, "shipChannel");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipChannelLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_channel < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipChannelLessThanOrEqualTo(String value) {
addCriterion("ship_channel <=", value, "shipChannel");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipChannelLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_channel <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipChannelLike(String value) {
addCriterion("ship_channel like", value, "shipChannel");
return (Criteria) this;
}
public Criteria andShipChannelNotLike(String value) {
addCriterion("ship_channel not like", value, "shipChannel");
return (Criteria) this;
}
public Criteria andShipChannelIn(List<String> values) {
addCriterion("ship_channel in", values, "shipChannel");
return (Criteria) this;
}
public Criteria andShipChannelNotIn(List<String> values) {
addCriterion("ship_channel not in", values, "shipChannel");
return (Criteria) this;
}
public Criteria andShipChannelBetween(String value1, String value2) {
addCriterion("ship_channel between", value1, value2, "shipChannel");
return (Criteria) this;
}
public Criteria andShipChannelNotBetween(String value1, String value2) {
addCriterion("ship_channel not between", value1, value2, "shipChannel");
return (Criteria) this;
}
public Criteria andShipTimeIsNull() {
addCriterion("ship_time is null");
return (Criteria) this;
}
public Criteria andShipTimeIsNotNull() {
addCriterion("ship_time is not null");
return (Criteria) this;
}
public Criteria andShipTimeEqualTo(LocalDateTime value) {
addCriterion("ship_time =", value, "shipTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipTimeEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_time = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipTimeNotEqualTo(LocalDateTime value) {
addCriterion("ship_time <>", value, "shipTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipTimeNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_time <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipTimeGreaterThan(LocalDateTime value) {
addCriterion("ship_time >", value, "shipTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipTimeGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_time > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipTimeGreaterThanOrEqualTo(LocalDateTime value) {
addCriterion("ship_time >=", value, "shipTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipTimeGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_time >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipTimeLessThan(LocalDateTime value) {
addCriterion("ship_time <", value, "shipTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipTimeLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_time < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipTimeLessThanOrEqualTo(LocalDateTime value) {
addCriterion("ship_time <=", value, "shipTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andShipTimeLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("ship_time <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andShipTimeIn(List<LocalDateTime> values) {
addCriterion("ship_time in", values, "shipTime");
return (Criteria) this;
}
public Criteria andShipTimeNotIn(List<LocalDateTime> values) {
addCriterion("ship_time not in", values, "shipTime");
return (Criteria) this;
}
public Criteria andShipTimeBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("ship_time between", value1, value2, "shipTime");
return (Criteria) this;
}
public Criteria andShipTimeNotBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("ship_time not between", value1, value2, "shipTime");
return (Criteria) this;
}
public Criteria andConfirmTimeIsNull() {
addCriterion("confirm_time is null");
return (Criteria) this;
}
public Criteria andConfirmTimeIsNotNull() {
addCriterion("confirm_time is not null");
return (Criteria) this;
}
public Criteria andConfirmTimeEqualTo(LocalDateTime value) {
addCriterion("confirm_time =", value, "confirmTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConfirmTimeEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("confirm_time = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConfirmTimeNotEqualTo(LocalDateTime value) {
addCriterion("confirm_time <>", value, "confirmTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConfirmTimeNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("confirm_time <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConfirmTimeGreaterThan(LocalDateTime value) {
addCriterion("confirm_time >", value, "confirmTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConfirmTimeGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("confirm_time > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConfirmTimeGreaterThanOrEqualTo(LocalDateTime value) {
addCriterion("confirm_time >=", value, "confirmTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConfirmTimeGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("confirm_time >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConfirmTimeLessThan(LocalDateTime value) {
addCriterion("confirm_time <", value, "confirmTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConfirmTimeLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("confirm_time < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConfirmTimeLessThanOrEqualTo(LocalDateTime value) {
addCriterion("confirm_time <=", value, "confirmTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andConfirmTimeLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("confirm_time <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andConfirmTimeIn(List<LocalDateTime> values) {
addCriterion("confirm_time in", values, "confirmTime");
return (Criteria) this;
}
public Criteria andConfirmTimeNotIn(List<LocalDateTime> values) {
addCriterion("confirm_time not in", values, "confirmTime");
return (Criteria) this;
}
public Criteria andConfirmTimeBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("confirm_time between", value1, value2, "confirmTime");
return (Criteria) this;
}
public Criteria andConfirmTimeNotBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("confirm_time not between", value1, value2, "confirmTime");
return (Criteria) this;
}
public Criteria andCommentsIsNull() {
addCriterion("comments is null");
return (Criteria) this;
}
public Criteria andCommentsIsNotNull() {
addCriterion("comments is not null");
return (Criteria) this;
}
public Criteria andCommentsEqualTo(Short value) {
addCriterion("comments =", value, "comments");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andCommentsEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("comments = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCommentsNotEqualTo(Short value) {
addCriterion("comments <>", value, "comments");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andCommentsNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("comments <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCommentsGreaterThan(Short value) {
addCriterion("comments >", value, "comments");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andCommentsGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("comments > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCommentsGreaterThanOrEqualTo(Short value) {
addCriterion("comments >=", value, "comments");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andCommentsGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("comments >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCommentsLessThan(Short value) {
addCriterion("comments <", value, "comments");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andCommentsLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("comments < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCommentsLessThanOrEqualTo(Short value) {
addCriterion("comments <=", value, "comments");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andCommentsLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("comments <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andCommentsIn(List<Short> values) {
addCriterion("comments in", values, "comments");
return (Criteria) this;
}
public Criteria andCommentsNotIn(List<Short> values) {
addCriterion("comments not in", values, "comments");
return (Criteria) this;
}
public Criteria andCommentsBetween(Short value1, Short value2) {
addCriterion("comments between", value1, value2, "comments");
return (Criteria) this;
}
public Criteria andCommentsNotBetween(Short value1, Short value2) {
addCriterion("comments not between", value1, value2, "comments");
return (Criteria) this;
}
public Criteria andEndTimeIsNull() {
addCriterion("end_time is null");
return (Criteria) this;
}
public Criteria andEndTimeIsNotNull() {
addCriterion("end_time is not null");
return (Criteria) this;
}
public Criteria andEndTimeEqualTo(LocalDateTime value) {
addCriterion("end_time =", value, "endTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andEndTimeEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("end_time = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andEndTimeNotEqualTo(LocalDateTime value) {
addCriterion("end_time <>", value, "endTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andEndTimeNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("end_time <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andEndTimeGreaterThan(LocalDateTime value) {
addCriterion("end_time >", value, "endTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andEndTimeGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("end_time > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andEndTimeGreaterThanOrEqualTo(LocalDateTime value) {
addCriterion("end_time >=", value, "endTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andEndTimeGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("end_time >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andEndTimeLessThan(LocalDateTime value) {
addCriterion("end_time <", value, "endTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andEndTimeLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("end_time < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andEndTimeLessThanOrEqualTo(LocalDateTime value) {
addCriterion("end_time <=", value, "endTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andEndTimeLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("end_time <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andEndTimeIn(List<LocalDateTime> values) {
addCriterion("end_time in", values, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotIn(List<LocalDateTime> values) {
addCriterion("end_time not in", values, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("end_time between", value1, value2, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("end_time not between", value1, value2, "endTime");
return (Criteria) this;
}
public Criteria andServiceTypeIsNull() {
addCriterion("service_type is null");
return (Criteria) this;
}
public Criteria andServiceTypeIsNotNull() {
addCriterion("service_type is not null");
return (Criteria) this;
}
public Criteria andServiceTypeEqualTo(Byte value) {
addCriterion("service_type =", value, "serviceType");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andServiceTypeEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("service_type = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andServiceTypeNotEqualTo(Byte value) {
addCriterion("service_type <>", value, "serviceType");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andServiceTypeNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("service_type <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andServiceTypeGreaterThan(Byte value) {
addCriterion("service_type >", value, "serviceType");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andServiceTypeGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("service_type > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andServiceTypeGreaterThanOrEqualTo(Byte value) {
addCriterion("service_type >=", value, "serviceType");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andServiceTypeGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("service_type >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andServiceTypeLessThan(Byte value) {
addCriterion("service_type <", value, "serviceType");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andServiceTypeLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("service_type < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andServiceTypeLessThanOrEqualTo(Byte value) {
addCriterion("service_type <=", value, "serviceType");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andServiceTypeLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("service_type <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andServiceTypeIn(List<Byte> values) {
addCriterion("service_type in", values, "serviceType");
return (Criteria) this;
}
public Criteria andServiceTypeNotIn(List<Byte> values) {
addCriterion("service_type not in", values, "serviceType");
return (Criteria) this;
}
public Criteria andServiceTypeBetween(Byte value1, Byte value2) {
addCriterion("service_type between", value1, value2, "serviceType");
return (Criteria) this;
}
public Criteria andServiceTypeNotBetween(Byte value1, Byte value2) {
addCriterion("service_type not between", value1, value2, "serviceType");
return (Criteria) this;
}
public Criteria andAddTimeIsNull() {
addCriterion("add_time is null");
return (Criteria) this;
}
public Criteria andAddTimeIsNotNull() {
addCriterion("add_time is not null");
return (Criteria) this;
}
public Criteria andAddTimeEqualTo(LocalDateTime value) {
addCriterion("add_time =", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddTimeEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("add_time = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeNotEqualTo(LocalDateTime value) {
addCriterion("add_time <>", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddTimeNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("add_time <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeGreaterThan(LocalDateTime value) {
addCriterion("add_time >", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddTimeGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("add_time > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeGreaterThanOrEqualTo(LocalDateTime value) {
addCriterion("add_time >=", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddTimeGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("add_time >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeLessThan(LocalDateTime value) {
addCriterion("add_time <", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddTimeLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("add_time < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeLessThanOrEqualTo(LocalDateTime value) {
addCriterion("add_time <=", value, "addTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andAddTimeLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("add_time <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andAddTimeIn(List<LocalDateTime> values) {
addCriterion("add_time in", values, "addTime");
return (Criteria) this;
}
public Criteria andAddTimeNotIn(List<LocalDateTime> values) {
addCriterion("add_time not in", values, "addTime");
return (Criteria) this;
}
public Criteria andAddTimeBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("add_time between", value1, value2, "addTime");
return (Criteria) this;
}
public Criteria andAddTimeNotBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("add_time not between", value1, value2, "addTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(LocalDateTime value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUpdateTimeEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("update_time = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(LocalDateTime value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUpdateTimeNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("update_time <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(LocalDateTime value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUpdateTimeGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("update_time > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(LocalDateTime value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUpdateTimeGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("update_time >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(LocalDateTime value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUpdateTimeLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("update_time < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(LocalDateTime value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andUpdateTimeLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("update_time <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<LocalDateTime> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<LocalDateTime> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(LocalDateTime value1, LocalDateTime value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andDeletedIsNull() {
addCriterion("deleted is null");
return (Criteria) this;
}
public Criteria andDeletedIsNotNull() {
addCriterion("deleted is not null");
return (Criteria) this;
}
public Criteria andDeletedEqualTo(Boolean value) {
addCriterion("deleted =", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andDeletedEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("deleted = ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedNotEqualTo(Boolean value) {
addCriterion("deleted <>", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andDeletedNotEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("deleted <> ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedGreaterThan(Boolean value) {
addCriterion("deleted >", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andDeletedGreaterThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("deleted > ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedGreaterThanOrEqualTo(Boolean value) {
addCriterion("deleted >=", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andDeletedGreaterThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("deleted >= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedLessThan(Boolean value) {
addCriterion("deleted <", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andDeletedLessThanColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("deleted < ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedLessThanOrEqualTo(Boolean value) {
addCriterion("deleted <=", value, "deleted");
return (Criteria) this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andDeletedLessThanOrEqualToColumn(LitemallAdminOrder.Column column) {
addCriterion(new StringBuilder("deleted <= ").append(column.getEscapedColumnName()).toString());
return (Criteria) this;
}
public Criteria andDeletedIn(List<Boolean> values) {
addCriterion("deleted in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotIn(List<Boolean> values) {
addCriterion("deleted not in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedBetween(Boolean value1, Boolean value2) {
addCriterion("deleted between", value1, value2, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotBetween(Boolean value1, Boolean value2) {
addCriterion("deleted not between", value1, value2, "deleted");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table litemall_admin_order
*
* @mbg.generated do_not_delete_during_merge
*/
public static class Criteria extends GeneratedCriteria {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
private LitemallAdminOrderExample example;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
protected Criteria(LitemallAdminOrderExample example) {
super();
this.example = example;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public LitemallAdminOrderExample example() {
return this.example;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
@Deprecated
public Criteria andIf(boolean ifAdd, ICriteriaAdd add) {
if (ifAdd) {
add.add(this);
}
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria when(boolean condition, ICriteriaWhen then) {
if (condition) {
then.criteria(this);
}
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria when(boolean condition, ICriteriaWhen then, ICriteriaWhen otherwise) {
if (condition) {
then.criteria(this);
} else {
otherwise.criteria(this);
}
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
public Criteria andLogicalDeleted(boolean deleted) {
return deleted ? andDeletedEqualTo(LitemallAdminOrder.Deleted.IS_DELETED.value()) : andDeletedNotEqualTo(LitemallAdminOrder.Deleted.IS_DELETED.value());
}
@Deprecated
public interface ICriteriaAdd {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
Criteria add(Criteria add);
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
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);
}
}
public interface ICriteriaWhen {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
void criteria(Criteria criteria);
}
public interface IExampleWhen {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table litemall_admin_order
*
* @mbg.generated
*/
void example(org.linlinjava.litemall.db.domain.LitemallAdminOrderExample example);
}
}
|
package com.LiftOff.InventoryTrack.data;
public interface StorefrontProductRepository {
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.discovery.MasterNotDiscoveredException;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.node.Node;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import java.io.IOException;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@ClusterScope(scope = Scope.TEST, numDataNodes = 0)
@ESIntegTestCase.SuppressLocalMode
public class SpecificMasterNodesIT extends ESIntegTestCase {
protected final Settings.Builder settingsBuilder() {
return Settings.builder().put("discovery.type", "zen");
}
public void testSimpleOnlyMasterNodeElection() throws IOException {
logger.info("--> start data node / non master node");
internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), true).put(Node.NODE_MASTER_SETTING.getKey(), false).put("discovery.initial_state_timeout", "1s"));
try {
assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().getMasterNodeId(), nullValue());
fail("should not be able to find master");
} catch (MasterNotDiscoveredException e) {
// all is well, no master elected
}
logger.info("--> start master node");
final String masterNodeName = internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), false).put(Node.NODE_MASTER_SETTING.getKey(), true));
assertThat(internalCluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(masterNodeName));
assertThat(internalCluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(masterNodeName));
logger.info("--> stop master node");
internalCluster().stopCurrentMasterNode();
try {
assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().getMasterNodeId(), nullValue());
fail("should not be able to find master");
} catch (MasterNotDiscoveredException e) {
// all is well, no master elected
}
logger.info("--> start master node");
final String nextMasterEligibleNodeName = internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), false).put(Node.NODE_MASTER_SETTING.getKey(), true));
assertThat(internalCluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(nextMasterEligibleNodeName));
assertThat(internalCluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(nextMasterEligibleNodeName));
}
public void testElectOnlyBetweenMasterNodes() throws IOException {
logger.info("--> start data node / non master node");
internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), true).put(Node.NODE_MASTER_SETTING.getKey(), false).put("discovery.initial_state_timeout", "1s"));
try {
assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().getMasterNodeId(), nullValue());
fail("should not be able to find master");
} catch (MasterNotDiscoveredException e) {
// all is well, no master elected
}
logger.info("--> start master node (1)");
final String masterNodeName = internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), false).put(Node.NODE_MASTER_SETTING.getKey(), true));
assertThat(internalCluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(masterNodeName));
assertThat(internalCluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(masterNodeName));
logger.info("--> start master node (2)");
final String nextMasterEligableNodeName = internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), false).put(Node.NODE_MASTER_SETTING.getKey(), true));
assertThat(internalCluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(masterNodeName));
assertThat(internalCluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(masterNodeName));
assertThat(internalCluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(masterNodeName));
logger.info("--> closing master node (1)");
internalCluster().stopCurrentMasterNode();
assertThat(internalCluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(nextMasterEligableNodeName));
assertThat(internalCluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().getMasterNode().getName(), equalTo(nextMasterEligableNodeName));
}
/**
* Tests that putting custom default mapping and then putting a type mapping will have the default mapping merged
* to the type mapping.
*/
public void testCustomDefaultMapping() throws Exception {
logger.info("--> start master node / non data");
internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), false).put(Node.NODE_MASTER_SETTING.getKey(), true));
logger.info("--> start data node / non master node");
internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), true).put(Node.NODE_MASTER_SETTING.getKey(), false));
createIndex("test");
assertAcked(client().admin().indices().preparePutMapping("test").setType("_default_").setSource("_timestamp", "enabled=true"));
MappingMetaData defaultMapping = client().admin().cluster().prepareState().get().getState().getMetaData().getIndices().get("test").getMappings().get("_default_");
assertThat(defaultMapping.getSourceAsMap().get("_timestamp"), notNullValue());
assertAcked(client().admin().indices().preparePutMapping("test").setType("_default_").setSource("_timestamp", "enabled=true"));
assertAcked(client().admin().indices().preparePutMapping("test").setType("type1").setSource("foo", "enabled=true"));
MappingMetaData type1Mapping = client().admin().cluster().prepareState().get().getState().getMetaData().getIndices().get("test").getMappings().get("type1");
assertThat(type1Mapping.getSourceAsMap().get("_timestamp"), notNullValue());
}
public void testAliasFilterValidation() throws Exception {
logger.info("--> start master node / non data");
internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), false).put(Node.NODE_MASTER_SETTING.getKey(), true));
logger.info("--> start data node / non master node");
internalCluster().startNode(settingsBuilder().put(Node.NODE_DATA_SETTING.getKey(), true).put(Node.NODE_MASTER_SETTING.getKey(), false));
assertAcked(prepareCreate("test").addMapping("type1", "{\"type1\" : {\"properties\" : {\"table_a\" : { \"type\" : \"nested\", \"properties\" : {\"field_a\" : { \"type\" : \"keyword\" },\"field_b\" :{ \"type\" : \"keyword\" }}}}}}"));
client().admin().indices().prepareAliases().addAlias("test", "a_test", QueryBuilders.nestedQuery("table_a", QueryBuilders.termQuery("table_a.field_b", "y"))).get();
}
}
|
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Java API Library
*
* Copyright (c) 2017 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.model;
import java.util.List;
import java.util.Objects;
import com.adyen.Util.Util;
import com.adyen.constants.ApiConstants;
import com.adyen.model.additionalData.InvoiceLine;
import com.adyen.model.additionalData.SplitPayment;
import com.adyen.model.additionalData.SplitPaymentItem;
import com.google.gson.annotations.SerializedName;
/**
* PaymentRequest
*/
public class PaymentRequest extends AbstractPaymentRequest<PaymentRequest> {
private static final String ADDITIONAL_DATA = "/authorise-3d-adyen-response";
@SerializedName("card")
private Card card = null;
@SerializedName("mpiData")
private ThreeDSecureData mpiData = null;
@SerializedName("bankAccount")
private BankAccount bankAccount = null;
@SerializedName("store")
private String store = null;
/**
* how the shopper interacts with the system
*/
public enum RecurringProcessingModelEnum {
@SerializedName("Subscription")
SUBSCRIPTION("Subscription"),
@SerializedName("CardOnFile")
CARD_ON_FILE("CardOnFile");
private String value;
RecurringProcessingModelEnum(String value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}
@SerializedName("recurringProcessingModel")
private RecurringProcessingModelEnum recurringProcessingModel = null;
public PaymentRequest setAmountData(String amount, String currency) {
Amount amountData = Util.createAmount(amount, currency);
this.setAmount(amountData);
return this;
}
public PaymentRequest setCSEToken(String cseToken) {
getOrCreateAdditionalData().put(ApiConstants.AdditionalData.Card.Encrypted.JSON, cseToken);
return this;
}
public PaymentRequest setCardData(String cardNumber, String cardHolder, String expiryMonth, String expiryYear, String cvc) {
Card card = new Card();
card.setExpiryMonth(expiryMonth);
card.setExpiryYear(expiryYear);
card.setHolderName(cardHolder);
card.setNumber(cardNumber);
card.setCvc(cvc);
this.setCard(card);
return this;
}
/**
* Set Data needed for payment request using secured fields
*/
public PaymentRequest setSecuredFieldsData(String encryptedCardNumber, String cardHolder, String encryptedExpiryMonth, String encryptedExpiryYear, String encryptedSecurityCode) {
this.setCardHolder(cardHolder)
.setEncryptedCardNumber(encryptedCardNumber)
.setEncryptedExpiryMonth(encryptedExpiryMonth)
.setEncryptedExpiryYear(encryptedExpiryYear)
.setEncryptedSecurityCode(encryptedSecurityCode);
return this;
}
public PaymentRequest setCardHolder(String cardHolder) {
if (card == null) {
card = new Card();
}
card.setHolderName(cardHolder);
return this;
}
public PaymentRequest setEncryptedCardNumber(String encryptedCardNumber) {
getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_CARD_NUMBER, encryptedCardNumber);
return this;
}
public PaymentRequest setEncryptedExpiryMonth(String encryptedExpiryMonth) {
getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_EXPIRY_MONTH, encryptedExpiryMonth);
return this;
}
public PaymentRequest setEncryptedExpiryYear(String encryptedExpiryYear) {
getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_EXPIRY_YEAR, encryptedExpiryYear);
return this;
}
public PaymentRequest setEncryptedSecurityCode(String encryptedSecurityCode) {
getOrCreateAdditionalData().put(ApiConstants.AdditionalData.ENCRYPTED_SECURITY_CODE, encryptedSecurityCode);
return this;
}
public PaymentRequest setPaymentToken(String paymentToken) {
getOrCreateAdditionalData().put(ApiConstants.AdditionalData.PAYMENT_TOKEN, paymentToken);
return this;
}
public RecurringProcessingModelEnum getRecurringProcessingModel() {
return recurringProcessingModel;
}
public PaymentRequest setRecurringProcessingModel(RecurringProcessingModelEnum recurringProcessingModel) {
this.recurringProcessingModel = recurringProcessingModel;
return this;
}
/**
* Set invoiceLines in addtionalData
*/
public PaymentRequest setInvoiceLines(List<InvoiceLine> invoiceLines) {
Integer count = 1;
for (InvoiceLine invoiceLine : invoiceLines) {
StringBuilder sb = new StringBuilder();
sb.append("openinvoicedata.line");
sb.append(Integer.toString(count));
String lineNumber = sb.toString();
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".currencyCode").toString(), invoiceLine.getCurrencyCode());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".description").toString(), invoiceLine.getDescription());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemAmount").toString(), invoiceLine.getItemAmount().toString());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemVatAmount").toString(), invoiceLine.getItemVATAmount().toString());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemVatPercentage").toString(), invoiceLine.getItemVatPercentage().toString());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".numberOfItems").toString(), Integer.toString(invoiceLine.getNumberOfItems()));
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".vatCategory").toString(), invoiceLine.getVatCategory().toString());
// Addional field only for RatePay
if (invoiceLine.getItemId() != null && ! invoiceLine.getItemId().isEmpty()) {
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".itemId").toString(), invoiceLine.getItemId());
}
count++;
}
this.getOrCreateAdditionalData().put("openinvoicedata.numberOfLines", Integer.toString(invoiceLines.size()));
return this;
}
public PaymentRequest setSplitPayment(SplitPayment splitPayment) {
this.getOrCreateAdditionalData().put("split.api", splitPayment.getApi().toString());
this.getOrCreateAdditionalData().put("split.totalAmount", splitPayment.getTotalAmount().toString());
this.getOrCreateAdditionalData().put("split.currencyCode", splitPayment.getCurrencyCode());
Integer count = 1;
for (SplitPaymentItem splitPaymentItem : splitPayment.getSplitPaymentItems()) {
StringBuilder sb = new StringBuilder();
sb.append("split.item");
sb.append(Integer.toString(count));
String lineNumber = sb.toString();
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".amount").toString(), splitPaymentItem.getAmount().toString());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".type").toString(), splitPaymentItem.getType());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".account").toString(), splitPaymentItem.getAccount());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".reference").toString(), splitPaymentItem.getReference());
this.getOrCreateAdditionalData().put(new StringBuilder().append(lineNumber).append(".description").toString(), splitPaymentItem.getDescription());
count++;
}
this.getOrCreateAdditionalData().put("split.nrOfItems", Integer.toString(splitPayment.getSplitPaymentItems().size()));
return this;
}
public PaymentRequest card(Card card) {
this.card = card;
return this;
}
/**
* a representation of a (credit or debit) card
*
* @return card
**/
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public PaymentRequest mpiData(ThreeDSecureData mpiData) {
this.mpiData = mpiData;
return this;
}
/**
* authentication data produced by an MPI (MasterCard SecureCode or Verified By Visa)
*
* @return mpiData
**/
public ThreeDSecureData getMpiData() {
return mpiData;
}
public void setMpiData(ThreeDSecureData mpiData) {
this.mpiData = mpiData;
}
public PaymentRequest bankAccount(BankAccount bankAccount) {
this.bankAccount = bankAccount;
return this;
}
/**
* a representation of a bank account
*
* @return bankAccount
**/
public BankAccount getBankAccount() {
return bankAccount;
}
public void setBankAccount(BankAccount bankAccount) {
this.bankAccount = bankAccount;
}
public PaymentRequest store(String store) {
this.store = store;
return this;
}
/**
* store id from which the payment request is made from
*
* @return store
**/
public String getStore() {
return store;
}
public void setStore(String store) {
this.store = store;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PaymentRequest paymentRequest = (PaymentRequest) o;
return super.equals(paymentRequest)
&& Objects.equals(this.card, paymentRequest.card)
&& Objects.equals(this.mpiData, paymentRequest.mpiData)
&& Objects.equals(this.bankAccount, paymentRequest.bankAccount)
&& Objects.equals(this.store, paymentRequest.store);
}
@Override
public int hashCode() {
return Objects.hash(card, mpiData, bankAccount, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PaymentRequest {\n");
sb.append(super.toString());
sb.append(" mpiData: ").append(toIndentedString(mpiData)).append("\n");
sb.append(" bankAccount: ").append(toIndentedString(bankAccount)).append("\n");
sb.append(" recurringProcessingModel: ").append(toIndentedString(recurringProcessingModel)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package com.example.digitalnoticeboard;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class NativeSignupActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_native_signup);
}
}
|
package com.github.wugenshui.generate.db.doc.mapper;
import com.github.wugenshui.generate.db.doc.entity.TableFileds;
import com.github.wugenshui.generate.db.doc.entity.Tables;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author : chenbo
* @date : 2021-01-25
*/
public interface BaseTableMapper {
/**
* 获取指定数据库下所有表名和注释
*
* @param dbName 数据库名
* @return 表集合
*/
List<Tables> getAllTables(@Param("dbName") String dbName);
/**
* 获取指定表信息
*
* @param tableName 表名
* @return 字段集合
*/
List<TableFileds> getTable(@Param("tableName") String tableName);
}
|
package seedu.address.storage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.commons.util.JsonUtil;
import seedu.address.model.vendor.VendorManager;
import seedu.address.testutil.TypicalVendors;
public class JsonSerializableVendorManagerTest {
private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data",
"JsonSerializableVendorManagerTest");
private static final Path TYPICAL_VENDORS_FILE = TEST_DATA_FOLDER.resolve("typicalVendorManager.json");
private static final Path STORAGE_FILE = TEST_DATA_FOLDER.resolve("storageVendorManager.json");
private static final Path INVALID_VENDOR_FILE = TEST_DATA_FOLDER.resolve("invalidVendorManager.json");
private static final Path DUPLICATE_VENDOR_FILE = TEST_DATA_FOLDER.resolve("duplicateVendorManager.json");
@Test
public void toModelType_typicalVendorsFile_success() throws Exception {
VendorManager book = TypicalVendors.getTypicalVendorManager();
JsonSerializableVendorManager dataFromFile = JsonUtil.readJsonFile(STORAGE_FILE,
JsonSerializableVendorManager.class).get();
VendorManager dataBook = dataFromFile.toModelType();
assertEquals(dataBook, book);
}
@Test
public void toModelType_invalidVendorFile_throwsIllegalValueException() throws Exception {
JsonSerializableVendorManager dataFromFile = JsonUtil.readJsonFile(INVALID_VENDOR_FILE,
JsonSerializableVendorManager.class).get();
assertThrows(IllegalValueException.class, dataFromFile::toModelType);
}
@Test
public void toModelType_duplicateVendors_throwsIllegalValueException() throws Exception {
JsonSerializableVendorManager dataFromFile = JsonUtil.readJsonFile(DUPLICATE_VENDOR_FILE,
JsonSerializableVendorManager.class).get();
assertThrows(IllegalValueException.class, dataFromFile::toModelType);
}
}
|
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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.onosproject.incubator.net.dpi;
import java.util.List;
/**
* Service for DPI Statistics Service Manager.
*/
public interface DpiStatisticsManagerService {
/**
* Get the latest DpiStatistics in the Store list.
*
* @return the DpiStatistics object class or null if not exist
*/
DpiStatistics getDpiStatisticsLatest();
/**
* Get the latest DpiStatistics in the Store list.
*
* @param topnProtocols detected topn protocols, default = 100
* @param topnFlows detected topn known and unknown flows , default = 100
*
* @return the DpiStatistics object class or null if not exist
*/
DpiStatistics getDpiStatisticsLatest(int topnProtocols, int topnFlows);
/**
* Gets the last N(Max = 100) DpiStatistics in the Store list.
*
* @return the List of DpiStatistics object class
*/
List<DpiStatistics> getDpiStatistics(int lastN);
/**
* Gets the last N(Max = 100) DpiStatistics in the Store list.
*
* @param lastN latest N entries
* @param topnProtocols detected topn protocols, default = 100
* @param topnFlows detected topn known and unknown flows , default = 100
* @return the List of DpiStatistics object class
*/
List<DpiStatistics> getDpiStatistics(int lastN, int topnProtocols, int topnFlows);
/**
* Get the specified receivedTime DpiStatistics in the Store list.
*
* @param receivedTime receivedTime string with format "yyyy-MM-dd HH:mm:ss"
* @return the DpiStatistics object class or null if not exist
*/
DpiStatistics getDpiStatistics(String receivedTime);
/**
* Get the specified receivedTime DpiStatistics in the Store list.
*
* @param receivedTime receivedTime string with format "yyyy-MM-dd HH:mm:ss"
* @param topnProtocols detected topn protocols, default = 100
* @param topnFlows detected topn known and unknown flows , default = 100
* @return the DpiStatistics object class or null if not exist
*/
DpiStatistics getDpiStatistics(String receivedTime, int topnProtocols, int topnFlows);
/**
* Adds DpiStatistics at the end of the Store list.
*
* @return the added DpiStatistics object class
*/
DpiStatistics addDpiStatistics(DpiStatistics ds);
}
|
/*
* #%L
* Jetro Patch
* %%
* Copyright (C) 2013 - 2019 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.
* #L%
*/
package net.sf.jetro.patch;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.Test;
import net.sf.jetro.object.serializer.SerializationContext;
import net.sf.jetro.patch.data.AddPatchOperationData;
import net.sf.jetro.patch.data.CopyPatchOperationData;
import net.sf.jetro.patch.data.MovePatchOperationData;
import net.sf.jetro.patch.data.PatchOperationData;
import net.sf.jetro.patch.data.RemovePatchOperationData;
import net.sf.jetro.patch.data.ReplacePatchOperationData;
import net.sf.jetro.patch.data.TestPatchOperationData;
import net.sf.jetro.patch.pointer.JsonPointer;
import net.sf.jetro.tree.JsonArray;
import net.sf.jetro.tree.JsonObject;
import net.sf.jetro.tree.JsonProperty;
@Test(groups = "individualTests")
public class JsonPatchOperationsCollectorTest {
private static final JsonObject SOURCE = new JsonObject();
private JsonPatchOperationsCollector getJsonSourceCollector() {
return new JsonPatchOperationsCollector(SOURCE);
}
@Test
public void testApplyingString() {
JsonPatchApplier applier = getJsonSourceCollector().applying("[]");
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray());
}
@Test
public void testApplyingInputStream() throws IOException {
JsonPatchApplier applier = getJsonSourceCollector().applying(
new ByteArrayInputStream("[]".getBytes("UTF-8")));
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray());
}
@Test
public void testApplyingReader() {
JsonPatchApplier applier = getJsonSourceCollector().applying(new StringReader("[]"));
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray());
}
@Test
public void testApplyingJsonArray() {
JsonPatchApplier applier = getJsonSourceCollector().applying(new JsonArray());
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray());
}
@Test
public void testApplyingJsonObject() {
JsonPatchApplier applier = getJsonSourceCollector().applying(new JsonObject());
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray(
Arrays.asList(new JsonObject())));
}
@Test
public void testApplyingPatchOperationData() {
JsonPointer path = JsonPointer.compile("/a/b/1");
RemovePatchOperationData patchOperation = new RemovePatchOperationData(path);
JsonPatchApplier applier = getJsonSourceCollector().applying(patchOperation);
JsonObject expectedOperation = new JsonObject();
expectedOperation.add(new JsonProperty("op", "remove"));
expectedOperation.add(new JsonProperty("path", path.toString()));
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray(
Arrays.asList(expectedOperation)));
}
@Test
public void testApplyingListOfPatchOperationData() {
JsonPointer path = JsonPointer.compile("/a/b/1");
JsonPointer from = JsonPointer.compile("/a/b/2");
Object value = new ArrayList<>();
List<PatchOperationData> patchOperations = new ArrayList<>();
patchOperations.add(new RemovePatchOperationData(path));
patchOperations.add(new AddPatchOperationData(path, value));
patchOperations.add(new ReplacePatchOperationData(path, value));
patchOperations.add(new TestPatchOperationData(path, value));
patchOperations.add(new MovePatchOperationData(path, from));
patchOperations.add(new CopyPatchOperationData(path, from));
JsonPatchApplier applier = getJsonSourceCollector().applying(patchOperations);
JsonProperty pathProperty = new JsonProperty("path", path.toString());
JsonProperty fromProperty = new JsonProperty("from", from.toString());
JsonProperty valueProperty = new JsonProperty("value", new JsonArray());
JsonObject removeOperation = new JsonObject();
removeOperation.add(new JsonProperty("op", "remove"));
removeOperation.add(pathProperty);
JsonObject addOperation = new JsonObject();
addOperation.add(new JsonProperty("op", "add"));
addOperation.add(pathProperty);
addOperation.add(valueProperty);
JsonObject replaceOperation = new JsonObject();
replaceOperation.add(new JsonProperty("op", "replace"));
replaceOperation.add(pathProperty);
replaceOperation.add(valueProperty);
JsonObject testOperation = new JsonObject();
testOperation.add(new JsonProperty("op", "test"));
testOperation.add(pathProperty);
testOperation.add(valueProperty);
JsonObject moveOperation = new JsonObject();
moveOperation.add(new JsonProperty("op", "move"));
moveOperation.add(pathProperty);
moveOperation.add(fromProperty);
JsonObject copyOperation = new JsonObject();
copyOperation.add(new JsonProperty("op", "copy"));
copyOperation.add(pathProperty);
copyOperation.add(fromProperty);
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray(Arrays.asList(
removeOperation, addOperation, replaceOperation, testOperation,
moveOperation, copyOperation)));
}
@Test
public void testApplyingPatchOperationDataWithContext() {
JsonPointer path = JsonPointer.compile("/a/b/1");
RemovePatchOperationData patchOperation = new RemovePatchOperationData(path);
SerializationContext context = new SerializationContext();
JsonPatchApplier applier = getJsonSourceCollector().applying(patchOperation, context);
JsonObject expectedOperation = new JsonObject();
expectedOperation.add(new JsonProperty("op", "remove"));
expectedOperation.add(new JsonProperty("path", path.toString()));
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray(
Arrays.asList(expectedOperation)));
}
@Test
public void testApplyingListOfPatchOperationDataWithContext() {
JsonPointer path = JsonPointer.compile("/a/b/1");
JsonPointer from = JsonPointer.compile("/a/b/2");
Object value = new ArrayList<>();
List<PatchOperationData> patchOperations = new ArrayList<>();
patchOperations.add(new RemovePatchOperationData(path));
patchOperations.add(new AddPatchOperationData(path, value));
patchOperations.add(new ReplacePatchOperationData(path, value));
patchOperations.add(new TestPatchOperationData(path, value));
patchOperations.add(new MovePatchOperationData(path, from));
patchOperations.add(new CopyPatchOperationData(path, from));
SerializationContext context = new SerializationContext();
JsonPatchApplier applier = getJsonSourceCollector().applying(patchOperations, context);
JsonProperty pathProperty = new JsonProperty("path", path.toString());
JsonProperty fromProperty = new JsonProperty("from", from.toString());
JsonProperty valueProperty = new JsonProperty("value", new JsonArray());
JsonObject removeOperation = new JsonObject();
removeOperation.add(new JsonProperty("op", "remove"));
removeOperation.add(pathProperty);
JsonObject addOperation = new JsonObject();
addOperation.add(new JsonProperty("op", "add"));
addOperation.add(pathProperty);
addOperation.add(valueProperty);
JsonObject replaceOperation = new JsonObject();
replaceOperation.add(new JsonProperty("op", "replace"));
replaceOperation.add(pathProperty);
replaceOperation.add(valueProperty);
JsonObject testOperation = new JsonObject();
testOperation.add(new JsonProperty("op", "test"));
testOperation.add(pathProperty);
testOperation.add(valueProperty);
JsonObject moveOperation = new JsonObject();
moveOperation.add(new JsonProperty("op", "move"));
moveOperation.add(pathProperty);
moveOperation.add(fromProperty);
JsonObject copyOperation = new JsonObject();
copyOperation.add(new JsonProperty("op", "copy"));
copyOperation.add(pathProperty);
copyOperation.add(fromProperty);
assertNotNull(applier);
assertTrue(applier.getSource() == SOURCE);
assertEquals(applier.getPatchOperations(), new JsonArray(Arrays.asList(
removeOperation, addOperation, replaceOperation, testOperation,
moveOperation, copyOperation)));
}
}
|
package webrtccall.fragments;
import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.ale.infra.contact.Contact;
import com.ale.infra.contact.IRainbowContact;
import com.ale.rainbowsdk.RainbowSdk;
import webrtccall.activities.StartupActivity;
import webrtccall.callapplication.R;
public class ContactFragment extends Fragment {
private IRainbowContact m_contact;
private StartupActivity m_activity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.contact_fragment, container, false);
if (m_contact == null)
throw new IllegalStateException();
if (m_activity.getSupportActionBar() != null)
m_activity.getSupportActionBar().setTitle(m_contact.getLastName() + " " + m_contact.getFirstName());
ImageView m_imageViewPhoto = (ImageView)fragmentView.findViewById(R.id.photo_image_view);
if (m_contact.getPhoto() == null) {
m_imageViewPhoto.setImageResource(R.drawable.contact);
} else {
m_imageViewPhoto.setImageBitmap(m_contact.getPhoto());
}
ImageView imageViewCallAudio = (ImageView)fragmentView.findViewById(R.id.call_audio_button);
imageViewCallAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// In an audio call, if the Android version is more than M, check if the permission "RECORD_AUDIO" is granted.
// If not, ask for it.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || m_activity.hasMicrophonePermission()) {
// The Android version is lower than M OR we already have the permission "RECORD_AUDIO" --> just make the audio call
RainbowSdk.instance().webRTC().makeCall((Contact)m_contact, false);
} else {
// We have to ask for the permission "RECORD_AUDIO" first.
ActivityCompat.requestPermissions(m_activity, new String[] {Manifest.permission.RECORD_AUDIO}, StartupActivity.REQUEST_MAKE_AUDIO_CALL);
}
}
});
ImageView imageViewCallVideo = (ImageView)fragmentView.findViewById(R.id.call_video_button);
imageViewCallVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// In a video call, if the Android version is more than M, check if the permission "RECORD_AUDIO" and "CAMERA" are granted.
// If not, ask for them.
boolean hasMicrophonePermission = m_activity.hasMicrophonePermission();
boolean hasCameraPermission = m_activity.hasCameraPermission();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || hasMicrophonePermission && hasCameraPermission) {
// The Android version is lower than M OR we already have the permissions "RECORD_AUDIO" and "CAMERA" --> just make the video call
RainbowSdk.instance().webRTC().makeCall((Contact) m_contact, true);
} else {
if (!hasMicrophonePermission && !hasCameraPermission) {
// Both permissions are missing --> ask for them
ActivityCompat.requestPermissions(m_activity, new String[] {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA}, StartupActivity.REQUEST_MAKE_VIDEO_CALL);
} else if (!hasMicrophonePermission){
// Permission "RECORD_AUDIO" is missing --> ask for it
ActivityCompat.requestPermissions(m_activity, new String[] {Manifest.permission.RECORD_AUDIO}, StartupActivity.REQUEST_MAKE_VIDEO_CALL);
} else {
// Permission "CAMERA" is missing --> ask for it
ActivityCompat.requestPermissions(m_activity, new String[] {Manifest.permission.CAMERA}, StartupActivity.REQUEST_MAKE_VIDEO_CALL);
}
}
}
});
return fragmentView;
}
@Override
public void onAttach(Context context)
{
super.onAttach(context);
if (context instanceof StartupActivity){
m_activity = (StartupActivity) context;
}
}
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (activity instanceof StartupActivity) {
m_activity = (StartupActivity)activity;
}
}
}
public void setContact(IRainbowContact contact) {
m_contact = contact;
}
}
|
package diploma.services.mail.html;
import java.util.ArrayList;
import java.util.List;
import net.percederberg.grammatica.parser.Node;
import net.percederberg.grammatica.parser.ParseException;
import net.percederberg.grammatica.parser.Production;
import net.percederberg.grammatica.parser.Token;
/**
* A class providing callback methods for the parser.
*
* @author Serban Petrescu
*/
class Analyzer extends HtmlAnalyzer {
/**
* Removes the dollar sign and white spaces from variable names.
*
* @param name
* The given variable name.
* @return A trimmed version of the name.
*/
private static String removeDollar(String name) {
name = name.trim();
if (name.length() < 1) {
return "";
} else {
return name.substring(1);
}
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitDollar(Token node) throws ParseException {
node.addValue(new Content.Literal("$"));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitVariable(Token node) throws ParseException {
String name = removeDollar(node.getImage());
node.addValue(new Content.Variable(name));
node.addValue(name);
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitParsedLiteral(Token node) throws ParseException {
String quoted = removeDollar(node.getImage());
if (quoted.length() < 2) {
node.addValue(new Content.Literal(""));
} else {
node.addValue(new Content.Literal(quoted.substring(1, quoted.length() - 1)));
}
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitLiteral(Token node) throws ParseException {
node.addValue(new Content.Literal(node.getImage()));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitEmail(Production node) throws ParseException {
node.addValue(node.getChildAt(0).getValue(0));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitContent(Production node) throws ParseException {
List<Content> list = new ArrayList<Content>();
for (int i = 0; i < node.getChildCount(); ++i) {
list.add((Content) node.getChildAt(i).getValue(0));
}
node.addValue(new Content.Composite(list));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitPlain(Production node) throws ParseException {
List<Content> list = new ArrayList<Content>();
for (int i = 0; i < node.getChildCount(); ++i) {
list.add((Content) node.getChildAt(i).getValue(0));
}
node.addValue(new Content.Composite(list));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitInstruction(Production node) throws ParseException {
node.addValue(node.getChildAt(0).getValue(0));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitIf(Production node) throws ParseException {
if (node.getChildCount() == 6) {
node.addValue(new Content.IfThenElse((Content) node.getChildAt(1).getValue(0),
(Content) node.getChildAt(2).getValue(0), (Content) node.getChildAt(4).getValue(0)));
} else {
node.addValue(new Content.IfThenElse((Content) node.getChildAt(1).getValue(0),
(Content) node.getChildAt(2).getValue(0)));
}
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitFor(Production node) throws ParseException {
node.addValue(
new Content.ForLoop((String) node.getChildAt(1).getValue(1), (Content) node.getChildAt(2).getValue(0)));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitOutput(Production node) throws ParseException {
node.addValue(node.getChildAt(1).getValue(0));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitExpression(Production node) throws ParseException {
node.addValue(node.getChildAt(0).getValue(0));
return node;
}
/**
* Called when exiting a parse tree node.
*
* @param node
* the node being exited
*
* @return the node to add to the parse tree, or null if no parse tree
* should be created
*
* @throws ParseException
* if the node analysis discovered errors
*/
@Override
protected Node exitCall(Production node) throws ParseException {
String name = (String) node.getChildAt(1).getValue(1);
List<Content> params = new ArrayList<Content>();
for (int i = 2; i < node.getChildCount(); ++i) {
params.add((Content) node.getChildAt(i).getValue(0));
}
node.addValue(new Content.Call(name, params));
return node;
}
}
|
package cn.itrip.trade.config;
public class AlipayConfig {
// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
private String appID;
// 商户私钥,您的PKCS8格式RSA2私钥
private String rsaPrivateKey;
// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
private String alipayPublicKey;
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
private String notifyUrl;
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
private String returnUrl;
// 签名方式
private String signType;
// 字符编码格式
private String charset;
// 支付宝网关
private String url;
// 支付宝网关
private String logPath;
//数据格式类型
private String format;
//支付成功
private String paymentSuccessUrl;
//支付失败
private String paymentFailureUrl;
public String getAppID() {
return appID;
}
public void setAppID(String appID) {
this.appID = appID;
}
public String getRsaPrivateKey() {
return rsaPrivateKey;
}
public void setRsaPrivateKey(String rsaPrivateKey) {
this.rsaPrivateKey = rsaPrivateKey;
}
public String getAlipayPublicKey() {
return alipayPublicKey;
}
public void setAlipayPublicKey(String alipayPublicKey) {
this.alipayPublicKey = alipayPublicKey;
}
public String getNotifyUrl() {
return notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public String getReturnUrl() {
return returnUrl;
}
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
public String getSignType() {
return signType;
}
public void setSignType(String signType) {
this.signType = signType;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getLogPath() {
return logPath;
}
public void setLogPath(String logPath) {
this.logPath = logPath;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getPaymentSuccessUrl() {
return paymentSuccessUrl;
}
public void setPaymentSuccessUrl(String paymentSuccessUrl) {
this.paymentSuccessUrl = paymentSuccessUrl;
}
public String getPaymentFailureUrl() {
return paymentFailureUrl;
}
public void setPaymentFailureUrl(String paymentFailureUrl) {
this.paymentFailureUrl = paymentFailureUrl;
}
}
|
package io.boostcd.todo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.client.RestTemplate;
import io.jaegertracing.Configuration;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public io.opentracing.Tracer jaegerTracer() {
return new Configuration(System.getenv("JAEGER_SERVICE_NAME"))
.withReporter(Configuration.ReporterConfiguration.fromEnv())
.withSampler(Configuration.SamplerConfiguration.fromEnv())
.getTracer();
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
}
|
/* ©Copyright 2011 Cameron Morris
*
* 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.owasp.passfault;
import org.junit.Test;
import org.owasp.passfault.api.PatternFinder;
import org.owasp.passfault.impl.FinderByPropsBuilder;
import java.io.File;
import java.util.Collection;
import static org.junit.Assert.assertTrue;
public class FinderByPropsBuilderTest {
@Test
public void byFile() throws Exception {
System.out.println("current directory:" + new File(".").getCanonicalFile());
File file = new File("src/test/resources/wordlists");
assertTrue(file.exists());
Collection<PatternFinder> finders = new FinderByPropsBuilder().
isInMemory(false).
setFileLoader(file).
build();
System.out.println("Finders found " + finders);
assertTrue(finders.size() > 4);
}
//@Test() the word lists are no longer embedded.
public void byResource() throws Exception {
Collection<PatternFinder> finders = new FinderByPropsBuilder().
loadDefaultWordLists().
isInMemory(true).
build();
System.out.println("Finders found " + finders);
assertTrue(finders.size() > 4);
}
}
|
package ro.msg.learning.shop;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/index").setViewName("index");
}
}
|
package com.example.geektrust;
public class Ratio {
double corporationWater;
double borewellWater;
public Ratio(String ratioString) {
String[] ratioTokens = ratioString.split(":");
int corporationRatio = Integer.parseInt(ratioTokens[0]);
int borewellRatio = Integer.parseInt(ratioTokens[1]);
corporationWater = corporationRatio /(1.0 * (corporationRatio + borewellRatio));
borewellWater = borewellRatio / (1.0 * (borewellRatio + corporationRatio));
}
}
|
package com.github.discvrseq.tools;
import org.broadinstitute.barclay.argparser.CommandLineProgramGroup;
/**
* Created by bimber on 8/1/2017.
*/
public class VariantManipulationProgramGroup implements CommandLineProgramGroup {
@Override
public String getName() {
return "Variant Manipulation";
}
@Override
public String getDescription() {
return "These tools perform manipulation/QC of variant data, and should be rigorously validated and stable.";
}
}
|
package carbon.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.view.ViewHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import carbon.Carbon;
import carbon.R;
import carbon.animation.AnimUtils;
import carbon.animation.StateAnimator;
import carbon.drawable.RippleDrawable;
import carbon.drawable.RippleView;
import carbon.internal.ElevationComparator;
import carbon.shadow.Shadow;
import carbon.shadow.ShadowGenerator;
import carbon.shadow.ShadowView;
/**
* Created by Marcin on 2014-11-20.
*/
public class FrameLayout extends android.widget.FrameLayout implements ShadowView, RippleView, TouchMarginView, StateAnimatorView, AnimatedView {
private boolean debugMode;
public FrameLayout(Context context) {
this(context,null);
}
public FrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.carbon_frameLayoutStyle);
}
public FrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr);
}
private void init(AttributeSet attrs, int defStyleAttr) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FrameLayout, defStyleAttr, 0);
Carbon.initRippleDrawable(this, attrs, defStyleAttr);
setElevation(a.getDimension(R.styleable.FrameLayout_carbon_elevation, 0));
Carbon.initAnimations(this, attrs, defStyleAttr);
Carbon.initTouchMargin(this, attrs, defStyleAttr);
setCornerRadius(a.getDimension(R.styleable.FrameLayout_carbon_cornerRadius, 0));
a.recycle();
if (isInEditMode()) {
a = getContext().obtainStyledAttributes(attrs, R.styleable.Carbon, defStyleAttr, 0);
debugMode = a.getBoolean(R.styleable.Carbon_carbon_debugMode, false);
a.recycle();
}
setChildrenDrawingOrderEnabled(true);
setClipToPadding(false);
}
List<View> views;
Map<View, Shadow> shadows = new HashMap<>();
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (debugMode)
Carbon.drawDebugInfo(this, canvas);
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
if (!child.isShown())
return super.drawChild(canvas, child, drawingTime);
if (!isInEditMode() && child instanceof ShadowView) {
ShadowView shadowView = (ShadowView) child;
float elevation = shadowView.getElevation() + shadowView.getTranslationZ();
if (elevation >= 0.01f) {
Shadow shadow = shadows.get(child);
if (shadow == null || shadow.elevation != elevation) {
shadow = ShadowGenerator.generateShadow(child, elevation);
shadows.put(child, shadow);
}
paint.setAlpha((int) (127 * ViewHelper.getAlpha(child)));
int[] location = new int[2];
child.getLocationOnScreen(location);
float x = location[0] + child.getWidth() / 2.0f;
float y = location[1] + child.getHeight() / 2.0f;
x -= getRootView().getWidth() / 2;
y += getRootView().getHeight() / 2; // looks nice
float length = (float) Math.sqrt(x * x + y * y);
int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.translate(
x / length * elevation / 2,
y / length * elevation / 2);
canvas.translate(
child.getLeft(),
child.getTop());
if (Build.VERSION.SDK_INT >= 11) {
canvas.concat(child.getMatrix());
} else {
canvas.concat(carbon.internal.ViewHelper.getMatrix(child));
}
canvas.scale(ShadowGenerator.SHADOW_SCALE, ShadowGenerator.SHADOW_SCALE);
shadow.draw(canvas, child, paint);
canvas.restoreToCount(saveCount);
}
}
if (child instanceof RippleView) {
RippleView rippleView = (RippleView) child;
RippleDrawable rippleDrawable = rippleView.getRippleDrawable();
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless) {
int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.translate(
child.getLeft(),
child.getTop());
rippleDrawable.draw(canvas);
canvas.restoreToCount(saveCount);
}
}
return super.drawChild(canvas, child, drawingTime);
}
@Override
protected int getChildDrawingOrder(int childCount, int child) {
if(views==null||views.size()!=getChildCount()) {
views = new ArrayList<View>();
for (int i = 0; i < getChildCount(); i++)
views.add(getChildAt(i));
Collections.sort(views, new ElevationComparator());
}
return views.indexOf(getChildAt(child));
}
protected boolean isTransformedTouchPointInView(float x, float y, View child, PointF outLocalPoint) {
final Rect frame = new Rect();
child.getHitRect(frame);
if (frame.contains((int) x, (int) y)) {
return true;
}
return false;
}
// -------------------------------
// corners
// -------------------------------
private float cornerRadius;
private Canvas textureCanvas;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
public float getCornerRadius() {
return cornerRadius;
}
public void setCornerRadius(float cornerRadius) {
this.cornerRadius = cornerRadius;
initDrawing();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (!changed || getWidth() == 0 || getHeight() == 0)
return;
initDrawing();
if (rippleDrawable != null)
rippleDrawable.setBounds(0, 0, getWidth(), getHeight());
}
private void initDrawing() {
if (cornerRadius == 0 || getWidth() == 0 || getHeight() == 0)
return;
Bitmap texture = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
textureCanvas = new Canvas(texture);
paint.setShader(new BitmapShader(texture, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
}
@Override
public void draw(Canvas canvas) {
if (cornerRadius > 0 && getWidth() > 0 && getHeight() > 0) {
textureCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
super.draw(textureCanvas);
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Over)
rippleDrawable.draw(textureCanvas);
RectF rect = new RectF();
rect.bottom = getHeight();
rect.right = getWidth();
paint.setAlpha(255);
canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint);
} else {
super.draw(canvas);
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Over)
rippleDrawable.draw(canvas);
}
}
// -------------------------------
// ripple
// -------------------------------
private RippleDrawable rippleDrawable;
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (rippleDrawable != null && event.getAction() == MotionEvent.ACTION_DOWN)
((RippleDrawable) rippleDrawable).setHotspot(event.getX(), event.getY());
return super.dispatchTouchEvent(event);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
setTranslationZ(enabled ? 0 : -elevation);
}
@Override
public RippleDrawable getRippleDrawable() {
return rippleDrawable;
}
public void setRippleDrawable(RippleDrawable rippleDrawable) {
this.rippleDrawable = rippleDrawable;
}
@Override
protected boolean verifyDrawable(Drawable who) {
return super.verifyDrawable(who) || rippleDrawable == who;
}
@Override
public void invalidateDrawable(Drawable drawable) {
super.invalidateDrawable(drawable);
if (rippleDrawable != null && getParent() != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).postInvalidate();
}
@Override
public void setBackground(Drawable background) {
setBackgroundDrawable(background);
}
@Override
public void setBackgroundDrawable(Drawable background) {
if (rippleDrawable == null || rippleDrawable.getBackground() == null) {
super.setBackgroundDrawable(background);
return;
}
rippleDrawable.setBackground(background);
super.setBackgroundDrawable(rippleDrawable);
}
// -------------------------------
// elevation
// -------------------------------
private float elevation = 0;
private float translationZ = 0;
private boolean isRect = true;
@Override
public float getElevation() {
return elevation;
}
public synchronized void setElevation(float elevation) {
elevation = Math.max(0, Math.min(elevation, 25));
if (elevation == this.elevation)
return;
this.elevation = elevation;
if (getParent() != null)
((View) getParent()).postInvalidate();
}
@Override
public float getTranslationZ() {
return translationZ;
}
public synchronized void setTranslationZ(float translationZ) {
if (translationZ == this.translationZ)
return;
this.translationZ = translationZ;
if (getParent() != null)
((View) getParent()).postInvalidate();
}
@Override
public boolean isRect() {
return isRect;
}
@Override
public void setRect(boolean rect) {
this.isRect = rect;
}
// -------------------------------
// touch margin
// -------------------------------
private Rect touchMargin;
@Override
public void setTouchMargin(Rect rect) {
touchMargin = rect;
}
@Override
public void setTouchMargin(int left, int top, int right, int bottom) {
touchMargin = new Rect(left, top, right, bottom);
}
@Override
public Rect getTouchMargin() {
return touchMargin;
}
public void getHitRect(Rect outRect) {
if (touchMargin == null) {
super.getHitRect(outRect);
return;
}
outRect.set(getLeft() - touchMargin.left, getTop() - touchMargin.top, getRight() + touchMargin.right, getBottom() + touchMargin.bottom);
}
// -------------------------------
// state animators
// -------------------------------
private List<StateAnimator> stateAnimators = new ArrayList<>();
public void removeStateAnimator(StateAnimator animator) {
stateAnimators.remove(animator);
}
public void addStateAnimator(StateAnimator animator) {
this.stateAnimators.add(animator);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (stateAnimators != null)
for (StateAnimator animator : stateAnimators)
animator.stateChanged(getDrawableState());
}
// -------------------------------
// animations
// -------------------------------
private AnimUtils.Style inAnim, outAnim;
public void setVisibility(final int visibility) {
if (getVisibility() != View.VISIBLE && visibility == View.VISIBLE && inAnim != null) {
AnimUtils.animateIn(this, inAnim, null);
super.setVisibility(visibility);
} else if (getVisibility() == View.VISIBLE && visibility != View.VISIBLE) {
AnimUtils.animateOut(this, outAnim, new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
FrameLayout.super.setVisibility(visibility);
}
});
}
}
public AnimUtils.Style getOutAnimation() {
return outAnim;
}
public void setOutAnimation(AnimUtils.Style outAnim) {
this.outAnim = outAnim;
}
public AnimUtils.Style getInAnimation() {
return inAnim;
}
public void setInAnimation(AnimUtils.Style inAnim) {
this.inAnim = inAnim;
}
}
|
/**
* Copyright 2009-2013 The Australian National University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package au.edu.anu.portal.portlets.sakaiconnector.models;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
* An object to store information about a tool.
*
* @author Steve Swinsburg (steve.swinsburg@anu.edu.au)
*
*/
@NoArgsConstructor
@Data
@Root(name="tool")
public class Tool {
@Attribute(name="id")
private String id;
@Element(name="tool-id")
private String registrationId;
@Element(name="tool-title")
private String title;
}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright 2019 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://www.apache.org/licenses/LICENSE-2.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.amazon.opendistroforelasticsearch.sql.legacy.executor.adapter;
import com.amazon.opendistroforelasticsearch.sql.legacy.query.QueryAction;
import com.amazon.opendistroforelasticsearch.sql.legacy.query.SqlElasticRequestBuilder;
import com.google.common.base.Strings;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* The definition of QueryPlan of QueryAction which works as the adapter to the current QueryAction framework.
*/
public class QueryPlanQueryAction extends QueryAction {
private final QueryPlanRequestBuilder requestBuilder;
public QueryPlanQueryAction(QueryPlanRequestBuilder requestBuilder) {
super(null, null);
this.requestBuilder = requestBuilder;
}
@Override
public SqlElasticRequestBuilder explain() {
return requestBuilder;
}
@Override
public Optional<List<String>> getFieldNames() {
List<String> fieldNames = ((QueryPlanRequestBuilder) requestBuilder).outputColumns()
.stream()
.map(node -> Strings.isNullOrEmpty(node.getAlias()) ? node.getName() : node.getAlias())
.collect(Collectors.toList());
return Optional.of(fieldNames);
}
}
|
package com.github.shareme.greenandroid.spinkitapp;
/**
* Created by ybq.
*/
public interface Colors {
int[] colors = new int[]{
android.graphics.Color.parseColor("#D55400"),
android.graphics.Color.parseColor("#2B3E51"),
android.graphics.Color.parseColor("#00BD9C"),
android.graphics.Color.parseColor("#227FBB"),
android.graphics.Color.parseColor("#7F8C8D"),
android.graphics.Color.parseColor("#FFCC5C"),
android.graphics.Color.parseColor("#D55400"),
android.graphics.Color.parseColor("#1AAF5D"),
};
}
|
package algorithms;
import lombok.extern.slf4j.Slf4j;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@Slf4j
public class AddBinary {
// Example 1:
//
// Input: a = "11", b = "1"
// Output: "100"
// Example 2:
//
// Input: a = "1010", b = "1011"
// Output: "10101"
public static String addBinary(String a, String b) {
char[] array_a;
char[] array_b;
boolean aIsLonger = a.length() > b.length();
if (aIsLonger) {
array_a = reverse(a.toCharArray(), a.length());
array_b = reverse(b.toCharArray(), b.length());
} else {
array_a = reverse(b.toCharArray(), b.length());
array_b = reverse(a.toCharArray(), a.length());
}
StringBuilder result = new StringBuilder();
char adder = '0';
for (int i = 0; i < array_b.length; i++) {
adder = addBinaryRecursive(array_a[i], array_b[i], adder, result);
}
int lengthDiff = array_a.length - array_b.length;
for (int i = 0; i < lengthDiff; i++) {
adder = addBinaryRecursive(array_a[i+array_b.length],'0', adder, result);
}
if (adder == '1'){
result.insert(0, String.valueOf(1));
}
return result.toString();
}
private static char addBinaryRecursive(char a, char b, char adder, StringBuilder result){
if (adder == '0'){
if ((a == '1') && (b == '1')) {
result.insert(0, String.valueOf(0));
return '1';
} else if ((a == '0') && (b == '0')){
result.insert(0, String.valueOf(0));
return '0';
} else {
result.insert(0, String.valueOf(1));
return '0';
}
} else {
if ((a == '1') && (b == '1')) {
result.insert(0, String.valueOf(1));
return '1';
} else if ((a == '0') && (b == '0')){
result.insert(0, String.valueOf(1));
return '0';
} else {
result.insert(0, String.valueOf(0));
return '1';
}
}
}
static char[] reverse(char a[], int n)
{
char i, k, t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
return a;
}
public static void main(String[] args) {
String a = "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101";
String b = "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011";
String a_1 = "100";
String b_1 = "110010";
log.info("ANSWER: {}",addBinary(a_1, b_1));
}
}
|
package com.hockeyhurd.item.renderer;
import net.minecraft.client.model.ModelChest;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.IItemRenderer;
import com.hockeyhurd.entity.tileentity.TileEntityGlowChest;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ItemRendererGlowChest implements IItemRenderer {
private ModelChest chestModel;
public ItemRendererGlowChest() {
}
public boolean handleRenderType(ItemStack stack, ItemRenderType type) {
return true;
}
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack stack, ItemRendererHelper helper) {
return true;
}
public void renderItem(ItemRenderType type, ItemStack stack, Object... data) {
TileEntityRendererDispatcher.instance.renderTileEntityAt(new TileEntityGlowChest(), 0.0d, 0.0d, 0.0d, 0.0f);
}
}
|
/*
* Copyright 2002-2021 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.util;
import org.junit.jupiter.api.Test;
import org.springframework.util.StopWatch.TaskInfo;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Unit tests for {@link StopWatch}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
*/
class StopWatchTests {
private static final String ID = "myId";
private static final String name1 = "Task 1";
private static final String name2 = "Task 2";
private static final long duration1 = 200;
private static final long duration2 = 100;
private static final long fudgeFactor = 100;
private final StopWatch stopWatch = new StopWatch(ID);
@Test
void failureToStartBeforeGettingTimings() {
assertThatIllegalStateException().isThrownBy(stopWatch::getLastTaskTimeMillis);
}
@Test
void failureToStartBeforeStop() {
assertThatIllegalStateException().isThrownBy(stopWatch::stop);
}
@Test
void rejectsStartTwice() {
stopWatch.start();
assertThat(stopWatch.isRunning()).isTrue();
stopWatch.stop();
assertThat(stopWatch.isRunning()).isFalse();
stopWatch.start();
assertThat(stopWatch.isRunning()).isTrue();
assertThatIllegalStateException().isThrownBy(stopWatch::start);
}
@Test
void validUsage() throws Exception {
assertThat(stopWatch.isRunning()).isFalse();
stopWatch.start(name1);
Thread.sleep(duration1);
assertThat(stopWatch.isRunning()).isTrue();
assertThat(stopWatch.currentTaskName()).isEqualTo(name1);
stopWatch.stop();
assertThat(stopWatch.isRunning()).isFalse();
assertThat(stopWatch.getLastTaskTimeNanos())
.as("last task time in nanoseconds for task #1")
.isGreaterThanOrEqualTo(millisToNanos(duration1 - fudgeFactor))
.isLessThanOrEqualTo(millisToNanos(duration1 + fudgeFactor));
assertThat(stopWatch.getTotalTimeMillis())
.as("total time in milliseconds for task #1")
.isGreaterThanOrEqualTo(duration1 - fudgeFactor)
.isLessThanOrEqualTo(duration1 + fudgeFactor);
assertThat(stopWatch.getTotalTimeSeconds())
.as("total time in seconds for task #1")
.isGreaterThanOrEqualTo((duration1 - fudgeFactor) / 1000.0)
.isLessThanOrEqualTo((duration1 + fudgeFactor) / 1000.0);
stopWatch.start(name2);
Thread.sleep(duration2);
assertThat(stopWatch.isRunning()).isTrue();
assertThat(stopWatch.currentTaskName()).isEqualTo(name2);
stopWatch.stop();
assertThat(stopWatch.isRunning()).isFalse();
assertThat(stopWatch.getLastTaskTimeNanos())
.as("last task time in nanoseconds for task #2")
.isGreaterThanOrEqualTo(millisToNanos(duration2))
.isLessThanOrEqualTo(millisToNanos(duration2 + fudgeFactor));
assertThat(stopWatch.getTotalTimeMillis())
.as("total time in milliseconds for tasks #1 and #2")
.isGreaterThanOrEqualTo(duration1 + duration2 - fudgeFactor)
.isLessThanOrEqualTo(duration1 + duration2 + fudgeFactor);
assertThat(stopWatch.getTotalTimeSeconds())
.as("total time in seconds for task #2")
.isGreaterThanOrEqualTo((duration1 + duration2 - fudgeFactor) / 1000.0)
.isLessThanOrEqualTo((duration1 + duration2 + fudgeFactor) / 1000.0);
assertThat(stopWatch.getTaskCount()).isEqualTo(2);
assertThat(stopWatch.prettyPrint()).contains(name1, name2);
assertThat(stopWatch.getTaskInfo()).extracting(TaskInfo::getTaskName).containsExactly(name1, name2);
assertThat(stopWatch.toString()).contains(ID, name1, name2);
assertThat(stopWatch.getId()).isEqualTo(ID);
}
@Test
void validUsageDoesNotKeepTaskList() throws Exception {
stopWatch.setKeepTaskList(false);
stopWatch.start(name1);
Thread.sleep(duration1);
assertThat(stopWatch.currentTaskName()).isEqualTo(name1);
stopWatch.stop();
stopWatch.start(name2);
Thread.sleep(duration2);
assertThat(stopWatch.currentTaskName()).isEqualTo(name2);
stopWatch.stop();
assertThat(stopWatch.getTaskCount()).isEqualTo(2);
assertThat(stopWatch.prettyPrint()).contains("No task info kept");
assertThat(stopWatch.toString()).doesNotContain(name1, name2);
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(stopWatch::getTaskInfo)
.withMessage("Task info is not being kept!");
}
private static long millisToNanos(long duration) {
return MILLISECONDS.toNanos(duration);
}
}
|
package star.lut.com.chatdemo.dataModels.sendModel;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by kamrulhasan on 28/10/18.
*/
public class LoginSendModel {
@SerializedName("username")
@Expose
public String username;
@SerializedName("password")
@Expose
public String password;
@Override
public String toString() {
return "LoginSendModel{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
|
package com.bazl.dna.lims.core.service.impl;
import com.bazl.dna.lims.core.dao.LoaRoleRelationMapper;
import com.bazl.dna.lims.core.model.po.LoaRoleRelation;
import com.bazl.dna.lims.core.service.LoaRoleRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Administrator on 2018/12/21.
*/
@Service
public class LoaRoleRelationServiceImpl implements LoaRoleRelationService{
@Autowired
private LoaRoleRelationMapper loaRoleRelationMapper;
@Override
public void addLoaRoleRelation(LoaRoleRelation loaRoleRelation) {
loaRoleRelationMapper.addLoaRoleRelation(loaRoleRelation);
}
@Override
public void deleteloaRoleRelationByUserId(String userId) {
loaRoleRelationMapper.deleteloaRoleRelationByUserId(userId);
}
@Override
public void updateloaRoleRelationByUserId(String roleId, String userId) {
loaRoleRelationMapper.updateloaRoleRelationByUserId(roleId,userId);
}
/**
* 通过用户Id获取关联的角色
* @param userId
* @return
*/
@Override
public List<LoaRoleRelation> listByUserId(String userId) {
return loaRoleRelationMapper.listByUserId(userId);
}
}
|
package com.xy1m.cci.chapter10_sorting_searching;
import java.util.Arrays;
/**
* Sorted Merge: You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B.
* Write a method to merge B into A in sorted order.
*/
public class Q10_01_Sorted_Merge {
static void merge(int[] a, int[] b, int sizeA, int sizeB) {
int indexA = sizeA - 1;
int indexB = sizeB - 1;
int indexMerged = sizeA + sizeB - 1;
while (indexB >= 0) {
if (indexA >= 0 && a[indexA] > b[indexB]) {
a[indexMerged] = a[indexA--];
}
else {
a[indexMerged] = b[indexB--];
}
indexMerged--;
}
}
public static void main(String[] args) {
int[] a = new int[10];
Arrays.fill(a, -1);
a[0] = 1;
a[1] = 3;
a[2] = 5;
a[3] = 7;
a[4] = 9;
int[] b = new int[]{2, 4, 6, 8};
merge(a, b, 5, 4);
for (int i : a) {
System.out.println(i);
}
}
}
|
package com.wvkity.mybatis.core.constant;
/**
* 执行处理枚举类
* @author wvkity
*/
public enum Execute {
/**
* 不操作
*/
NONE,
/**
* 保存
*/
INSERT,
/**
* 替换(更新)
*/
REPLACE
}
|
package org.example.seed.domain;
import lombok.Getter;
import lombok.Setter;
import org.example.seed.constraint.Location;
import org.example.seed.group.address.AddressCreateGroup;
import org.example.seed.group.address.AddressUpdateGroup;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.UUID;
/**
* Created by PINA on 30/06/2017.
*/
@Getter
@Setter
public class Address extends Dates {
@NotEmpty(groups = {AddressUpdateGroup.class})
@Size(min = 36, max = 36, groups = {AddressUpdateGroup.class})
private String id;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 1, max = 5, groups = {AddressCreateGroup.class})
private String intNumber;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 1, max = 5, groups = {AddressCreateGroup.class})
private String exNumber;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 1, max = 5, groups = {AddressCreateGroup.class})
private String block;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 1, max = 5, groups = {AddressCreateGroup.class})
private String number;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 3, max = 15, groups = {AddressCreateGroup.class})
private String street;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 3, max = 15, groups = {AddressCreateGroup.class})
private String colony;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 3, max = 20, groups = {AddressCreateGroup.class})
private String municipality;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 3, max = 15, groups = {AddressCreateGroup.class})
private String state;
@Location(groups = {AddressCreateGroup.class})
@NotEmpty(groups = {AddressCreateGroup.class})
@Size(min = 3, max = 10, groups = {AddressCreateGroup.class})
private String country;
public Address() {
this.id = UUID.randomUUID().toString();
}
}
|
/*
* Copyright (C) 2017 优客服-多渠道客服系统
* Modifications copyright (C) 2018-2019 Chatopera Inc, <https://www.chatopera.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.chatopera.cc.persistence.es;
import com.chatopera.cc.model.KbsTopic;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
@Component
public class KbsTopicRepositoryImpl implements KbsTopicEsCommonRepository{
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
public void setElasticsearchTemplate(ElasticsearchTemplate elasticsearchTemplate) {
this.elasticsearchTemplate = elasticsearchTemplate;
}
@Override
public Page<KbsTopic> getTopicByCate(String cate , String q, final int p , final int ps) {
Page<KbsTopic> pages = null ;
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(termQuery("cate" , cate)) ;
if(!StringUtils.isBlank(q)){
boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
}
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
if(elasticsearchTemplate.indexExists(KbsTopic.class)){
pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class , new UKResultMapper());
}
return pages ;
}
@SuppressWarnings("deprecation")
@Override
public Page<KbsTopic> getTopicByTop(boolean top , final int p , final int ps) {
Page<KbsTopic> pages = null ;
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(termQuery("top" , top)) ;
QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").from(new Date().getTime())) ;
QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").to(new Date().getTime())) ;
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
if(elasticsearchTemplate.indexExists(KbsTopic.class)){
pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class , new UKResultMapper());
}
return pages ;
}
@Override
public Page<KbsTopic> getTopicByCateAndUser(String cate , String q , String user ,final int p , final int ps) {
Page<KbsTopic> pages = null ;
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(termQuery("cate" , cate)) ;
if(!StringUtils.isBlank(q)){
boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
}
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withQuery(termQuery("creater" , user)).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps));
if(elasticsearchTemplate.indexExists(KbsTopic.class)){
pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class, new UKResultMapper());
}
return pages ;
}
@SuppressWarnings("deprecation")
@Override
public Page<KbsTopic> getTopicByCon(BoolQueryBuilder boolQueryBuilder, final int p , final int ps) {
Page<KbsTopic> pages = null ;
QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").from(new Date().getTime())) ;
QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").to(new Date().getTime())) ;
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
if(elasticsearchTemplate.indexExists(KbsTopic.class)){
pages = elasticsearchTemplate.queryForPage(searchQuery, KbsTopic.class);
}
return pages ;
}
@Override
public List<KbsTopic> getTopicByOrgi(String orgi , String type, String q) {
List<KbsTopic> list = null ;
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
if(!StringUtils.isBlank(type)){
boolQueryBuilder.must(termQuery("cate" , type)) ;
}
if(!StringUtils.isBlank(q)){
boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
}
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
SearchQuery searchQuery = searchQueryBuilder.build();
if(elasticsearchTemplate.indexExists(KbsTopic.class)){
list = elasticsearchTemplate.queryForList(searchQuery, KbsTopic.class);
}
return list ;
}
}
|
package com.flashspeed.logic.commands.gamecommands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static com.flashspeed.testutil.Assert.assertThrows;
import java.nio.file.Path;
import java.util.function.Predicate;
import javafx.beans.property.ReadOnlyProperty;
import javafx.collections.ObservableList;
import org.junit.jupiter.api.Test;
import com.flashspeed.model.GameManager;
import com.flashspeed.model.Model;
import com.flashspeed.model.ReadOnlyLibrary;
import com.flashspeed.model.ReadOnlyUserPrefs;
import com.flashspeed.model.Statistics;
import com.flashspeed.testutil.DeckUtils;
import com.flashspeed.commons.core.GuiSettings;
import com.flashspeed.commons.core.index.Index;
import com.flashspeed.logic.commands.CommandResult;
import com.flashspeed.logic.commands.exceptions.CommandException;
import com.flashspeed.model.deck.Deck;
import com.flashspeed.model.deck.Name;
import com.flashspeed.model.deck.card.BackFace;
import com.flashspeed.model.deck.card.Card;
import com.flashspeed.model.util.View;
public class AnswerNoCommandTest {
@Test
public void execute_AnswerNoSuccessful() throws Exception {
ModelStubAcceptingGameAnswerNo modelStub = new ModelStubAcceptingGameAnswerNo();
CommandResult commandResult = new AnswerNoCommand().execute(modelStub);
assertEquals(String.format(AnswerNoCommand.MESSAGE_SUCCESS), commandResult.getFeedbackToUser());
}
@Test
public void execute_notInPlayMode_throwsCommandException() {
ModelStubNotPlayMode modelStub = new ModelStubNotPlayMode();
AnswerNoCommand answerNoCommand = new AnswerNoCommand();
assertThrows(CommandException.class, AnswerNoCommand.MESSAGE_NOT_PLAY_MODE,
() -> answerNoCommand.execute(modelStub));
}
@Test
public void execute_gameNotFlipped_throwsCommandException() {
ModelStubCardNotFlipped modelStub = new ModelStubCardNotFlipped();
AnswerNoCommand answerNoCommand = new AnswerNoCommand();
assertThrows(CommandException.class, AnswerNoCommand.MESSAGE_NOT_FLIPPED,
() -> answerNoCommand.execute(modelStub));
}
@Test
public void equals() {
AnswerNoCommand answerNoCommand = new AnswerNoCommand();
// same object -> returns true
assertTrue(answerNoCommand.equals(answerNoCommand));
// same values -> returns true
AnswerNoCommand answerNoCommandCopy = new AnswerNoCommand();
assertTrue(answerNoCommand.equals(answerNoCommandCopy));
// different types -> returns false
assertFalse(answerNoCommand.equals(1));
// null -> returns false
assertFalse(answerNoCommand.equals(null));
}
/**
* A default model stub that have all of the methods failing.
*/
private class ModelStub implements Model {
public void setUserPrefs(ReadOnlyUserPrefs userPrefs) {
throw new AssertionError("This method should not be called.");
}
@Override
public ReadOnlyUserPrefs getUserPrefs() {
throw new AssertionError("This method should not be called.");
}
@Override
public GuiSettings getGuiSettings() {
throw new AssertionError("This method should not be called.");
}
@Override
public void setGuiSettings(GuiSettings guiSettings) {
throw new AssertionError("This method should not be called.");
}
@Override
public Path getLibraryFilePath() {
throw new AssertionError("This method should not be called.");
}
@Override
public void setLibraryFilePath(Path libraryFilePath) {
throw new AssertionError("This method should not be called.");
}
@Override
public void setLibrary(ReadOnlyLibrary newData) {
throw new AssertionError("This method should not be called.");
}
@Override
public ReadOnlyLibrary getLibrary() {
throw new AssertionError("This method should not be called.");
}
@Override
public void returnToLibrary() {
throw new AssertionError("This method should not be called");
}
//=========== Deck Functions =============================================================
@Override
public boolean hasDeck(Deck deck) {
throw new AssertionError("This method should not be called.");
}
@Override
public void deleteDeck(Deck target) {
throw new AssertionError("This method should not be called.");
}
@Override
public void setDeck(Deck target, Deck editedDeck) {
throw new AssertionError("This method should not be called.");
}
@Override
public void createDeck(Deck deck) {
throw new AssertionError("This method should not be called.");
}
@Override
public void selectDeck(Index targetIdx) {
throw new AssertionError("This method should not be called.");
}
@Override
public Deck getCurrentDeck() {
throw new AssertionError("This method should not be called");
}
@Override
public Deck getDeck(Index index) {
throw new AssertionError("This method should not be called");
}
@Override
public boolean renameDeck(Index targetIndex, Name name) {
throw new AssertionError("This method should not be called");
}
@Override
public ReadOnlyProperty<Deck> selectedDeckProperty() {
throw new AssertionError("This method should not be called");
}
@Override
public ReadOnlyProperty<View> currentViewProperty() {
throw new AssertionError("This method should not be called");
}
//=========== Card Functions =============================================================
@Override
public boolean hasCard(Card card) {
throw new AssertionError("This method should not be called");
}
@Override
public void deleteCard(Card target) {
throw new AssertionError("This method should not be called");
}
@Override
public void addCard(Card card) {
throw new AssertionError("This method should not be called");
}
@Override
public void replaceCard(Card target, Card card) {
throw new AssertionError("This method should not be called");
}
@Override
public ReadOnlyProperty<Card> playingCardProperty() {
throw new AssertionError("This method should not be called");
}
@Override
public ReadOnlyProperty<Boolean> flippedProperty() {
throw new AssertionError("This method should not be called");
}
@Override
public ReadOnlyProperty<Integer> cardAttemptedProperty() {
throw new AssertionError("This method should not be called");
}
@Override
public ReadOnlyProperty<Integer> cardRemainingProperty() {
throw new AssertionError("This method should not be called");
}
@Override
public View getView() {
throw new AssertionError("This method should not be called");
}
@Override
public void setCurrentView(View view) {
throw new AssertionError("This method should not be called");
}
//=========== Filtered Deck List Accessors =============================================================
@Override
public ObservableList<Deck> getFilteredDeckList() {
throw new AssertionError("This method should not be called");
}
@Override
public ObservableList<Card> getFilteredCardList() {
throw new AssertionError("This method should not be called");
}
@Override
public void updateFilteredDeckList(Predicate<Deck> predicate) {
throw new AssertionError("This method should not be called");
}
@Override
public void setSelectedDeck(Deck deck) {
throw new AssertionError("This method should not be called");
}
//=========== Play View Functions =============================================================
@Override
public void setFlipped(Boolean value) {
throw new AssertionError("This method should not be called");
}
@Override
public void setCardAttempted(int value) {
throw new AssertionError("This method should not be called");
}
@Override
public void setCardRemaining(int value) {
throw new AssertionError("This method should not be called");
}
@Override
public void setPlayingCard(Card card) {
throw new AssertionError("This method should not be called");
}
@Override
public Card getCard(Index index) {
throw new AssertionError("This method should not be called");
}
@Override
public Card play(Index index) {
throw new AssertionError("This method should not be called");
}
@Override
public BackFace flip() {
throw new AssertionError("This method should not be called");
}
@Override
public Card answerYes() {
throw new AssertionError("This method should not be called");
}
@Override
public Statistics stop() {
throw new AssertionError("This method should not be called");
}
@Override
public GameManager getGame() {
throw new AssertionError("This method should not be called");
}
@Override
public Card answerNo() {
throw new AssertionError("This method should not be called");
}
}
/**
* A Model stub that always answer no.
*/
private class ModelStubAcceptingGameAnswerNo extends ModelStub {
@Override
public View getView() {
return View.PLAY;
}
@Override
public GameManager getGame() {
Deck testDeck = DeckUtils.getTypicalJapDeck();
GameManager newGame = new GameManager(testDeck);
newGame.flip();
return newGame;
}
}
/**
* A Model stub that cannot play due to not in play mode.
*/
private class ModelStubNotPlayMode extends ModelStub {
@Override
public View getView() {
return View.DECK;
}
@Override
public GameManager getGame() {
Deck testDeck = DeckUtils.getTypicalJapDeck();
GameManager newGame = new GameManager(testDeck);
newGame.flip();
return newGame;
}
}
/**
* A Model stub that cannot answer no since card is not flipped.
*/
private class ModelStubCardNotFlipped extends ModelStub {
@Override
public View getView() {
return View.PLAY;
}
@Override
public GameManager getGame() {
Deck testDeck = DeckUtils.getTypicalJapDeck();
GameManager newGame = new GameManager(testDeck);
return newGame;
}
}
}
|
package com.elorri.android.xyzreader.data;
import android.net.Uri;
/**
* Created by Elorri on 10/03/2016.
*/
public class ItemsContract {
public static final String CONTENT_AUTHORITY = "com.elorri.android.xyzreader";
public static final Uri BASE_URI = Uri.parse("content://com.elorri.android.xyzreader");
interface ItemsColumns {
/** Type: INTEGER PRIMARY KEY AUTOINCREMENT */
String _ID = "_id";
/** Type: TEXT */
String SERVER_ID = "server_id";
/** Type: TEXT NOT NULL */
String TITLE = "title";
/** Type: TEXT NOT NULL */
String AUTHOR = "author";
/** Type: TEXT NOT NULL */
String BODY = "body";
/** Type: TEXT NOT NULL */
String THUMB_URL = "thumb_url";
/** Type: TEXT NOT NULL */
String PHOTO_URL = "photo_url";
/** Type: REAL NOT NULL DEFAULT 1.5 */
String ASPECT_RATIO = "aspect_ratio";
/** Type: INTEGER NOT NULL DEFAULT 0 */
String PUBLISHED_DATE = "published_date";
}
public static class Items implements ItemsColumns {
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.elorri.android.xyzreader.items";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.com.elorri.android.xyzreader.items";
public static final String DEFAULT_SORT = PUBLISHED_DATE + " DESC";
/** Matches: /items/ */
public static Uri buildDirUri() {
return BASE_URI.buildUpon().appendPath("items").build();
}
/** Matches: /items/[_id]/ */
public static Uri buildItemUri(long _id) {
return BASE_URI.buildUpon().appendPath("items").appendPath(Long.toString(_id)).build();
}
/** Read item ID item detail URI. */
public static long getItemId(Uri itemUri) {
return Long.parseLong(itemUri.getPathSegments().get(1));
}
}
private ItemsContract() {
}
}
|
package br.com.jotajr.empresas.ie.estados;
import br.com.jotajr.empresas.ie.InscricaoEstadualBase;
public class InscricaoEstadualBA extends InscricaoEstadualBase {
private static final Integer[] MULTIPLICADOR_8_1 = new Integer[]{Integer.valueOf(7), Integer.valueOf(6), Integer.valueOf(5), Integer.valueOf(4), Integer.valueOf(3), Integer.valueOf(2)};
private static final Integer[] MULTIPLICADOR_8_2 = new Integer[]{Integer.valueOf(8), Integer.valueOf(7), Integer.valueOf(6), Integer.valueOf(5), Integer.valueOf(4), Integer.valueOf(3)};
private static final Integer[] MULTIPLICADOR_9_1 = new Integer[]{Integer.valueOf(8), Integer.valueOf(7), Integer.valueOf(6), Integer.valueOf(5), Integer.valueOf(4), Integer.valueOf(3), Integer.valueOf(2)};
private static final Integer[] MULTIPLICADOR_9_2 = new Integer[]{Integer.valueOf(9), Integer.valueOf(8), Integer.valueOf(7), Integer.valueOf(6), Integer.valueOf(5), Integer.valueOf(4), Integer.valueOf(3)};
public InscricaoEstadualBA() {
}
public boolean validar(String numero) {
boolean valido = false;
String ie = this.limpar(numero, "[^0-9]");
int inicial;
Integer[] numeros;
Integer[] calculo1;
int soma;
int digito;
Integer[] calculo2;
if(ie.length() == 8) {
inicial = this.toInt(ie.substring(0, 1));
if(this.in(inicial, new Integer[]{Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(8)})) {
numeros = this.split(ie);
calculo1 = this.multiplicar(numeros, MULTIPLICADOR_8_1);
soma = this.somar(calculo1);
digito = 10 - this.modulo10(soma);
if(digito == 10) {
digito = 0;
}
if(numeros[7].intValue() == digito) {
calculo2 = this.multiplicar(numeros, MULTIPLICADOR_8_2);
soma = this.somar(calculo2) + 2 * digito;
digito = 10 - this.modulo10(soma);
if(digito == 10) {
digito = 0;
}
valido = numeros[6].intValue() == digito;
}
} else if(this.in(inicial, new Integer[]{Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(9)})) {
numeros = this.split(ie);
calculo1 = this.multiplicar(numeros, MULTIPLICADOR_8_1);
soma = this.somar(calculo1);
digito = 11 - this.modulo11(soma);
if(digito == 10 || digito == 11) {
digito = 0;
}
if(numeros[7].intValue() == digito) {
calculo2 = this.multiplicar(numeros, MULTIPLICADOR_8_2);
soma = this.somar(calculo2) + 2 * digito;
digito = 11 - this.modulo11(soma);
if(digito == 10 || digito == 11) {
digito = 0;
}
valido = numeros[6].intValue() == digito;
}
}
} else if(ie.length() == 9) {
inicial = this.toInt(ie.substring(0, 1));
if(this.in(inicial, new Integer[]{Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(8)})) {
numeros = this.split(ie);
calculo1 = this.multiplicar(numeros, MULTIPLICADOR_9_1);
soma = this.somar(calculo1);
digito = 10 - this.modulo10(soma);
if(digito == 10) {
digito = 0;
}
if(numeros[8].intValue() == digito) {
calculo2 = this.multiplicar(numeros, MULTIPLICADOR_9_2);
soma = this.somar(calculo2) + 2 * digito;
digito = 10 - this.modulo10(soma);
if(digito == 10) {
digito = 0;
}
valido = numeros[7].intValue() == digito;
}
} else if(this.in(inicial, new Integer[]{Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(9)})) {
numeros = this.split(ie);
calculo1 = this.multiplicar(numeros, MULTIPLICADOR_9_1);
soma = this.somar(calculo1);
digito = 11 - this.modulo11(soma);
if(digito == 10 || digito == 11) {
digito = 0;
}
if(numeros[8].intValue() == digito) {
calculo2 = this.multiplicar(numeros, MULTIPLICADOR_9_2);
soma = this.somar(calculo2) + 2 * digito;
digito = 11 - this.modulo11(soma);
if(digito == 10 || digito == 11) {
digito = 0;
}
valido = numeros[7].intValue() == digito;
}
}
}
return valido;
}
}
|
/*
* 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.skyscreamer.jsonassert.comparator;
import org.skyscreamer.json.JSONArray;
import org.skyscreamer.json.JSONException;
import org.skyscreamer.json.JSONObject;
import org.skyscreamer.jsonassert.JSONCompareResult;
/**
* Interface for comparison handler.
*
* @author <a href="mailto:aiveeen@gmail.com">Ivan Zaytsev</a>
* 2013-01-04
*/
public interface JSONComparator {
/**
* Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
*
* @param expected the expected JSON object
* @param actual the actual JSON object
* @return the result of the comparison
* @throws JSONException JSON parsing error
*/
JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
/**
* Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
*
* @param expected the expected JSON array
* @param actual the actual JSON array
* @return the result of the comparison
* @throws JSONException JSON parsing error
*/
JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
/**
* Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
* updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
*
* @param prefix the path in the json where the comparison happens
* @param expected the expected JSON object
* @param actual the actual JSON object
* @param result stores the actual state of the comparison result
* @throws JSONException JSON parsing error
*/
void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
/**
* Compares two {@link Object}s on the provided path represented by {@code prefix} and
* updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
*
* @param prefix the path in the json where the comparison happens
* @param expectedValue the expected value
* @param actualValue the actual value
* @param result stores the actual state of the comparison result
* @throws JSONException JSON parsing error
*/
void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
/**
* Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
* updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
*
* @param prefix the path in the json where the comparison happens
* @param expected the expected JSON array
* @param actual the actual JSON array
* @param result stores the actual state of the comparison result
* @throws JSONException JSON parsing error
*/
void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
}
|
package terriblethings.main;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelDragon;
import terriblethings.mobs.EntityBreaker;
import terriblethings.mobs.EntityFirebird;
import terriblethings.mobs.EntityMinotaur;
import terriblethings.mobs.ModelFirebird;
import terriblethings.mobs.ModelMinotaur;
import terriblethings.mobs.RenderBreaker;
import terriblethings.mobs.RenderFirebird;
import terriblethings.mobs.RenderMinotaur;
import cpw.mods.fml.client.registry.RenderingRegistry;
public class ClientProxy extends ServerProxy{
public void RegisterRenderThings(){
RenderingRegistry.registerEntityRenderingHandler(EntityMinotaur.class, new RenderMinotaur(new ModelMinotaur(), 0.3F));
RenderingRegistry.registerEntityRenderingHandler(EntityBreaker.class, new RenderBreaker(new ModelBiped(), 0.3F));
RenderingRegistry.registerEntityRenderingHandler(EntityFirebird.class, new RenderFirebird(new ModelFirebird(), 0.3F));
}
}
|
/*
* Source code generated by Celerio, a Jaxio product.
* Documentation: http://www.jaxio.com/documentation/celerio/
* Follow us on twitter: @jaxiosoft
* Need commercial support ? Contact us: info@jaxio.com
* Template pack-jsf2-spring-conversation:src/main/java/domain/SearchForm.e.vm.java
* Template is part of Open Source Project: https://github.com/jaxio/pack-jsf2-spring-conversation
*/
package ma.sgma.edi2.web.domain;
import static com.jaxio.jpa.querybyexample.PropertySelector.newPropertySelector;
import javax.inject.Named;
import com.jaxio.jpa.querybyexample.PropertySelector;
import com.jaxio.jpa.querybyexample.SearchParameters;
import ma.sgma.edi2.domain.SgediTitrerffi;
import ma.sgma.edi2.domain.SgediTitrerffi_;
import ma.sgma.edi2.domain.Sgedirffi;
import ma.sgma.edi2.web.domain.support.GenericSearchForm;
import ma.sgma.edi2.web.faces.ConversationContextScoped;
/**
* View Helper to search {@link SgediTitrerffi}.
* It exposes a {@link SgediTitrerffi} instance so it can be used in search by-example-query.
*/
@Named
@ConversationContextScoped
public class SgediTitrerffiSearchForm extends GenericSearchForm<SgediTitrerffi, Integer, SgediTitrerffiSearchForm> {
private static final long serialVersionUID = 1L;
protected SgediTitrerffi sgediTitrerffi = new SgediTitrerffi();
protected PropertySelector<SgediTitrerffi, String> titreSelector = newPropertySelector(SgediTitrerffi_.titre);
protected PropertySelector<SgediTitrerffi, Sgedirffi> idrffiSelector = newPropertySelector(SgediTitrerffi_.idrffi);
public SgediTitrerffi getSgediTitrerffi() {
return sgediTitrerffi;
}
@Override
protected SgediTitrerffi getEntity() {
return getSgediTitrerffi();
}
@Override
public SgediTitrerffiSearchForm newInstance() {
return new SgediTitrerffiSearchForm();
}
@Override
public SearchParameters toSearchParameters() {
SearchParameters sp = searchParameters();
sp.fetch(SgediTitrerffi_.idrffi);
sp.property(titreSelector);
sp.property(idrffiSelector);
return sp;
}
@Override
public void resetWithOther(SgediTitrerffiSearchForm other) {
this.sgediTitrerffi = other.getSgediTitrerffi();
this.titreSelector = other.getTitreSelector();
this.idrffiSelector = other.getIdrffiSelector();
}
// Property selectors
public PropertySelector<SgediTitrerffi, String> getTitreSelector() {
return titreSelector;
}
// Relation selectors
public PropertySelector<SgediTitrerffi, Sgedirffi> getIdrffiSelector() {
return idrffiSelector;
}
}
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.tools.transfer.ui.wizard;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.jkiss.dbeaver.tools.transfer.DataTransferPipe;
import org.jkiss.dbeaver.tools.transfer.DataTransferSettings;
import org.jkiss.dbeaver.tools.transfer.IDataTransferNode;
import org.jkiss.dbeaver.tools.transfer.internal.DTMessages;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.ActiveWizardPage;
/**
* This page hosts other settings pages
*/
class DataTransferPageSettings extends ActiveWizardPage<DataTransferWizard> {
private IWizardPage producerSettingsPage;
private IWizardPage consumerSettingsPage;
DataTransferPageSettings() {
super(DTMessages.data_transfer_wizard_settings_name);
setTitle(DTMessages.data_transfer_wizard_settings_title);
setDescription(DTMessages.data_transfer_wizard_settings_description);
}
@Override
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite = UIUtils.createComposite(parent, 1);
setControl(composite);
}
private void createSettingsPages(Composite composite) {
DataTransferSettings dtSettings = getWizard().getSettings();
{
DataTransferPipe dataPipe = dtSettings.getDataPipes().get(0);
StringBuilder title = new StringBuilder();
String producerName = dtSettings.getProducer() == null ? "null" : dtSettings.getProducer().getName();
String consumerName = dtSettings.getConsumer() == null ? "null" : dtSettings.getConsumer().getName();
title.append(DTMessages.data_transfer_wizard_settings_title).append(" (").append(producerName).append(" to ").append(consumerName);
if (dtSettings.getProcessor() != null) {
title.append(", ").append(dtSettings.getProcessor().getName());
}
title.append(")");
setTitle(title.toString());
producerSettingsPage = getSettingsPage(dataPipe.getProducer());
consumerSettingsPage = getSettingsPage(dataPipe.getConsumer());
}
Composite settingsComposite = composite;
if (producerSettingsPage != null && consumerSettingsPage != null) {
SashForm sash = new SashForm(composite, SWT.HORIZONTAL);
sash.setLayoutData(new GridData(GridData.FILL_BOTH));
settingsComposite = sash;
}
if (producerSettingsPage != null) {
producerSettingsPage.setWizard(getWizard());
Composite producerGroup = UIUtils.createPlaceholder(settingsComposite, 1);
UIUtils.createInfoLabel(producerGroup, producerSettingsPage.getTitle());
Composite settingPanel = new Composite(producerGroup, SWT.NONE);
settingPanel.setLayoutData(new GridData(GridData.FILL_BOTH));
settingPanel.setLayout(new FillLayout());
producerSettingsPage.createControl(settingPanel);
if (producerSettingsPage instanceof ActiveWizardPage) {
((ActiveWizardPage) producerSettingsPage).activatePage();
}
}
if (consumerSettingsPage != null) {
consumerSettingsPage.setWizard(getWizard());
Composite consumerGroup = UIUtils.createPlaceholder(settingsComposite, 1);
UIUtils.createInfoLabel(consumerGroup, consumerSettingsPage.getTitle());
Composite settingPanel = new Composite(consumerGroup, SWT.NONE);
settingPanel.setLayoutData(new GridData(GridData.FILL_BOTH));
settingPanel.setLayout(new FillLayout());
consumerSettingsPage.createControl(settingPanel);
if (consumerSettingsPage instanceof ActiveWizardPage) {
((ActiveWizardPage) consumerSettingsPage).activatePage();
}
}
}
private IWizardPage getSettingsPage(IDataTransferNode node) {
DataTransferWizard.NodePageSettings producerInfo = getWizard().getNodeInfo(node);
return producerInfo == null ? null : producerInfo.settingsPage;
}
@Override
public void activatePage()
{
Composite composite = (Composite) getControl();
UIUtils.disposeChildControls(composite);
createSettingsPages(composite);
composite.layout(true, true);
updatePageCompletion();
}
@Override
public void deactivatePage() {
if (producerSettingsPage instanceof ActiveWizardPage) {
((ActiveWizardPage) producerSettingsPage).deactivatePage();
}
if (consumerSettingsPage instanceof ActiveWizardPage) {
((ActiveWizardPage) consumerSettingsPage).deactivatePage();
}
}
@Override
protected boolean determinePageCompletion()
{
return (producerSettingsPage == null || producerSettingsPage.isPageComplete()) &&
(consumerSettingsPage == null || consumerSettingsPage.isPageComplete());
}
}
|
package com.ryit.commons.web.exception.user;
/**
* 用户锁定异常类
*
* @author ryit
*/
public class UserBlockedException extends UserException
{
private static final long serialVersionUID = 1L;
public UserBlockedException(String reason)
{
super("member.blocked", new Object[] { reason });
}
}
|
package google.instrumentationtest;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("google.instrumentationtest", appContext.getPackageName());
}
}
|
/*
* (C) Copyright IBM Corp. 2017, 2020
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.fhir.config;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ibm.fhir.core.HTTPHandlingPreference;
import com.ibm.fhir.core.HTTPReturnPreference;
import com.ibm.fhir.exception.FHIRException;
/**
* This class is used to hold FHIR REST API context information.
* There are non-static methods for maintaining individual instances, as
* well as static methods for setting instances on and getting instances from thread local.
* The overall strategy is for the REST API servlet filter to retrieve the request context
* information, create an instance of this class and set it on the current thread for use
* by the FHIR Server as it processes the request.
*/
public class FHIRRequestContext {
private static final Logger log = Logger.getLogger(FHIRRequestContext.class.getName());
private String tenantId;
private String tenantKey;
private String dataStoreId;
private String requestUniqueId;
private String originalRequestUri;
private Map<String, List<String>> httpHeaders;
// Default to the "strict" handling which means the server will reject unrecognized search parameters and elements
private HTTPHandlingPreference handlingPreference = HTTPHandlingPreference.STRICT;
// Default to the "minimal" representation which means create/update responses won't return the resource body
private HTTPReturnPreference returnPreference = HTTPReturnPreference.MINIMAL;
private Pattern validChars = Pattern.compile("[a-zA-Z0-9_\\-]+");
private String errorMsg = "Only [a-z], [A-Z], [0-9], '_', and '-' characters are allowed.";
private static ThreadLocal<FHIRRequestContext> contexts = new ThreadLocal<FHIRRequestContext>() {
@Override
public FHIRRequestContext initialValue() {
try {
return new FHIRRequestContext(FHIRConfiguration.DEFAULT_TENANT_ID, FHIRConfiguration.DEFAULT_DATASTORE_ID);
} catch (FHIRException e) {
throw new IllegalStateException("Unexpected error while initializing FHIRRequestContext");
}
}
};
public FHIRRequestContext() {
this.requestUniqueId = UUID.randomUUID().toString();
}
public FHIRRequestContext(String tenantId) throws FHIRException {
this();
setTenantId(tenantId);
}
public FHIRRequestContext(String tenantId, String dataStoreId) throws FHIRException {
this(tenantId);
setDataStoreId(dataStoreId);
}
public String getTenantId() {
return tenantId;
}
public String getTenantKey() {
return this.tenantKey;
}
public void setTenantId(String tenantId) throws FHIRException {
Matcher matcher = validChars.matcher(tenantId);
if (matcher.matches()) {
this.tenantId = tenantId;
} else {
throw new FHIRException("Invalid tenantId. " + errorMsg);
}
}
/**
* Setter for the tenant key
* @param b64
* @throws FHIRException if the given value is not a valid Base64 string
*/
public void setTenantKey(String b64) throws FHIRException {
try {
Base64.getDecoder().decode(b64);
this.tenantKey = b64;
}
catch (IllegalArgumentException x) {
// Tenant key is a secret, so don't include it in any error message
throw new FHIRException("Invalid tenantKey.");
}
}
public String getDataStoreId() {
return dataStoreId;
}
public void setDataStoreId(String dataStoreId) throws FHIRException {
Matcher matcher = validChars.matcher(dataStoreId);
if (matcher.matches()) {
this.dataStoreId = dataStoreId;
} else {
throw new FHIRException("Invalid dataStoreId. " + errorMsg);
}
}
/**
* Sets the specified FHIRRequestContext instance on the current thread,
* so that it can be used by FHIR Server downstream processing.
* This method is called when the FHIR Server starts processing a request.
*/
public static void set(FHIRRequestContext context) {
contexts.set(context);
if (log.isLoggable(Level.FINEST)) {
log.finest("FHIRRequestContext.set: " + context.toString());
}
}
/**
* Returns the FHIRRequestContext on the current thread.
*/
public static FHIRRequestContext get() {
FHIRRequestContext result = contexts.get();
if (log.isLoggable(Level.FINEST)) {
log.finest("FHIRRequestContext.get: " + result.toString());
}
return result;
}
/**
* Removes the FHIRRequestContext that's set on the current thread.
* This method is called when the FHIR Server is finished processing a request.
*/
public static void remove() {
contexts.remove();
log.finest("FHIRRequestContext.remove invoked.");
}
@Override
public String toString() {
return "FHIRRequestContext [tenantId=" + tenantId + ", dataStoreId=" + dataStoreId
+ ", this="+ objectHandle(this) + "]";
}
public String getRequestUniqueId() {
return this.requestUniqueId;
}
private static String objectHandle(Object obj) {
return '@' + Integer.toHexString(System.identityHashCode(obj));
}
/**
* @return the handlingPreference
*/
public HTTPHandlingPreference getHandlingPreference() {
return handlingPreference;
}
/**
* @param handlingPreference the handlingPreference to set
*/
public void setHandlingPreference(HTTPHandlingPreference handlingPreference) {
this.handlingPreference = handlingPreference;
}
/**
* @return the returnPreference
*/
public HTTPReturnPreference getReturnPreference() {
return returnPreference;
}
/**
* @param returnPreference the returnPreference to set
*/
public void setReturnPreference(HTTPReturnPreference returnPreference) {
this.returnPreference = returnPreference;
}
/**
* @return the originalRequestUri
*/
public String getOriginalRequestUri() {
return originalRequestUri;
}
/**
* @param originalRequestUri the originalRequestUri to set
*/
public void setOriginalRequestUri(String originalRequestUri) {
this.originalRequestUri = originalRequestUri;
}
/**
* @return the httpHeaders
*/
public Map<String, List<String>> getHttpHeaders() {
return httpHeaders;
}
/**
* @param httpHeaders the httpHeaders to set
*/
public void setHttpHeaders(Map<String, List<String>> httpHeaders) {
this.httpHeaders = httpHeaders;
}
}
|
/*
* FactSet Overview Report Builder API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.factset.sdk.OverviewReportBuilder.models;
import java.util.Objects;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.factset.sdk.OverviewReportBuilder.JSON;
/**
* ProfileDataBusinessCrunchbaseCategories
*/
@JsonPropertyOrder({
ProfileDataBusinessCrunchbaseCategories.JSON_PROPERTY_VALUE,
ProfileDataBusinessCrunchbaseCategories.JSON_PROPERTY_NOTE
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class ProfileDataBusinessCrunchbaseCategories implements Serializable {
private static final long serialVersionUID = 1L;
public static final String JSON_PROPERTY_VALUE = "value";
private java.util.List<String> value = new java.util.ArrayList<>();
public static final String JSON_PROPERTY_NOTE = "note";
private String note;
public ProfileDataBusinessCrunchbaseCategories() {
}
@JsonCreator
public ProfileDataBusinessCrunchbaseCategories(
@JsonProperty(value=JSON_PROPERTY_VALUE, required=true) java.util.List<String> value,
@JsonProperty(value=JSON_PROPERTY_NOTE, required=true) String note
) {
this();
this.value = value;
this.note = note;
}
public ProfileDataBusinessCrunchbaseCategories value(java.util.List<String> value) {
this.value = value;
return this;
}
public ProfileDataBusinessCrunchbaseCategories addValueItem(String valueItem) {
this.value.add(valueItem);
return this;
}
/**
* Get value
* @return value
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
@JsonProperty(JSON_PROPERTY_VALUE)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public java.util.List<String> getValue() {
return value;
}
@JsonProperty(JSON_PROPERTY_VALUE)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public void setValue(java.util.List<String> value) {
this.value = value;
}
public ProfileDataBusinessCrunchbaseCategories note(String note) {
this.note = note;
return this;
}
/**
* Get note
* @return note
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
@JsonProperty(JSON_PROPERTY_NOTE)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public String getNote() {
return note;
}
@JsonProperty(JSON_PROPERTY_NOTE)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public void setNote(String note) {
this.note = note;
}
/**
* Return true if this ProfileData_business_crunchbaseCategories object is equal to o.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProfileDataBusinessCrunchbaseCategories profileDataBusinessCrunchbaseCategories = (ProfileDataBusinessCrunchbaseCategories) o;
return Objects.equals(this.value, profileDataBusinessCrunchbaseCategories.value) &&
Objects.equals(this.note, profileDataBusinessCrunchbaseCategories.note);
}
@Override
public int hashCode() {
return Objects.hash(value, note);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ProfileDataBusinessCrunchbaseCategories {\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append(" note: ").append(toIndentedString(note)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package org.batfish.representation.cisco_xr;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* A visitor of {@link XrCommunitySetElem} that takes 1 generic argument and returns a generic
* value.
*/
@ParametersAreNonnullByDefault
public interface XrCommunitySetElemVisitor<T, U> {
T visitCommunitySetHighLowRangeExprs(XrCommunitySetHighLowRangeExprs highLowRangeExprs, U arg);
T visitCommunitySetDfaRegex(XrCommunitySetDfaRegex xrCommunitySetDfaRegex, U arg);
T visitCommunitySetIosRegex(XrCommunitySetIosRegex communitySetIosRegex, U arg);
T visitWildcardCommunitySetElem(XrWildcardCommunitySetElem xrWildcardCommunitySetElem);
}
|
/**
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.sitebricks.stat.testservices;
import com.google.sitebricks.stat.Stat;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* This is a simple dummy class that is used in tests to ensure that a private
* field on a class outside of a package can have its {@link com.google.sitebricks.stat.Stat} fields read
* and published.
*
* @author dhanji@gmail.com (Dhanji R. Prasanna)
*/
public class DummyService {
public static final String NUMBER_OF_CALLS = "number-of-calls";
@Stat(NUMBER_OF_CALLS)
private final AtomicInteger calls = new AtomicInteger();
public static final String CALL_LATENCY_NS = "call-latency-ns";
private final AtomicLong callLatencyNs = new AtomicLong(0L);
/**
* Increments {@link #calls} by one. Also increments {@link #callLatencyNs}
* by the amount of time required to do so..
*/
public void call() {
Long startTime = System.nanoTime();
try {
calls.incrementAndGet();
} finally {
callLatencyNs.addAndGet(System.nanoTime() - startTime);
}
}
public AtomicInteger getCalls() {
return calls;
}
@Stat(CALL_LATENCY_NS)
public Long getCallLatencyMs() {
return callLatencyNs.get();
}
}
|
package com.rbkmoney.newway.service;
import com.rbkmoney.newway.dao.AbstractAppDaoTests;
import com.rbkmoney.newway.dao.invoicing.iface.InvoiceDao;
import com.rbkmoney.newway.domain.tables.pojos.Invoice;
import com.rbkmoney.newway.domain.tables.pojos.InvoiceCart;
import com.rbkmoney.newway.model.InvoiceWrapper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static io.github.benas.randombeans.api.EnhancedRandom.random;
import static io.github.benas.randombeans.api.EnhancedRandom.randomListOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class InvoiceBatchServiceTest extends AbstractAppDaoTests {
@Autowired
private InvoiceBatchService invoiceBatchService;
@Autowired
private InvoiceDao invoiceDao;
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void processTest() {
List<InvoiceWrapper> invoiceWrappers = IntStream.range(1, 5)
.mapToObj(x -> new InvoiceWrapper(random(Invoice.class, "id"),
randomListOf(3, InvoiceCart.class, "id", "invId")))
.collect(Collectors.toList());
String invoiceIdFirst = "invoiceIdFirst";
String invoiceIdSecond = "invoiceIdSecond";
invoiceWrappers.get(0).getInvoice().setInvoiceId(invoiceIdFirst);
invoiceWrappers.get(1).getInvoice().setInvoiceId(invoiceIdFirst);
invoiceWrappers.get(2).getInvoice().setInvoiceId(invoiceIdSecond);
invoiceWrappers.get(3).getInvoice().setInvoiceId(invoiceIdSecond);
invoiceWrappers.forEach(iw -> {
iw.getInvoice().setCurrent(false);
});
invoiceBatchService.process(invoiceWrappers);
Invoice invoiceFirstGet = invoiceDao.get(invoiceIdFirst);
assertNotEquals(invoiceWrappers.get(0).getInvoice().getPartyId(), invoiceFirstGet.getPartyId());
assertEquals(invoiceWrappers.get(1).getInvoice().getPartyId(), invoiceFirstGet.getPartyId());
Invoice invoiceSecondGet = invoiceDao.get(invoiceIdSecond);
assertNotEquals(invoiceWrappers.get(2).getInvoice().getShopId(), invoiceSecondGet.getShopId());
assertEquals(invoiceWrappers.get(3).getInvoice().getShopId(), invoiceSecondGet.getShopId());
//Duplication check
invoiceBatchService.process(invoiceWrappers);
assertEquals(2, jdbcTemplate
.queryForObject("SELECT count(*) FROM nw.invoice WHERE invoice_id = ? ", new Object[]{invoiceIdFirst},
Integer.class).intValue());
assertEquals(2, jdbcTemplate
.queryForObject("SELECT count(*) FROM nw.invoice WHERE invoice_id = ? ", new Object[]{invoiceIdSecond},
Integer.class).intValue());
assertEquals(3, jdbcTemplate.queryForObject("SELECT count(*) FROM nw.invoice_cart where inv_id = ? ",
new Object[]{invoiceFirstGet.getId()}, Integer.class).intValue());
assertEquals(24,
jdbcTemplate.queryForObject("SELECT count(*) FROM nw.invoice_cart ", Integer.class).intValue());
}
}
|
package org.fluentjava.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import com.google.common.base.Strings;
public class UtilDates {
public static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
public static final DateFormat DEFAULT_PRETTY_DATE_FORMAT = new SimpleDateFormat("EEE MM/dd/yyyy");
public static final DateFormat DEFAULT_DATETIME_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
public static final DateFormat DEFAULT_TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
public static final DateFormat DEFAULT_HOUR_FORMAT = new SimpleDateFormat("HH:mm");
private static final GregorianCalendar CALENDAR_1 = new GregorianCalendar();
private static final GregorianCalendar CALENDAR_2 = new GregorianCalendar();
public static Date parseDateWithoutTime(final String date) {
return parseDateWithoutTime(date, false);
}
public static String formatDateWithoutTime(final Date date) {
return DEFAULT_DATE_FORMAT.format(date);
}
public static String formatDateTime(final Date date) {
return DEFAULT_DATETIME_FORMAT.format(date);
}
public static String formatPrettyDate(final Date date) {
return DEFAULT_PRETTY_DATE_FORMAT.format(date);
}
public static String formatTime(final Date date) {
return DEFAULT_TIME_FORMAT.format(date);
}
public static String formatHour(final Date date) {
return DEFAULT_HOUR_FORMAT.format(date);
}
public static Date parseDateWithoutTime(final String date, final boolean permissive) {
final Date res = null;
if ( ! permissive || ! Strings.isNullOrEmpty(date)) {
try {
return DEFAULT_DATE_FORMAT.parse(date);
}
catch (final ParseException e) {
if ( ! permissive) {
throw new RuntimeException("Error when parsing date : " + date, e);
}
}
}
return res;
}
public static boolean areDatesTheSameDay(final Date date1, final Date date2) {
boolean result = false;
synchronized (CALENDAR_1) {
final Calendar cal1 = CALENDAR_1;
final Calendar cal2 = CALENDAR_2;
cal1.setTime(date1);
cal2.setTime(date2);
if ((cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH))
&& (cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH))
&& (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR))) {
result = true;
}
}
return result;
}
public static boolean areDatesTheSameHour(final Date date1, final Date date2) {
boolean result = false;
if ((date1 != null) && (date2 != null)) {
synchronized (CALENDAR_1) {
final Calendar cal1 = CALENDAR_1;
final Calendar cal2 = CALENDAR_2;
cal1.setTime(date1);
cal2.setTime(date2);
if ( (cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY))
&& (cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE)))
{
result = true;
}
}
}
return result;
}
public static Date getDateWithoutHours(final Date date) {
if (date == null) {
return null;
}
synchronized (CALENDAR_1) {
final Calendar dateWithoutHours = CALENDAR_1;
dateWithoutHours.setTime(date);
dateWithoutHours.set(Calendar.HOUR_OF_DAY, 0);
dateWithoutHours.set(Calendar.MINUTE, 0);
dateWithoutHours.set(Calendar.SECOND, 0);
dateWithoutHours.set(Calendar.MILLISECOND, 0);
return dateWithoutHours.getTime();
}
}
}
|
package t08_ExamPreparations.e16_26_March_2016;
import java.util.Scanner;
public class p06_MagicNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
for (int d1 = 1; d1 <= 9; d1++) {
for (int d2 = 1; d2 <= 9; d2++) {
for (int d3 = 1; d3 <= 9; d3++) {
for (int d4 = 1; d4 <= 9; d4++) {
for (int d5 = 1; d5 <= 9; d5++) {
for (int d6 = 1; d6 <= 9; d6++) {
if (d1 * d2 * d3 * d4 * d5 * d6 == n) {
System.out.printf("%d%d%d%d%d%d ", d1, d2, d3, d4, d5, d6);
}
}
}
}
}
}
}
}
}
|
package com.itxiaoer.commons.jpa.service;
import com.itxiaoer.commons.core.NotFoundException;
import com.itxiaoer.commons.core.page.PageResponse;
import com.itxiaoer.commons.core.page.Paging;
import com.itxiaoer.commons.core.page.Sort;
import com.itxiaoer.commons.core.util.Lists;
import com.itxiaoer.commons.jpa.Restrictions;
import com.itxiaoer.commons.orm.page.PagingUtils;
import com.itxiaoer.commons.orm.service.BasicService;
import com.itxiaoer.commons.orm.service.BasicSpecificationExecutor;
import com.itxiaoer.commons.orm.validate.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* @author : liuyk
*/
@SuppressWarnings({"all"})
@Transactional(readOnly = true, rollbackFor = Exception.class)
public abstract class BasicJpaService<DTO, E, ID extends Serializable, JPA extends JpaRepository<E, ID> & JpaSpecificationExecutor> implements BasicService<DTO, E, ID>, BasicSpecificationExecutor<E>, Validate<DTO, ID> {
@Autowired
private JPA repository;
@Override
@Transactional(rollbackFor = Exception.class)
public E create(DTO dto) {
return this.create(dto, consumer());
}
@Override
@Transactional(rollbackFor = Exception.class)
public E create(DTO dto, BiConsumer<E, DTO> consumer) {
this.valid(dto);
E process = process(dto, consumer);
this.repository.saveAndFlush(process);
return process;
}
@Override
@Transactional(rollbackFor = Exception.class)
public E update(ID id, DTO dto) {
return this.update(id, dto, (dest, source) -> {
});
}
@Override
@Transactional(rollbackFor = Exception.class)
public E update(ID id, DTO dto, BiConsumer<E, DTO> consumer) {
this.idValid(id);
this.valid(id, dto);
Optional<E> optional = this.repository.findById(id);
E e = optional.orElseThrow(NotFoundException::new);
this.process(e, dto, consumer);
this.repository.saveAndFlush(e);
return e;
}
@Override
@Transactional(rollbackFor = Exception.class)
public E update(ID id, Consumer<E> consumer) {
this.idValid(id);
Optional<E> optional = this.repository.findById(id);
E e = optional.orElseThrow(NotFoundException::new);
consumer.accept(e);
return this.repository.saveAndFlush(e);
}
@Transactional(rollbackFor = Exception.class)
public E update(E e) {
return this.repository.saveAndFlush(e);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(ID id) {
this.idValid(id);
this.repository.deleteById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(List<ID> ids) {
if (Lists.iterable(ids)) {
for (ID id : ids) {
this.repository.deleteById(id);
}
}
}
@Override
public Optional<E> getById(ID id) {
this.idValid(id);
return this.repository.findById(id);
}
@Override
public List<E> getById(List<ID> ids) {
if (Lists.iterable(ids)) {
return this.repository.findAllById(ids);
}
return Lists.newArrayList();
}
@Override
public List<E> list() {
return this.repository.findAll();
}
@Override
public List<E> list(Sort... sorts) {
return this.repository.findAll(PagingUtils.of(sorts));
}
@Override
public PageResponse<E> list(Paging paging) {
Page<E> page = this.repository.findAll(PagingUtils.of(paging));
return PagingUtils.of(page);
}
@Override
public <T> List<E> listByWhere(T query) {
return this.repository.findAll(Restrictions.of().where(query).get());
}
@Override
public <T> List<E> listByWhere(T query, Sort... sorts) {
return this.repository.findAll(Restrictions.of().where(query).get(), PagingUtils.of(sorts));
}
@Override
public <T extends Paging> PageResponse<E> listByWhere(T query) {
Page<E> page = this.repository.findAll(Restrictions.of().where(query).get(), PagingUtils.of(query));
return PagingUtils.of(page);
}
@Override
public <T> PageResponse<E> listByWhere(T query, Paging paging) {
Page<E> page = this.repository.findAll(Restrictions.of().where(query).get(), PagingUtils.of(paging));
return PagingUtils.of(page);
}
@Override
public Class<E> getGenericClass(int index) {
Class cls = this.getClass();
while (!Objects.equals(cls.getSuperclass(), BasicJpaService.class)) {
cls = cls.getSuperclass();
}
ParameterizedType genericInterfaces = (ParameterizedType) cls.getGenericSuperclass();
return (Class<E>) genericInterfaces.getActualTypeArguments()[index];
}
/**
* 获取数据层对象
*
* @return 数据持久层对象
*/
public JPA getRepository() {
return this.repository;
}
}
|
/*
* Copyright 1999-2022 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appactive.rule.traffic.condition;
import java.util.List;
public interface RuleCondition {
/**
* 条件类型代码
*
* @return
*/
String conditionType();
/**
* 当前条件使用的tokenName
*
* @return
*/
String tokenName();
/**
* 条件优先级
*
* @return
*/
int priority();
/**
* 初始化条件
*
* @param conditionIndex 优先级
* @param routeTokenName 路由令牌名称
*/
void init(int conditionIndex, String routeTokenName, List<String> valueList);
/**
* token是否符合本条件
*
* @return
*/
boolean accept(String innerId);
}
|
// Copyright 2000-2022 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.sdk.codeInspection;
import com.intellij.codeInspection.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.ui.DocumentAdapter;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.util.StringTokenizer;
import static com.siyeh.ig.psiutils.ExpressionUtils.isNullLiteral;
/**
* Implements an inspection to detect when object references are compared using 'a==b' or 'a!=b'.
* The quick fix converts these comparisons to 'a.equals(b) or '!a.equals(b)' respectively.
*/
public class ComparingReferencesInspection extends AbstractBaseJavaLocalInspectionTool {
// Defines the text of the quick fix intention
public static final String QUICK_FIX_NAME = "SDK: " +
InspectionsBundle.message("inspection.comparing.references.use.quickfix");
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ComparingReferencesInspection");
private final CriQuickFix myQuickFix = new CriQuickFix();
// This string holds a list of classes relevant to this inspection.
@SuppressWarnings({"WeakerAccess"})
@NonNls
public String CHECKED_CLASSES = "java.lang.String;java.util.Date";
/**
* This method is called to get the panel describing the inspection.
* It is called every time the user selects the inspection in preferences.
* The user has the option to edit the list of {@link #CHECKED_CLASSES}.
*
* @return panel to display inspection information.
*/
@Override
public JComponent createOptionsPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
final JTextField checkedClasses = new JTextField(CHECKED_CLASSES);
checkedClasses.getDocument().addDocumentListener(new DocumentAdapter() {
public void textChanged(@NotNull DocumentEvent event) {
CHECKED_CLASSES = checkedClasses.getText();
}
});
panel.add(checkedClasses);
return panel;
}
/**
* This method is overridden to provide a custom visitor.
* that inspects expressions with relational operators '==' and '!='.
* The visitor must not be recursive and must be thread-safe.
*
* @param holder object for visitor to register problems found.
* @param isOnTheFly true if inspection was run in non-batch mode
* @return non-null visitor for this inspection.
* @see JavaElementVisitor
*/
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
/**
* This string defines the short message shown to a user signaling the inspection found a problem.
* It reuses a string from the inspections bundle.
*/
@NonNls
private final String DESCRIPTION_TEMPLATE = "SDK " +
InspectionsBundle.message("inspection.comparing.references.problem.descriptor");
/**
* Avoid defining visitors for both Reference and Binary expressions.
*
* @param psiReferenceExpression The expression to be evaluated.
*/
@Override
public void visitReferenceExpression(PsiReferenceExpression psiReferenceExpression) {
}
/**
* Evaluate binary psi expressions to see if they contain relational operators '==' and '!=', AND they contain
* classes contained in CHECKED_CLASSES. The evaluation ignores expressions comparing an object to null.
* IF this criteria is met, add the expression to the problems list.
*
* @param expression The binary expression to be evaluated.
*/
@Override
public void visitBinaryExpression(PsiBinaryExpression expression) {
super.visitBinaryExpression(expression);
IElementType opSign = expression.getOperationTokenType();
if (opSign == JavaTokenType.EQEQ || opSign == JavaTokenType.NE) {
// The binary expression is the correct type for this inspection
PsiExpression lOperand = expression.getLOperand();
PsiExpression rOperand = expression.getROperand();
if (rOperand == null || isNullLiteral(lOperand) || isNullLiteral(rOperand)) {
return;
}
// Nothing is compared to null, now check the types being compared
PsiType lType = lOperand.getType();
PsiType rType = rOperand.getType();
if (isCheckedType(lType) || isCheckedType(rType)) {
// Identified an expression with potential problems, add to list with fix object.
holder.registerProblem(expression,
DESCRIPTION_TEMPLATE, myQuickFix);
}
}
}
/**
* Verifies the input is the correct {@code PsiType} for this inspection.
*
* @param type The {@code PsiType} to be examined for a match
* @return {@code true} if input is {@code PsiClassType} and matches one of the classes
* in the {@link ComparingReferencesInspection#CHECKED_CLASSES} list.
*/
private boolean isCheckedType(PsiType type) {
if (!(type instanceof PsiClassType)) {
return false;
}
StringTokenizer tokenizer = new StringTokenizer(CHECKED_CLASSES, ";");
while (tokenizer.hasMoreTokens()) {
String className = tokenizer.nextToken();
if (type.equalsToText(className)) {
return true;
}
}
return false;
}
};
}
/**
* This class provides a solution to inspection problem expressions by manipulating the PSI tree to use 'a.equals(b)'
* instead of '==' or '!='.
*/
private static class CriQuickFix implements LocalQuickFix {
/**
* Returns a partially localized string for the quick fix intention.
* Used by the test code for this plugin.
*
* @return Quick fix short name.
*/
@NotNull
@Override
public String getName() {
return QUICK_FIX_NAME;
}
/**
* This method manipulates the PSI tree to replace 'a==b' with 'a.equals(b)' or 'a!=b' with '!a.equals(b)'.
*
* @param project The project that contains the file being edited.
* @param descriptor A problem found by this inspection.
*/
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
try {
PsiBinaryExpression binaryExpression = (PsiBinaryExpression) descriptor.getPsiElement();
IElementType opSign = binaryExpression.getOperationTokenType();
PsiExpression lExpr = binaryExpression.getLOperand();
PsiExpression rExpr = binaryExpression.getROperand();
if (rExpr == null) {
return;
}
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
PsiMethodCallExpression equalsCall =
(PsiMethodCallExpression) factory.createExpressionFromText("a.equals(b)", null);
equalsCall.getMethodExpression().getQualifierExpression().replace(lExpr);
equalsCall.getArgumentList().getExpressions()[0].replace(rExpr);
PsiExpression result = (PsiExpression) binaryExpression.replace(equalsCall);
if (opSign == JavaTokenType.NE) {
PsiPrefixExpression negation = (PsiPrefixExpression) factory.createExpressionFromText("!a", null);
negation.getOperand().replace(result);
result.replace(negation);
}
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
@NotNull
public String getFamilyName() {
return getName();
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.rpc.ext;
import com.alipay.sofa.rpc.core.exception.SofaRpcException;
import com.alipay.sofa.rpc.core.request.SofaRequest;
import com.alipay.sofa.rpc.core.response.SofaResponse;
import com.alipay.sofa.rpc.filter.Filter;
import com.alipay.sofa.rpc.filter.FilterInvoker;
/**
*
*
* @author <a href="mailto:zhanggeng.zg@antfin.com">GengZhang</a>
*/
@Extension(value = "rrr5", rejection = "rrr6")
public class RejectionFilter5 extends Filter {
@Override
public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException {
return null;
}
}
|
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class Anagrammi_v1 extends Anagramma{
//Overview questa classe estende la classe anagramma, permette di creare
//una lista di anagrammi per una data stringa e una data lista di stringhe
/**
* AF(list) = [list[0],...,a[i],...,a[size]] dove i è un numero intero 0<=i<size
*
* RI = super.repOk() && size>=1 && anagram_lst.size == size
*/
//fields
//lista di anagrammi
private final List<String> anagram_lst;
//numero di elementi nella lista anagram_lst
private int size;
//constructors
/**
* Initialize this as super(s) and adds s to anagram_lst
*/
public Anagrammi_v1(String s){
super(s);
anagram_lst = new ArrayList<>();
anagram_lst.add(s);
size = 1;
assert repOk();
}
/**
* Modifies: this and lst
* Effects: Appeneds to anagram_lst anagram words found in lst removing them from lst
* Returns modified lst
* Throws NullPointerException if lst list is null
*/
public List<String> build_list_of_anagrams(List<String> lst)throws NullPointerException{
if(lst == null) throw new NullPointerException("Provided list is null!");
lst.remove(super.getString());
Iterator<String> it = lst.iterator();
while(it.hasNext()){
String s = it.next();
if(isAnagram(s)) {
anagram_lst.add(s);
it.remove();
size++;
}
}
assert repOk();
//System.out.println(lst.toString());
return lst;
}
@Override
public boolean repOk(){
if(super.repOk()){
return size>=1 && anagram_lst.size() == size;
}
return false;
}
@Override
public boolean equals(Object o){
//if(o == null) return false;
if(o == this) return true;
if(! (o instanceof Anagrammi_v1)) return false;
Anagrammi_v1 a = (Anagrammi_v1) o;
if(!super.equals(a)) return false;
if(size!= a.size) return false;
for (String s1 : a.anagram_lst) {
if(!anagram_lst.contains(s1)) return false;
}
return true;
}
@Override
public String toString(){
return anagram_lst.toString();
}
@Override
public int hashCode(){
return super.hashCode() + anagram_lst.hashCode() +Objects.hash(size);
}
}
|
/*-
*
* * Copyright 2015 Skymind,Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*
*/
package org.nd4j.linalg.jcublas.buffer;
import org.bytedeco.javacpp.Pointer;
import org.nd4j.linalg.api.buffer.DataBuffer;
import java.nio.Buffer;
/**
* A Jcuda buffer
*
* @author Adam Gibson
*/
public interface JCudaBuffer extends DataBuffer {
/**
* Get the underlying host bytebuffer
* @return
*/
@Deprecated
Buffer getHostBuffer();
/**
* THe pointer for the buffer
*
* @return the pointer for this buffer
*/
@Deprecated
Pointer getHostPointer();
/**
* Get the host pointer with the given offset
* note that this will automatically
* multiply the specified offset
* by the element size
* @param offset the offset (NOT MULTIPLIED BY ELEMENT SIZE) to index in to the pointer at
* @return the pointer at the given byte offset
*/
@Deprecated
Pointer getHostPointer(long offset);
}
|
package com.github.catalin.cretu.conference.api.event;
import com.github.catalin.cretu.conference.api.ErrorView;
import com.github.catalin.cretu.conference.api.ErrorsResponse;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Set;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import static java.util.Objects.requireNonNullElse;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class EventsResponse extends ErrorsResponse {
private Set<EventView> events;
@Builder
public EventsResponse(final Set<EventView> events, final List<ErrorView> errors) {
super(requireNonNullElse(errors, emptyList()));
this.events = requireNonNullElse(events, emptySet());
}
}
|
/**
* Autogenerated by Thrift Compiler (0.9.2)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.xiaomi.infra.galaxy.emq.thrift;
import libthrift091.scheme.IScheme;
import libthrift091.scheme.SchemeFactory;
import libthrift091.scheme.StandardScheme;
import libthrift091.scheme.TupleScheme;
import libthrift091.protocol.TTupleProtocol;
import libthrift091.protocol.TProtocolException;
import libthrift091.EncodingUtils;
import libthrift091.TException;
import libthrift091.async.AsyncMethodCallback;
import libthrift091.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2018-7-6")
public class QueryMetricRequest implements libthrift091.TBase<QueryMetricRequest, QueryMetricRequest._Fields>, java.io.Serializable, Cloneable, Comparable<QueryMetricRequest> {
private static final libthrift091.protocol.TStruct STRUCT_DESC = new libthrift091.protocol.TStruct("QueryMetricRequest");
private static final libthrift091.protocol.TField QUEUE_NAME_FIELD_DESC = new libthrift091.protocol.TField("queueName", libthrift091.protocol.TType.STRING, (short)1);
private static final libthrift091.protocol.TField START_TIME_FIELD_DESC = new libthrift091.protocol.TField("startTime", libthrift091.protocol.TType.I64, (short)2);
private static final libthrift091.protocol.TField END_TIME_FIELD_DESC = new libthrift091.protocol.TField("endTime", libthrift091.protocol.TType.I64, (short)3);
private static final libthrift091.protocol.TField METRICS_FIELD_DESC = new libthrift091.protocol.TField("metrics", libthrift091.protocol.TType.STRING, (short)4);
private static final libthrift091.protocol.TField TAGS_FIELD_DESC = new libthrift091.protocol.TField("tags", libthrift091.protocol.TType.MAP, (short)5);
private static final libthrift091.protocol.TField AGGREGATOR_FIELD_DESC = new libthrift091.protocol.TField("aggregator", libthrift091.protocol.TType.STRING, (short)6);
private static final libthrift091.protocol.TField DOWNSAMPLE_AGGREGATOR_FIELD_DESC = new libthrift091.protocol.TField("downsampleAggregator", libthrift091.protocol.TType.STRING, (short)7);
private static final libthrift091.protocol.TField DOWNSAMPLE_INTERVAL_FIELD_DESC = new libthrift091.protocol.TField("downsampleInterval", libthrift091.protocol.TType.I32, (short)8);
private static final libthrift091.protocol.TField DOWNSAMPLE_TIME_UNIT_FIELD_DESC = new libthrift091.protocol.TField("downsampleTimeUnit", libthrift091.protocol.TType.STRING, (short)9);
private static final libthrift091.protocol.TField CAL_RATE_FIELD_DESC = new libthrift091.protocol.TField("calRate", libthrift091.protocol.TType.BOOL, (short)10);
private static final libthrift091.protocol.TField TAG_NAME_FIELD_DESC = new libthrift091.protocol.TField("tagName", libthrift091.protocol.TType.STRING, (short)11);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new QueryMetricRequestStandardSchemeFactory());
schemes.put(TupleScheme.class, new QueryMetricRequestTupleSchemeFactory());
}
public String queueName; // optional
public long startTime; // optional
public long endTime; // optional
/**
* metric name
*
*/
public String metrics; // optional
/**
* tags, reference to opentsdb,
* e.g. <"type", "">
*
*/
public Map<String,String> tags; // optional
/**
* data aggregator, reference to opentsdb,
* e.g. max, avg, min
*
*/
public String aggregator; // optional
/**
* similar to aggregator above
*
*/
public String downsampleAggregator; // optional
public int downsampleInterval; // optional
/**
* downsample interval unit, reference to opentsdb,
* e.g. ms(milliseconds), s(seconds), d(day)
*
*/
public String downsampleTimeUnit; // optional
public boolean calRate; // optional
public String tagName; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements libthrift091.TFieldIdEnum {
QUEUE_NAME((short)1, "queueName"),
START_TIME((short)2, "startTime"),
END_TIME((short)3, "endTime"),
/**
* metric name
*
*/
METRICS((short)4, "metrics"),
/**
* tags, reference to opentsdb,
* e.g. <"type", "">
*
*/
TAGS((short)5, "tags"),
/**
* data aggregator, reference to opentsdb,
* e.g. max, avg, min
*
*/
AGGREGATOR((short)6, "aggregator"),
/**
* similar to aggregator above
*
*/
DOWNSAMPLE_AGGREGATOR((short)7, "downsampleAggregator"),
DOWNSAMPLE_INTERVAL((short)8, "downsampleInterval"),
/**
* downsample interval unit, reference to opentsdb,
* e.g. ms(milliseconds), s(seconds), d(day)
*
*/
DOWNSAMPLE_TIME_UNIT((short)9, "downsampleTimeUnit"),
CAL_RATE((short)10, "calRate"),
TAG_NAME((short)11, "tagName");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // QUEUE_NAME
return QUEUE_NAME;
case 2: // START_TIME
return START_TIME;
case 3: // END_TIME
return END_TIME;
case 4: // METRICS
return METRICS;
case 5: // TAGS
return TAGS;
case 6: // AGGREGATOR
return AGGREGATOR;
case 7: // DOWNSAMPLE_AGGREGATOR
return DOWNSAMPLE_AGGREGATOR;
case 8: // DOWNSAMPLE_INTERVAL
return DOWNSAMPLE_INTERVAL;
case 9: // DOWNSAMPLE_TIME_UNIT
return DOWNSAMPLE_TIME_UNIT;
case 10: // CAL_RATE
return CAL_RATE;
case 11: // TAG_NAME
return TAG_NAME;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __STARTTIME_ISSET_ID = 0;
private static final int __ENDTIME_ISSET_ID = 1;
private static final int __DOWNSAMPLEINTERVAL_ISSET_ID = 2;
private static final int __CALRATE_ISSET_ID = 3;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.QUEUE_NAME,_Fields.START_TIME,_Fields.END_TIME,_Fields.METRICS,_Fields.TAGS,_Fields.AGGREGATOR,_Fields.DOWNSAMPLE_AGGREGATOR,_Fields.DOWNSAMPLE_INTERVAL,_Fields.DOWNSAMPLE_TIME_UNIT,_Fields.CAL_RATE,_Fields.TAG_NAME};
public static final Map<_Fields, libthrift091.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, libthrift091.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, libthrift091.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.QUEUE_NAME, new libthrift091.meta_data.FieldMetaData("queueName", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING)));
tmpMap.put(_Fields.START_TIME, new libthrift091.meta_data.FieldMetaData("startTime", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I64)));
tmpMap.put(_Fields.END_TIME, new libthrift091.meta_data.FieldMetaData("endTime", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I64)));
tmpMap.put(_Fields.METRICS, new libthrift091.meta_data.FieldMetaData("metrics", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING)));
tmpMap.put(_Fields.TAGS, new libthrift091.meta_data.FieldMetaData("tags", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.MapMetaData(libthrift091.protocol.TType.MAP,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING),
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING))));
tmpMap.put(_Fields.AGGREGATOR, new libthrift091.meta_data.FieldMetaData("aggregator", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING)));
tmpMap.put(_Fields.DOWNSAMPLE_AGGREGATOR, new libthrift091.meta_data.FieldMetaData("downsampleAggregator", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING)));
tmpMap.put(_Fields.DOWNSAMPLE_INTERVAL, new libthrift091.meta_data.FieldMetaData("downsampleInterval", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.I32)));
tmpMap.put(_Fields.DOWNSAMPLE_TIME_UNIT, new libthrift091.meta_data.FieldMetaData("downsampleTimeUnit", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING)));
tmpMap.put(_Fields.CAL_RATE, new libthrift091.meta_data.FieldMetaData("calRate", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.BOOL)));
tmpMap.put(_Fields.TAG_NAME, new libthrift091.meta_data.FieldMetaData("tagName", libthrift091.TFieldRequirementType.OPTIONAL,
new libthrift091.meta_data.FieldValueMetaData(libthrift091.protocol.TType.STRING)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
libthrift091.meta_data.FieldMetaData.addStructMetaDataMap(QueryMetricRequest.class, metaDataMap);
}
public QueryMetricRequest() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public QueryMetricRequest(QueryMetricRequest other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetQueueName()) {
this.queueName = other.queueName;
}
this.startTime = other.startTime;
this.endTime = other.endTime;
if (other.isSetMetrics()) {
this.metrics = other.metrics;
}
if (other.isSetTags()) {
Map<String,String> __this__tags = new HashMap<String,String>(other.tags);
this.tags = __this__tags;
}
if (other.isSetAggregator()) {
this.aggregator = other.aggregator;
}
if (other.isSetDownsampleAggregator()) {
this.downsampleAggregator = other.downsampleAggregator;
}
this.downsampleInterval = other.downsampleInterval;
if (other.isSetDownsampleTimeUnit()) {
this.downsampleTimeUnit = other.downsampleTimeUnit;
}
this.calRate = other.calRate;
if (other.isSetTagName()) {
this.tagName = other.tagName;
}
}
public QueryMetricRequest deepCopy() {
return new QueryMetricRequest(this);
}
@Override
public void clear() {
this.queueName = null;
setStartTimeIsSet(false);
this.startTime = 0;
setEndTimeIsSet(false);
this.endTime = 0;
this.metrics = null;
this.tags = null;
this.aggregator = null;
this.downsampleAggregator = null;
setDownsampleIntervalIsSet(false);
this.downsampleInterval = 0;
this.downsampleTimeUnit = null;
setCalRateIsSet(false);
this.calRate = false;
this.tagName = null;
}
public String getQueueName() {
return this.queueName;
}
public QueryMetricRequest setQueueName(String queueName) {
this.queueName = queueName;
return this;
}
public void unsetQueueName() {
this.queueName = null;
}
/** Returns true if field queueName is set (has been assigned a value) and false otherwise */
public boolean isSetQueueName() {
return this.queueName != null;
}
public void setQueueNameIsSet(boolean value) {
if (!value) {
this.queueName = null;
}
}
public long getStartTime() {
return this.startTime;
}
public QueryMetricRequest setStartTime(long startTime) {
this.startTime = startTime;
setStartTimeIsSet(true);
return this;
}
public void unsetStartTime() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __STARTTIME_ISSET_ID);
}
/** Returns true if field startTime is set (has been assigned a value) and false otherwise */
public boolean isSetStartTime() {
return EncodingUtils.testBit(__isset_bitfield, __STARTTIME_ISSET_ID);
}
public void setStartTimeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __STARTTIME_ISSET_ID, value);
}
public long getEndTime() {
return this.endTime;
}
public QueryMetricRequest setEndTime(long endTime) {
this.endTime = endTime;
setEndTimeIsSet(true);
return this;
}
public void unsetEndTime() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ENDTIME_ISSET_ID);
}
/** Returns true if field endTime is set (has been assigned a value) and false otherwise */
public boolean isSetEndTime() {
return EncodingUtils.testBit(__isset_bitfield, __ENDTIME_ISSET_ID);
}
public void setEndTimeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ENDTIME_ISSET_ID, value);
}
/**
* metric name
*
*/
public String getMetrics() {
return this.metrics;
}
/**
* metric name
*
*/
public QueryMetricRequest setMetrics(String metrics) {
this.metrics = metrics;
return this;
}
public void unsetMetrics() {
this.metrics = null;
}
/** Returns true if field metrics is set (has been assigned a value) and false otherwise */
public boolean isSetMetrics() {
return this.metrics != null;
}
public void setMetricsIsSet(boolean value) {
if (!value) {
this.metrics = null;
}
}
public int getTagsSize() {
return (this.tags == null) ? 0 : this.tags.size();
}
public void putToTags(String key, String val) {
if (this.tags == null) {
this.tags = new HashMap<String,String>();
}
this.tags.put(key, val);
}
/**
* tags, reference to opentsdb,
* e.g. <"type", "">
*
*/
public Map<String,String> getTags() {
return this.tags;
}
/**
* tags, reference to opentsdb,
* e.g. <"type", "">
*
*/
public QueryMetricRequest setTags(Map<String,String> tags) {
this.tags = tags;
return this;
}
public void unsetTags() {
this.tags = null;
}
/** Returns true if field tags is set (has been assigned a value) and false otherwise */
public boolean isSetTags() {
return this.tags != null;
}
public void setTagsIsSet(boolean value) {
if (!value) {
this.tags = null;
}
}
/**
* data aggregator, reference to opentsdb,
* e.g. max, avg, min
*
*/
public String getAggregator() {
return this.aggregator;
}
/**
* data aggregator, reference to opentsdb,
* e.g. max, avg, min
*
*/
public QueryMetricRequest setAggregator(String aggregator) {
this.aggregator = aggregator;
return this;
}
public void unsetAggregator() {
this.aggregator = null;
}
/** Returns true if field aggregator is set (has been assigned a value) and false otherwise */
public boolean isSetAggregator() {
return this.aggregator != null;
}
public void setAggregatorIsSet(boolean value) {
if (!value) {
this.aggregator = null;
}
}
/**
* similar to aggregator above
*
*/
public String getDownsampleAggregator() {
return this.downsampleAggregator;
}
/**
* similar to aggregator above
*
*/
public QueryMetricRequest setDownsampleAggregator(String downsampleAggregator) {
this.downsampleAggregator = downsampleAggregator;
return this;
}
public void unsetDownsampleAggregator() {
this.downsampleAggregator = null;
}
/** Returns true if field downsampleAggregator is set (has been assigned a value) and false otherwise */
public boolean isSetDownsampleAggregator() {
return this.downsampleAggregator != null;
}
public void setDownsampleAggregatorIsSet(boolean value) {
if (!value) {
this.downsampleAggregator = null;
}
}
public int getDownsampleInterval() {
return this.downsampleInterval;
}
public QueryMetricRequest setDownsampleInterval(int downsampleInterval) {
this.downsampleInterval = downsampleInterval;
setDownsampleIntervalIsSet(true);
return this;
}
public void unsetDownsampleInterval() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DOWNSAMPLEINTERVAL_ISSET_ID);
}
/** Returns true if field downsampleInterval is set (has been assigned a value) and false otherwise */
public boolean isSetDownsampleInterval() {
return EncodingUtils.testBit(__isset_bitfield, __DOWNSAMPLEINTERVAL_ISSET_ID);
}
public void setDownsampleIntervalIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DOWNSAMPLEINTERVAL_ISSET_ID, value);
}
/**
* downsample interval unit, reference to opentsdb,
* e.g. ms(milliseconds), s(seconds), d(day)
*
*/
public String getDownsampleTimeUnit() {
return this.downsampleTimeUnit;
}
/**
* downsample interval unit, reference to opentsdb,
* e.g. ms(milliseconds), s(seconds), d(day)
*
*/
public QueryMetricRequest setDownsampleTimeUnit(String downsampleTimeUnit) {
this.downsampleTimeUnit = downsampleTimeUnit;
return this;
}
public void unsetDownsampleTimeUnit() {
this.downsampleTimeUnit = null;
}
/** Returns true if field downsampleTimeUnit is set (has been assigned a value) and false otherwise */
public boolean isSetDownsampleTimeUnit() {
return this.downsampleTimeUnit != null;
}
public void setDownsampleTimeUnitIsSet(boolean value) {
if (!value) {
this.downsampleTimeUnit = null;
}
}
public boolean isCalRate() {
return this.calRate;
}
public QueryMetricRequest setCalRate(boolean calRate) {
this.calRate = calRate;
setCalRateIsSet(true);
return this;
}
public void unsetCalRate() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __CALRATE_ISSET_ID);
}
/** Returns true if field calRate is set (has been assigned a value) and false otherwise */
public boolean isSetCalRate() {
return EncodingUtils.testBit(__isset_bitfield, __CALRATE_ISSET_ID);
}
public void setCalRateIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __CALRATE_ISSET_ID, value);
}
public String getTagName() {
return this.tagName;
}
public QueryMetricRequest setTagName(String tagName) {
this.tagName = tagName;
return this;
}
public void unsetTagName() {
this.tagName = null;
}
/** Returns true if field tagName is set (has been assigned a value) and false otherwise */
public boolean isSetTagName() {
return this.tagName != null;
}
public void setTagNameIsSet(boolean value) {
if (!value) {
this.tagName = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case QUEUE_NAME:
if (value == null) {
unsetQueueName();
} else {
setQueueName((String)value);
}
break;
case START_TIME:
if (value == null) {
unsetStartTime();
} else {
setStartTime((Long)value);
}
break;
case END_TIME:
if (value == null) {
unsetEndTime();
} else {
setEndTime((Long)value);
}
break;
case METRICS:
if (value == null) {
unsetMetrics();
} else {
setMetrics((String)value);
}
break;
case TAGS:
if (value == null) {
unsetTags();
} else {
setTags((Map<String,String>)value);
}
break;
case AGGREGATOR:
if (value == null) {
unsetAggregator();
} else {
setAggregator((String)value);
}
break;
case DOWNSAMPLE_AGGREGATOR:
if (value == null) {
unsetDownsampleAggregator();
} else {
setDownsampleAggregator((String)value);
}
break;
case DOWNSAMPLE_INTERVAL:
if (value == null) {
unsetDownsampleInterval();
} else {
setDownsampleInterval((Integer)value);
}
break;
case DOWNSAMPLE_TIME_UNIT:
if (value == null) {
unsetDownsampleTimeUnit();
} else {
setDownsampleTimeUnit((String)value);
}
break;
case CAL_RATE:
if (value == null) {
unsetCalRate();
} else {
setCalRate((Boolean)value);
}
break;
case TAG_NAME:
if (value == null) {
unsetTagName();
} else {
setTagName((String)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case QUEUE_NAME:
return getQueueName();
case START_TIME:
return Long.valueOf(getStartTime());
case END_TIME:
return Long.valueOf(getEndTime());
case METRICS:
return getMetrics();
case TAGS:
return getTags();
case AGGREGATOR:
return getAggregator();
case DOWNSAMPLE_AGGREGATOR:
return getDownsampleAggregator();
case DOWNSAMPLE_INTERVAL:
return Integer.valueOf(getDownsampleInterval());
case DOWNSAMPLE_TIME_UNIT:
return getDownsampleTimeUnit();
case CAL_RATE:
return Boolean.valueOf(isCalRate());
case TAG_NAME:
return getTagName();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case QUEUE_NAME:
return isSetQueueName();
case START_TIME:
return isSetStartTime();
case END_TIME:
return isSetEndTime();
case METRICS:
return isSetMetrics();
case TAGS:
return isSetTags();
case AGGREGATOR:
return isSetAggregator();
case DOWNSAMPLE_AGGREGATOR:
return isSetDownsampleAggregator();
case DOWNSAMPLE_INTERVAL:
return isSetDownsampleInterval();
case DOWNSAMPLE_TIME_UNIT:
return isSetDownsampleTimeUnit();
case CAL_RATE:
return isSetCalRate();
case TAG_NAME:
return isSetTagName();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof QueryMetricRequest)
return this.equals((QueryMetricRequest)that);
return false;
}
public boolean equals(QueryMetricRequest that) {
if (that == null)
return false;
boolean this_present_queueName = true && this.isSetQueueName();
boolean that_present_queueName = true && that.isSetQueueName();
if (this_present_queueName || that_present_queueName) {
if (!(this_present_queueName && that_present_queueName))
return false;
if (!this.queueName.equals(that.queueName))
return false;
}
boolean this_present_startTime = true && this.isSetStartTime();
boolean that_present_startTime = true && that.isSetStartTime();
if (this_present_startTime || that_present_startTime) {
if (!(this_present_startTime && that_present_startTime))
return false;
if (this.startTime != that.startTime)
return false;
}
boolean this_present_endTime = true && this.isSetEndTime();
boolean that_present_endTime = true && that.isSetEndTime();
if (this_present_endTime || that_present_endTime) {
if (!(this_present_endTime && that_present_endTime))
return false;
if (this.endTime != that.endTime)
return false;
}
boolean this_present_metrics = true && this.isSetMetrics();
boolean that_present_metrics = true && that.isSetMetrics();
if (this_present_metrics || that_present_metrics) {
if (!(this_present_metrics && that_present_metrics))
return false;
if (!this.metrics.equals(that.metrics))
return false;
}
boolean this_present_tags = true && this.isSetTags();
boolean that_present_tags = true && that.isSetTags();
if (this_present_tags || that_present_tags) {
if (!(this_present_tags && that_present_tags))
return false;
if (!this.tags.equals(that.tags))
return false;
}
boolean this_present_aggregator = true && this.isSetAggregator();
boolean that_present_aggregator = true && that.isSetAggregator();
if (this_present_aggregator || that_present_aggregator) {
if (!(this_present_aggregator && that_present_aggregator))
return false;
if (!this.aggregator.equals(that.aggregator))
return false;
}
boolean this_present_downsampleAggregator = true && this.isSetDownsampleAggregator();
boolean that_present_downsampleAggregator = true && that.isSetDownsampleAggregator();
if (this_present_downsampleAggregator || that_present_downsampleAggregator) {
if (!(this_present_downsampleAggregator && that_present_downsampleAggregator))
return false;
if (!this.downsampleAggregator.equals(that.downsampleAggregator))
return false;
}
boolean this_present_downsampleInterval = true && this.isSetDownsampleInterval();
boolean that_present_downsampleInterval = true && that.isSetDownsampleInterval();
if (this_present_downsampleInterval || that_present_downsampleInterval) {
if (!(this_present_downsampleInterval && that_present_downsampleInterval))
return false;
if (this.downsampleInterval != that.downsampleInterval)
return false;
}
boolean this_present_downsampleTimeUnit = true && this.isSetDownsampleTimeUnit();
boolean that_present_downsampleTimeUnit = true && that.isSetDownsampleTimeUnit();
if (this_present_downsampleTimeUnit || that_present_downsampleTimeUnit) {
if (!(this_present_downsampleTimeUnit && that_present_downsampleTimeUnit))
return false;
if (!this.downsampleTimeUnit.equals(that.downsampleTimeUnit))
return false;
}
boolean this_present_calRate = true && this.isSetCalRate();
boolean that_present_calRate = true && that.isSetCalRate();
if (this_present_calRate || that_present_calRate) {
if (!(this_present_calRate && that_present_calRate))
return false;
if (this.calRate != that.calRate)
return false;
}
boolean this_present_tagName = true && this.isSetTagName();
boolean that_present_tagName = true && that.isSetTagName();
if (this_present_tagName || that_present_tagName) {
if (!(this_present_tagName && that_present_tagName))
return false;
if (!this.tagName.equals(that.tagName))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_queueName = true && (isSetQueueName());
list.add(present_queueName);
if (present_queueName)
list.add(queueName);
boolean present_startTime = true && (isSetStartTime());
list.add(present_startTime);
if (present_startTime)
list.add(startTime);
boolean present_endTime = true && (isSetEndTime());
list.add(present_endTime);
if (present_endTime)
list.add(endTime);
boolean present_metrics = true && (isSetMetrics());
list.add(present_metrics);
if (present_metrics)
list.add(metrics);
boolean present_tags = true && (isSetTags());
list.add(present_tags);
if (present_tags)
list.add(tags);
boolean present_aggregator = true && (isSetAggregator());
list.add(present_aggregator);
if (present_aggregator)
list.add(aggregator);
boolean present_downsampleAggregator = true && (isSetDownsampleAggregator());
list.add(present_downsampleAggregator);
if (present_downsampleAggregator)
list.add(downsampleAggregator);
boolean present_downsampleInterval = true && (isSetDownsampleInterval());
list.add(present_downsampleInterval);
if (present_downsampleInterval)
list.add(downsampleInterval);
boolean present_downsampleTimeUnit = true && (isSetDownsampleTimeUnit());
list.add(present_downsampleTimeUnit);
if (present_downsampleTimeUnit)
list.add(downsampleTimeUnit);
boolean present_calRate = true && (isSetCalRate());
list.add(present_calRate);
if (present_calRate)
list.add(calRate);
boolean present_tagName = true && (isSetTagName());
list.add(present_tagName);
if (present_tagName)
list.add(tagName);
return list.hashCode();
}
@Override
public int compareTo(QueryMetricRequest other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetQueueName()).compareTo(other.isSetQueueName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetQueueName()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.queueName, other.queueName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetStartTime()).compareTo(other.isSetStartTime());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetStartTime()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.startTime, other.startTime);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetEndTime()).compareTo(other.isSetEndTime());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetEndTime()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.endTime, other.endTime);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetMetrics()).compareTo(other.isSetMetrics());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMetrics()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.metrics, other.metrics);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetTags()).compareTo(other.isSetTags());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTags()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.tags, other.tags);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetAggregator()).compareTo(other.isSetAggregator());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetAggregator()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.aggregator, other.aggregator);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetDownsampleAggregator()).compareTo(other.isSetDownsampleAggregator());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDownsampleAggregator()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.downsampleAggregator, other.downsampleAggregator);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetDownsampleInterval()).compareTo(other.isSetDownsampleInterval());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDownsampleInterval()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.downsampleInterval, other.downsampleInterval);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetDownsampleTimeUnit()).compareTo(other.isSetDownsampleTimeUnit());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDownsampleTimeUnit()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.downsampleTimeUnit, other.downsampleTimeUnit);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetCalRate()).compareTo(other.isSetCalRate());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCalRate()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.calRate, other.calRate);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetTagName()).compareTo(other.isSetTagName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTagName()) {
lastComparison = libthrift091.TBaseHelper.compareTo(this.tagName, other.tagName);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(libthrift091.protocol.TProtocol iprot) throws libthrift091.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(libthrift091.protocol.TProtocol oprot) throws libthrift091.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("QueryMetricRequest(");
boolean first = true;
if (isSetQueueName()) {
sb.append("queueName:");
if (this.queueName == null) {
sb.append("null");
} else {
sb.append(this.queueName);
}
first = false;
}
if (isSetStartTime()) {
if (!first) sb.append(", ");
sb.append("startTime:");
sb.append(this.startTime);
first = false;
}
if (isSetEndTime()) {
if (!first) sb.append(", ");
sb.append("endTime:");
sb.append(this.endTime);
first = false;
}
if (isSetMetrics()) {
if (!first) sb.append(", ");
sb.append("metrics:");
if (this.metrics == null) {
sb.append("null");
} else {
sb.append(this.metrics);
}
first = false;
}
if (isSetTags()) {
if (!first) sb.append(", ");
sb.append("tags:");
if (this.tags == null) {
sb.append("null");
} else {
sb.append(this.tags);
}
first = false;
}
if (isSetAggregator()) {
if (!first) sb.append(", ");
sb.append("aggregator:");
if (this.aggregator == null) {
sb.append("null");
} else {
sb.append(this.aggregator);
}
first = false;
}
if (isSetDownsampleAggregator()) {
if (!first) sb.append(", ");
sb.append("downsampleAggregator:");
if (this.downsampleAggregator == null) {
sb.append("null");
} else {
sb.append(this.downsampleAggregator);
}
first = false;
}
if (isSetDownsampleInterval()) {
if (!first) sb.append(", ");
sb.append("downsampleInterval:");
sb.append(this.downsampleInterval);
first = false;
}
if (isSetDownsampleTimeUnit()) {
if (!first) sb.append(", ");
sb.append("downsampleTimeUnit:");
if (this.downsampleTimeUnit == null) {
sb.append("null");
} else {
sb.append(this.downsampleTimeUnit);
}
first = false;
}
if (isSetCalRate()) {
if (!first) sb.append(", ");
sb.append("calRate:");
sb.append(this.calRate);
first = false;
}
if (isSetTagName()) {
if (!first) sb.append(", ");
sb.append("tagName:");
if (this.tagName == null) {
sb.append("null");
} else {
sb.append(this.tagName);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws libthrift091.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new libthrift091.protocol.TCompactProtocol(new libthrift091.transport.TIOStreamTransport(out)));
} catch (libthrift091.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new libthrift091.protocol.TCompactProtocol(new libthrift091.transport.TIOStreamTransport(in)));
} catch (libthrift091.TException te) {
throw new java.io.IOException(te);
}
}
private static class QueryMetricRequestStandardSchemeFactory implements SchemeFactory {
public QueryMetricRequestStandardScheme getScheme() {
return new QueryMetricRequestStandardScheme();
}
}
private static class QueryMetricRequestStandardScheme extends StandardScheme<QueryMetricRequest> {
public void read(libthrift091.protocol.TProtocol iprot, QueryMetricRequest struct) throws libthrift091.TException {
libthrift091.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == libthrift091.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // QUEUE_NAME
if (schemeField.type == libthrift091.protocol.TType.STRING) {
struct.queueName = iprot.readString();
struct.setQueueNameIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // START_TIME
if (schemeField.type == libthrift091.protocol.TType.I64) {
struct.startTime = iprot.readI64();
struct.setStartTimeIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // END_TIME
if (schemeField.type == libthrift091.protocol.TType.I64) {
struct.endTime = iprot.readI64();
struct.setEndTimeIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // METRICS
if (schemeField.type == libthrift091.protocol.TType.STRING) {
struct.metrics = iprot.readString();
struct.setMetricsIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // TAGS
if (schemeField.type == libthrift091.protocol.TType.MAP) {
{
libthrift091.protocol.TMap _map82 = iprot.readMapBegin();
struct.tags = new HashMap<String,String>(2*_map82.size);
String _key83;
String _val84;
for (int _i85 = 0; _i85 < _map82.size; ++_i85)
{
_key83 = iprot.readString();
_val84 = iprot.readString();
struct.tags.put(_key83, _val84);
}
iprot.readMapEnd();
}
struct.setTagsIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 6: // AGGREGATOR
if (schemeField.type == libthrift091.protocol.TType.STRING) {
struct.aggregator = iprot.readString();
struct.setAggregatorIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 7: // DOWNSAMPLE_AGGREGATOR
if (schemeField.type == libthrift091.protocol.TType.STRING) {
struct.downsampleAggregator = iprot.readString();
struct.setDownsampleAggregatorIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 8: // DOWNSAMPLE_INTERVAL
if (schemeField.type == libthrift091.protocol.TType.I32) {
struct.downsampleInterval = iprot.readI32();
struct.setDownsampleIntervalIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 9: // DOWNSAMPLE_TIME_UNIT
if (schemeField.type == libthrift091.protocol.TType.STRING) {
struct.downsampleTimeUnit = iprot.readString();
struct.setDownsampleTimeUnitIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 10: // CAL_RATE
if (schemeField.type == libthrift091.protocol.TType.BOOL) {
struct.calRate = iprot.readBool();
struct.setCalRateIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 11: // TAG_NAME
if (schemeField.type == libthrift091.protocol.TType.STRING) {
struct.tagName = iprot.readString();
struct.setTagNameIsSet(true);
} else {
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
libthrift091.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(libthrift091.protocol.TProtocol oprot, QueryMetricRequest struct) throws libthrift091.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.queueName != null) {
if (struct.isSetQueueName()) {
oprot.writeFieldBegin(QUEUE_NAME_FIELD_DESC);
oprot.writeString(struct.queueName);
oprot.writeFieldEnd();
}
}
if (struct.isSetStartTime()) {
oprot.writeFieldBegin(START_TIME_FIELD_DESC);
oprot.writeI64(struct.startTime);
oprot.writeFieldEnd();
}
if (struct.isSetEndTime()) {
oprot.writeFieldBegin(END_TIME_FIELD_DESC);
oprot.writeI64(struct.endTime);
oprot.writeFieldEnd();
}
if (struct.metrics != null) {
if (struct.isSetMetrics()) {
oprot.writeFieldBegin(METRICS_FIELD_DESC);
oprot.writeString(struct.metrics);
oprot.writeFieldEnd();
}
}
if (struct.tags != null) {
if (struct.isSetTags()) {
oprot.writeFieldBegin(TAGS_FIELD_DESC);
{
oprot.writeMapBegin(new libthrift091.protocol.TMap(libthrift091.protocol.TType.STRING, libthrift091.protocol.TType.STRING, struct.tags.size()));
for (Map.Entry<String, String> _iter86 : struct.tags.entrySet())
{
oprot.writeString(_iter86.getKey());
oprot.writeString(_iter86.getValue());
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
}
if (struct.aggregator != null) {
if (struct.isSetAggregator()) {
oprot.writeFieldBegin(AGGREGATOR_FIELD_DESC);
oprot.writeString(struct.aggregator);
oprot.writeFieldEnd();
}
}
if (struct.downsampleAggregator != null) {
if (struct.isSetDownsampleAggregator()) {
oprot.writeFieldBegin(DOWNSAMPLE_AGGREGATOR_FIELD_DESC);
oprot.writeString(struct.downsampleAggregator);
oprot.writeFieldEnd();
}
}
if (struct.isSetDownsampleInterval()) {
oprot.writeFieldBegin(DOWNSAMPLE_INTERVAL_FIELD_DESC);
oprot.writeI32(struct.downsampleInterval);
oprot.writeFieldEnd();
}
if (struct.downsampleTimeUnit != null) {
if (struct.isSetDownsampleTimeUnit()) {
oprot.writeFieldBegin(DOWNSAMPLE_TIME_UNIT_FIELD_DESC);
oprot.writeString(struct.downsampleTimeUnit);
oprot.writeFieldEnd();
}
}
if (struct.isSetCalRate()) {
oprot.writeFieldBegin(CAL_RATE_FIELD_DESC);
oprot.writeBool(struct.calRate);
oprot.writeFieldEnd();
}
if (struct.tagName != null) {
if (struct.isSetTagName()) {
oprot.writeFieldBegin(TAG_NAME_FIELD_DESC);
oprot.writeString(struct.tagName);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class QueryMetricRequestTupleSchemeFactory implements SchemeFactory {
public QueryMetricRequestTupleScheme getScheme() {
return new QueryMetricRequestTupleScheme();
}
}
private static class QueryMetricRequestTupleScheme extends TupleScheme<QueryMetricRequest> {
@Override
public void write(libthrift091.protocol.TProtocol prot, QueryMetricRequest struct) throws libthrift091.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetQueueName()) {
optionals.set(0);
}
if (struct.isSetStartTime()) {
optionals.set(1);
}
if (struct.isSetEndTime()) {
optionals.set(2);
}
if (struct.isSetMetrics()) {
optionals.set(3);
}
if (struct.isSetTags()) {
optionals.set(4);
}
if (struct.isSetAggregator()) {
optionals.set(5);
}
if (struct.isSetDownsampleAggregator()) {
optionals.set(6);
}
if (struct.isSetDownsampleInterval()) {
optionals.set(7);
}
if (struct.isSetDownsampleTimeUnit()) {
optionals.set(8);
}
if (struct.isSetCalRate()) {
optionals.set(9);
}
if (struct.isSetTagName()) {
optionals.set(10);
}
oprot.writeBitSet(optionals, 11);
if (struct.isSetQueueName()) {
oprot.writeString(struct.queueName);
}
if (struct.isSetStartTime()) {
oprot.writeI64(struct.startTime);
}
if (struct.isSetEndTime()) {
oprot.writeI64(struct.endTime);
}
if (struct.isSetMetrics()) {
oprot.writeString(struct.metrics);
}
if (struct.isSetTags()) {
{
oprot.writeI32(struct.tags.size());
for (Map.Entry<String, String> _iter87 : struct.tags.entrySet())
{
oprot.writeString(_iter87.getKey());
oprot.writeString(_iter87.getValue());
}
}
}
if (struct.isSetAggregator()) {
oprot.writeString(struct.aggregator);
}
if (struct.isSetDownsampleAggregator()) {
oprot.writeString(struct.downsampleAggregator);
}
if (struct.isSetDownsampleInterval()) {
oprot.writeI32(struct.downsampleInterval);
}
if (struct.isSetDownsampleTimeUnit()) {
oprot.writeString(struct.downsampleTimeUnit);
}
if (struct.isSetCalRate()) {
oprot.writeBool(struct.calRate);
}
if (struct.isSetTagName()) {
oprot.writeString(struct.tagName);
}
}
@Override
public void read(libthrift091.protocol.TProtocol prot, QueryMetricRequest struct) throws libthrift091.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(11);
if (incoming.get(0)) {
struct.queueName = iprot.readString();
struct.setQueueNameIsSet(true);
}
if (incoming.get(1)) {
struct.startTime = iprot.readI64();
struct.setStartTimeIsSet(true);
}
if (incoming.get(2)) {
struct.endTime = iprot.readI64();
struct.setEndTimeIsSet(true);
}
if (incoming.get(3)) {
struct.metrics = iprot.readString();
struct.setMetricsIsSet(true);
}
if (incoming.get(4)) {
{
libthrift091.protocol.TMap _map88 = new libthrift091.protocol.TMap(libthrift091.protocol.TType.STRING, libthrift091.protocol.TType.STRING, iprot.readI32());
struct.tags = new HashMap<String,String>(2*_map88.size);
String _key89;
String _val90;
for (int _i91 = 0; _i91 < _map88.size; ++_i91)
{
_key89 = iprot.readString();
_val90 = iprot.readString();
struct.tags.put(_key89, _val90);
}
}
struct.setTagsIsSet(true);
}
if (incoming.get(5)) {
struct.aggregator = iprot.readString();
struct.setAggregatorIsSet(true);
}
if (incoming.get(6)) {
struct.downsampleAggregator = iprot.readString();
struct.setDownsampleAggregatorIsSet(true);
}
if (incoming.get(7)) {
struct.downsampleInterval = iprot.readI32();
struct.setDownsampleIntervalIsSet(true);
}
if (incoming.get(8)) {
struct.downsampleTimeUnit = iprot.readString();
struct.setDownsampleTimeUnitIsSet(true);
}
if (incoming.get(9)) {
struct.calRate = iprot.readBool();
struct.setCalRateIsSet(true);
}
if (incoming.get(10)) {
struct.tagName = iprot.readString();
struct.setTagNameIsSet(true);
}
}
}
}
|
package mypackage.rest;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.testng.SkipException;
import java.io.IOException;
public class TestBase {
private Executor getExecutor() {
return Executor.newInstance().
auth("288f44776e7bec4bf44fdfeb1e646490", "");
}
public String getIssueStatus(int issueId) throws IOException {
String status = "";
String json = getExecutor()
.execute(Request.Get("http://bugify.stqa.ru/api/issues/" + issueId + ".json"))
.returnContent().asString();
JsonElement parsed = new JsonParser().parse(json);
JsonArray issues = (JsonArray) parsed.getAsJsonObject().get("issues");
for(JsonElement issue : issues) {
status = issue.getAsJsonObject().get("state_name").getAsString();
}
return status;
}
public boolean isIssueOpen(int issueId) throws IOException {
String status = getIssueStatus(issueId);
if (status.equals("Fixed")) {
return false;
}
return true;
}
public void skipIfNotFixed(int issueId) throws IOException {
if (isIssueOpen(issueId)) {
throw new SkipException("Ignored because of issue " + issueId);
}
}
}
|
package cn.axg.study.mq.rabbitmq.boot.work_queues;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class ConsumerWork {
@RabbitListener(queuesToDeclare = @Queue(value = "work-queue"))
public void receive1(String message){
System.out.println("消费者1===========>" + message);
}
@RabbitListener(queuesToDeclare = @Queue(value = "work-queue"))
public void receive2(String message){
System.out.println("消费者2===========>" + message);
}
}
|
package com.zev.noads;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.zev.noads", appContext.getPackageName());
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.testcase.httpclient5;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/httpclient-5.x")
public class BackController {
@GetMapping("/back")
public String back() {
return "Hello back";
}
}
|
package net.eduard.curso.projeto.essentials;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* Comando de setar o mesmos items de você para o restante de jogadores
* @author Eduard
*
*/
public class ComandoSkit implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label,
String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
for (Player playerLoop:Bukkit.getOnlinePlayers()) {
if (playerLoop!=player) {
playerLoop.getInventory().setArmorContents(player.getInventory().getArmorContents());
playerLoop.getInventory().setContents(player.getInventory().getContents());
}
}
player.sendMessage("§6Seu inventario foi aplicado para todos jogadores!");
}
return true;
}
}
|
// Targeted by JavaCPP version 1.5.3-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.cuda.cudart;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.cuda.global.cudart.*;
/**
* CUDA texture descriptor
*/
@Properties(inherit = org.bytedeco.cuda.presets.cudart.class)
public class cudaTextureDesc extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public cudaTextureDesc() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public cudaTextureDesc(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public cudaTextureDesc(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public cudaTextureDesc position(long position) {
return (cudaTextureDesc)super.position(position);
}
/**
* Texture address mode for up to 3 dimensions
*/
public native @Cast("cudaTextureAddressMode") int addressMode(int i); public native cudaTextureDesc addressMode(int i, int setter);
@MemberGetter public native @Cast("cudaTextureAddressMode*") IntPointer addressMode();
/**
* Texture filter mode
*/
public native @Cast("cudaTextureFilterMode") int filterMode(); public native cudaTextureDesc filterMode(int setter);
/**
* Texture read mode
*/
public native @Cast("cudaTextureReadMode") int readMode(); public native cudaTextureDesc readMode(int setter);
/**
* Perform sRGB->linear conversion during texture read
*/
public native int sRGB(); public native cudaTextureDesc sRGB(int setter);
/**
* Texture Border Color
*/
public native float borderColor(int i); public native cudaTextureDesc borderColor(int i, float setter);
@MemberGetter public native FloatPointer borderColor();
/**
* Indicates whether texture reads are normalized or not
*/
public native int normalizedCoords(); public native cudaTextureDesc normalizedCoords(int setter);
/**
* Limit to the anisotropy ratio
*/
public native @Cast("unsigned int") int maxAnisotropy(); public native cudaTextureDesc maxAnisotropy(int setter);
/**
* Mipmap filter mode
*/
public native @Cast("cudaTextureFilterMode") int mipmapFilterMode(); public native cudaTextureDesc mipmapFilterMode(int setter);
/**
* Offset applied to the supplied mipmap level
*/
public native float mipmapLevelBias(); public native cudaTextureDesc mipmapLevelBias(float setter);
/**
* Lower end of the mipmap level range to clamp access to
*/
public native float minMipmapLevelClamp(); public native cudaTextureDesc minMipmapLevelClamp(float setter);
/**
* Upper end of the mipmap level range to clamp access to
*/
public native float maxMipmapLevelClamp(); public native cudaTextureDesc maxMipmapLevelClamp(float setter);
}
|
/*
* Copyright 2018 NAVER Corp.
*
* 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.navercorp.pinpoint.io.request;
import com.navercorp.pinpoint.io.header.Header;
import com.navercorp.pinpoint.io.header.HeaderEntity;
import com.navercorp.pinpoint.io.header.v1.HeaderV1;
/**
* @author Woonduk Kang(emeroad)
*/
public class EmptyMessage<T> implements Message<T> {
public static final Message<?> INSTANCE = new EmptyMessage<>();
private static final Header EMPTY_HEADER = new HeaderV1((short) -1);
@Override
public Header getHeader() {
return EMPTY_HEADER;
}
@Override
public HeaderEntity getHeaderEntity() {
return HeaderEntity.EMPTY_HEADER_ENTITY;
}
@Override
public T getData() {
return null;
}
public static <T> Message<T> emptyMessage() {
return (Message<T>) INSTANCE;
}
}
|
package se.liu.ida.graphics;
import java.awt.*;
import java.util.List;
/**
* A Painter is responsible for drawing the game area. Multiple painters can be
* used to draw the game area from different players views.
*/
public class Painter {
private int width;
private int height;
private final int scale;
private List<Player> players;
private Player focussedPlayer;
private Board board;
private boolean draw = true;
/**
* Create a new painter with scale, board which state to be drawn, player to
* follow and all players
*
* @param scale how much a tile should be scaled from one pixel
* @param board board which state to be drawn
* @param focussedPlayer player to follow from which view the game area and
* player should be drawn
* @param players all players that at each time should be drawn
*/
Painter(int scale, Board board, Player focussedPlayer, List<Player> players) {
this.scale = scale;
this.board = board;
this.players = players;
this.focussedPlayer = focussedPlayer;
}
/**
* Sets whether painter should draw or not
*
* @param draw true if painter should continue to draw, false otherwise
*/
public void setDraw(boolean draw) {
this.draw = draw;
}
/**
* Method is called from board to initialize a draw with graphics received
*
* @param g graphics object used to draw
*/
void draw(Graphics g) {
if (draw) {
height = g.getClipBounds().height;
width = g.getClipBounds().width;
drawGameArea(g);
drawPlayers(g);
}
}
/**
* Draws all players and their name on the map with corresponding color.
* Doesn't draw players not seen by player.
*
* @param g Graphics object received as argument in paintComponent method
*/
private void drawPlayers(Graphics g) {
int drawX;
int drawY;
g.setFont(new Font("Monospaced", Font.PLAIN, 12));
FontMetrics fontMetrics = g.getFontMetrics();
for (Player player : players) {
// x and y position relative to focussedPlayer at which player should be drawn
drawX = (player.getX() - focussedPlayer.getX()) * scale + ((width - scale) / 2);
drawY = (player.getY() - focussedPlayer.getY()) * scale + ((height - scale) / 2);
if (player != focussedPlayer) {
// For all other players than focussedPlayer we need to smooth animations
// regarding to animation smoothing
// of focussedPlayer
drawX += ((player.getDx() - focussedPlayer.getDx()) * scale
* ((board.getTickCounter() + 1) / (double) board.getTickReset()));
drawY += ((player.getDy() - focussedPlayer.getDy()) * scale
* ((board.getTickCounter() + 1) / (double) board.getTickReset()));
}
g.setColor(Color.BLACK);
g.drawString(player.getName(), drawX + (scale - fontMetrics.stringWidth(player.getName())) / 2,
drawY + scale + 16);
// Draw player if visible
if ((drawX + scale > 0 && drawX < width) && (drawY + scale > 0 && drawY < height)) {
g.setColor(player.getColor());
g.fillRect(drawX, drawY, scale, scale);
}
}
}
/**
* Draws all tiles on the map with colors corresponding to owner and contested
* owner. Doesn't draw tiles not seen by player.
*
* @param g Graphics object received as argument in paintComponent method
*/
private void drawGameArea(Graphics g) {
int drawX;
int drawY;
for (int y = 0; y < board.getAreaHeight(); y++) {
for (int x = 0; x < board.getAreaWidth(); x++) {
// x and y position relative to focussedPlayer at which tile should be drawn
drawX = (x - focussedPlayer.getX()) * scale + ((width - scale) / 2);
drawY = (y - focussedPlayer.getY()) * scale + ((height - scale) / 2);
// If visible, draw the tile's color EDIT: drawing first with white, to have
// lighter colors
if ((drawX + scale > 0 && drawX < width) && (drawY + scale > 0 && drawY < height)) {
g.setColor(Color.WHITE);
g.fillRect(drawX, drawY, scale, scale);
g.setColor(board.getTile(x, y).getColor());
g.fillRect(drawX, drawY, scale, scale);
}
}
}
}
}
|
/*
* Copyright (C) 2016 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.android.builder.utils;
import static com.android.testutils.truth.FileSubject.assertThat;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import com.android.annotations.NonNull;
import com.android.repository.Revision;
import com.android.testutils.concurrency.ConcurrencyTester;
import com.android.utils.FileUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
/** Test cases for {@link FileCache}. */
public class FileCacheTest {
@Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File cacheDir;
private File outputDir;
@Before
public void setUp() throws IOException {
cacheDir = temporaryFolder.newFolder();
outputDir = temporaryFolder.newFolder();
}
@Test
public void testCreateFile_SameInputSameOutput() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
// First access to the cache, expect cache miss
fileCache.createFile(outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
assertThat(fileCache.getHits()).isEqualTo(0);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(outputFile).hasContents("Some text");
FileUtils.delete(outputFile);
// Second access to the cache, expect cache hit
fileCache.createFile(
outputFile,
inputs,
() -> {
fail("This statement should not be executed");
writeStringToFile("This text should not be written", outputFile);
});
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(outputFile).hasContents("Some text");
}
@Test
public void testCreateFile_SameInputDifferentOutputs() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
// First access to the cache
File outputFile1 = new File(outputDir, "output1");
fileCache.createFile(
outputFile1, inputs, () -> writeStringToFile("Some text", outputFile1));
// Second access to the cache, expect cache hit
File outputFile2 = new File(outputDir, "output2");
fileCache.createFile(
outputFile2,
inputs,
() -> {
fail("This statement should not be executed");
writeStringToFile("This text should not be written", outputFile2);
});
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(outputFile1).hasContents("Some text");
assertThat(outputFile2).hasContents("Some text");
}
@Test
public void testCreateFile_DifferentInputsSameOutput() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
File outputFile = new File(outputDir, "output");
// First access to the cache
FileCache.Inputs inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input1")
.build();
fileCache.createFile(outputFile, inputs1, () -> writeStringToFile("Some text", outputFile));
// Second access to the cache, expect cache miss
FileCache.Inputs inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input2")
.build();
fileCache.createFile(
outputFile, inputs2, () -> writeStringToFile("Some other text", outputFile));
assertThat(fileCache.getHits()).isEqualTo(0);
assertThat(fileCache.getMisses()).isEqualTo(2);
assertThat(outputFile).hasContents("Some other text");
}
@Test
public void testCreateFile_DifferentInputsDifferentOutputs() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
// First access to the cache
FileCache.Inputs inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input1")
.build();
File outputFile1 = new File(outputDir, "output1");
fileCache.createFile(
outputFile1, inputs1, () -> writeStringToFile("Some text", outputFile1));
// Second access to the cache, expect cache miss
FileCache.Inputs inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input2")
.build();
File outputFile2 = new File(outputDir, "output2");
fileCache.createFile(
outputFile2, inputs2, () -> writeStringToFile("Some other text", outputFile2));
assertThat(fileCache.getHits()).isEqualTo(0);
assertThat(fileCache.getMisses()).isEqualTo(2);
assertThat(outputFile1).hasContents("Some text");
assertThat(outputFile2).hasContents("Some other text");
}
@Test
public void testCreateFileInCacheIfAbsent_SameInput() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
// First access to the cache, expect cache miss
File cachedFile =
fileCache
.createFileInCacheIfAbsent(
inputs, (outputFile) -> writeStringToFile("Some text", outputFile))
.getCachedFile();
assertThat(fileCache.getHits()).isEqualTo(0);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(cachedFile).hasContents("Some text");
// Second access to the cache, expect cache hit
File cachedFile2 =
fileCache
.createFileInCacheIfAbsent(
inputs,
(outputFile) -> {
fail("This statement should not be executed");
writeStringToFile(
"This text should not be written", outputFile);
})
.getCachedFile();
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(cachedFile2).isEqualTo(cachedFile);
assertThat(cachedFile).hasContents("Some text");
}
@Test
public void testCreateFileInCacheIfAbsent_DifferentInputs() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
// First access to the cache
FileCache.Inputs inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input1")
.build();
File cachedFile1 =
fileCache
.createFileInCacheIfAbsent(
inputs1, (outputFile) -> writeStringToFile("Some text", outputFile))
.getCachedFile();
// Second access to the cache, expect cache miss
FileCache.Inputs inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input2")
.build();
File cachedFile2 =
fileCache
.createFileInCacheIfAbsent(
inputs2,
(outputFile) -> writeStringToFile("Some other text", outputFile))
.getCachedFile();
assertThat(fileCache.getHits()).isEqualTo(0);
assertThat(fileCache.getMisses()).isEqualTo(2);
assertThat(cachedFile2).isNotEqualTo(cachedFile1);
assertThat(cachedFile1).hasContents("Some text");
assertThat(cachedFile2).hasContents("Some other text");
}
@Test
public void testCreateFile_OutputToDirectory() throws Exception {
// Use same input different outputs
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
// First access to the cache
File outputDir1 = new File(outputDir, "outputDir1");
fileCache.createFile(
outputDir1,
inputs,
() -> {
FileUtils.mkdirs(outputDir1);
writeStringToFile("Some text", new File(outputDir1, "fileInOutputDir"));
});
// Second access to the cache, expect cache hit
File outputDir2 = new File(outputDir, "outputDir2");
fileCache.createFile(
outputDir2,
inputs,
() -> {
fail("This statement should not be executed");
FileUtils.mkdirs(outputDir2);
writeStringToFile(
"This text should not be written",
new File(outputDir2, "fileInOutputDir"));
});
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(outputDir1.list()).hasLength(1);
assertThat(outputDir2.list()).hasLength(1);
assertThat(new File(outputDir1, "fileInOutputDir")).hasContents("Some text");
assertThat(new File(outputDir2, "fileInOutputDir")).hasContents("Some text");
}
@Test
public void testCreateFileInCacheIfAbsent_OutputToDirectory() throws Exception {
// Use same input
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
// First access to the cache
File cachedDir1 =
fileCache
.createFileInCacheIfAbsent(
inputs,
(outputDir) -> {
FileUtils.mkdirs(outputDir);
writeStringToFile(
"Some text", new File(outputDir, "fileInOutputDir"));
})
.getCachedFile();
// Second access to the cache, expect cache hit
File cachedDir2 =
fileCache
.createFileInCacheIfAbsent(
inputs,
(outputDir) -> {
fail("This statement should not be executed");
FileUtils.mkdirs(outputDir);
writeStringToFile(
"This text should not be written",
new File(outputDir, "fileInOutputDir"));
})
.getCachedFile();
assertNotNull(cachedDir2);
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(cachedDir2).isEqualTo(cachedDir1);
assertThat(cachedDir2.list()).hasLength(1);
assertThat(new File(cachedDir2, "fileInOutputDir")).hasContents("Some text");
}
@Test
public void testCreateFileThenCreateFileInCacheIfAbsent() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
fileCache.createFile(outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
File cachedFile =
fileCache
.createFileInCacheIfAbsent(
inputs,
(aCachedFile) -> {
fail("This statement should not be executed");
writeStringToFile(
"This text should not be written", aCachedFile);
})
.getCachedFile();
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(outputFile).hasContents("Some text");
assertThat(cachedFile).hasContents("Some text");
}
@Test
public void testCreateFileInCacheIfAbsentThenCreateFile() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File cachedFile =
fileCache
.createFileInCacheIfAbsent(
inputs,
(cachedOutputFile) ->
writeStringToFile("Some text", cachedOutputFile))
.getCachedFile();
File outputFile = new File(outputDir, "output");
fileCache.createFile(
outputFile,
inputs,
() -> {
fail("This statement should not be executed");
writeStringToFile("This text should not be written", outputFile);
});
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(outputFile).hasContents("Some text");
assertThat(cachedFile).hasContents("Some text");
}
@Test
public void testInvalidCacheDirectory() throws Exception {
// Use an invalid cache directory, expect that an exception is thrown not when the cache is
// created but when it is used
File invalidCacheDirectory = new File("\0");
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(invalidCacheDirectory);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
try {
fileCache.createFile(
outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
fail("Expected UncheckedIOException");
} catch (UncheckedIOException e) {
assertThat(Throwables.getRootCause(e)).hasMessageThat().isEqualTo("Invalid file path");
}
}
@Test
public void testCacheDirectoryDidNotExist_ExistsAfterCreateFile() throws Exception {
FileUtils.delete(cacheDir);
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
assertThat(fileCache.getCacheDirectory()).doesNotExist();
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
fileCache.createFile(outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
assertThat(fileCache.getCacheDirectory()).exists();
}
@Test
public void testCacheDirectoryDidNotExist_ExistsAfterCreateFileInCacheIfAbsent()
throws Exception {
FileUtils.delete(cacheDir);
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
assertThat(fileCache.getCacheDirectory()).doesNotExist();
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
fileCache.createFileInCacheIfAbsent(
inputs, (outputFile) -> writeStringToFile("Some text", outputFile));
assertThat(fileCache.getCacheDirectory()).exists();
}
@Test
public void testUnusualInput() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST).putString("file", "").build();
File outputFile = new File(outputDir, "output");
fileCache.createFile(outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
assertThat(fileCache.getHits()).isEqualTo(0);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(outputFile).hasContents("Some text");
}
@Test
public void testCreateFile_InvalidOutputFile() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(cacheDir, "output");
try {
fileCache.createFile(outputFile, inputs, () -> {});
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException exception) {
assertThat(exception)
.hasMessageThat()
.isEqualTo(
String.format(
"Output file/directory '%1$s' must not be located"
+ " in the cache directory '%2$s'",
outputFile.getAbsolutePath(),
fileCache.getCacheDirectory().getAbsolutePath()));
}
assertThat(fileCache.getCacheDirectory().list()).isEmpty();
outputFile = cacheDir.getParentFile();
try {
fileCache.createFile(outputFile, inputs, () -> {});
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException exception) {
assertThat(exception)
.hasMessageThat()
.isEqualTo(
String.format(
"Output directory '%1$s' must not contain the cache directory '%2$s'",
outputFile.getAbsolutePath(),
fileCache.getCacheDirectory().getAbsolutePath()));
}
assertThat(fileCache.getCacheDirectory().list()).isEmpty();
outputFile = cacheDir;
try {
fileCache.createFile(outputFile, inputs, () -> {});
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException exception) {
assertThat(exception)
.hasMessageThat()
.isEqualTo(
String.format(
"Output directory must not be the same as the cache directory '%1$s'",
fileCache.getCacheDirectory().getAbsolutePath()));
}
assertThat(fileCache.getCacheDirectory().list()).isEmpty();
}
@Test
public void testCreateFile_OutputFileAlreadyExistsAndIsNotCreated() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputDir1 = new File(outputDir, "dir1");
File outputDir2 = new File(outputDir, "dir2");
FileUtils.mkdirs(outputDir1);
FileUtils.mkdirs(outputDir2);
File fileInOutputDir1 = new File(outputDir1, "output1");
File fileInOutputDir2 = new File(outputDir2, "output2");
Files.touch(fileInOutputDir1);
Files.touch(fileInOutputDir2);
fileCache.createFile(fileInOutputDir1, inputs, () -> {
// The cache should have deleted the existing output file (but not the parent directory)
// before calling this callback
assertThat(fileInOutputDir1).doesNotExist();
assertThat(fileInOutputDir1.getParentFile()).exists();
});
// Since the callback didn't create an output, if the cache is called again, it should
// delete any existing output files (but not their parent directories)
fileCache.createFile(fileInOutputDir2, inputs, () -> {});
assertThat(fileInOutputDir2).doesNotExist();
assertThat(fileInOutputDir2.getParentFile()).exists();
}
@Test
public void testCreateFile_OutputFileDoesNotAlreadyExistAndIsCreated() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputDir1 = new File(outputDir, "dir1");
File outputDir2 = new File(outputDir, "dir2");
File fileInOutputDir1 = new File(outputDir1, "output1");
File fileInOutputDir2 = new File(outputDir2, "output2");
fileCache.createFile(fileInOutputDir1, inputs, () -> {
// The cache should have created the parent directory of the output file (but should not
// have created the output file) before calling this callback
assertThat(fileInOutputDir1).doesNotExist();
assertThat(fileInOutputDir1.getParentFile()).exists();
Files.touch(fileInOutputDir1);
});
// Since the callback created an output, if the cache is called again, it should create new
// output files (together with their parent directories)
fileCache.createFile(fileInOutputDir2, inputs, () -> {});
assertThat(fileInOutputDir2).exists();
}
@Test
public void testCreateFile_OutputFileNotLocked() throws Exception {
FileCache fileCache = FileCache.getInstanceWithMultiProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
fileCache.createFile(outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
// The cache directory should contain 1 cache entry directory and 1 lock file for that
// directory (no lock file for the output file)
assertThat(fileCache.getCacheDirectory().list()).hasLength(2);
}
@Test
public void testCreateFile_FileCreatorIOException() throws IOException {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
try {
fileCache.createFile(
outputFile,
inputs,
() -> {
throw new IOException("Some I/O exception");
});
fail("expected ExecutionException");
} catch (ExecutionException exception) {
assertThat(Throwables.getRootCause(exception)).isInstanceOf(IOException.class);
assertThat(Throwables.getRootCause(exception))
.hasMessageThat()
.isEqualTo("Some I/O exception");
}
assertThat(fileCache.getCacheDirectory().list()).isNotEmpty();
}
@Test
public void testCreateFile_FileCreatorRuntimeException() throws IOException {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
try {
fileCache.createFile(outputFile, inputs, () -> {
throw new RuntimeException("Some runtime exception");
});
fail("expected ExecutionException");
} catch (ExecutionException exception) {
assertThat(Throwables.getRootCause(exception)).isInstanceOf(RuntimeException.class);
assertThat(Throwables.getRootCause(exception))
.hasMessageThat()
.isEqualTo("Some runtime exception");
}
assertThat(fileCache.getCacheDirectory().list()).isNotEmpty();
}
@Test
public void testCreateFile_IOExceptionNotThrownByFileCreator() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
// Use an invalid character in the file name
File outputFile = new File("\0");
try {
fileCache.createFile(outputFile, inputs, () -> {});
fail("expected UncheckedIOException");
} catch (UncheckedIOException e) {
assertThat(Throwables.getRootCause(e)).hasMessageThat().isEqualTo("Invalid file path");
}
assertThat(fileCache.getCacheDirectory().list()).isEmpty();
}
@Test
public void testCreateFileInCacheIfAbsent_FileCreatorIOException() throws IOException {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
try {
fileCache.createFileInCacheIfAbsent(inputs, (outputFile) -> {
throw new IOException("Some I/O exception");
});
fail("expected ExecutionException");
} catch (ExecutionException exception) {
assertThat(Throwables.getRootCause(exception)).isInstanceOf(IOException.class);
assertThat(Throwables.getRootCause(exception))
.hasMessageThat()
.isEqualTo("Some I/O exception");
}
assertThat(fileCache.getCacheDirectory().list()).isNotEmpty();
}
@Test
public void testCreateFileInCacheIfAbsent_FileCreatorRuntimeException() throws IOException {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
try {
fileCache.createFileInCacheIfAbsent(inputs, (outputFile) -> {
throw new RuntimeException("Some runtime exception");
});
fail("expected ExecutionException");
} catch (ExecutionException exception) {
assertThat(Throwables.getRootCause(exception)).isInstanceOf(RuntimeException.class);
assertThat(Throwables.getRootCause(exception))
.hasMessageThat()
.isEqualTo("Some runtime exception");
}
assertThat(fileCache.getCacheDirectory().list()).isNotEmpty();
}
@Test
public void testCreateFileInCacheIfAbsent_IOExceptionNotThrownByFileCreator()
throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
try {
fileCache.createFileInCacheIfAbsent(inputs, (outputFile) -> {
// Delete the cache entry directory to so that the execution will crash later
FileUtils.deletePath(outputFile.getParentFile());
});
fail("expected IOException");
} catch (IOException exception) {
assertThat(Throwables.getRootCause(exception))
.isInstanceOf(FileNotFoundException.class);
}
assertThat(fileCache.getCacheDirectory().list()).isEmpty();
}
@Test
public void testCacheEntryExists() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
// Case 1: Cache entry does not exist
assertThat(fileCache.cacheEntryExists(inputs)).isFalse();
// Case 2: Cache entry exists and is not corrupted
fileCache.createFile(outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
assertThat(fileCache.cacheEntryExists(inputs)).isTrue();
// Case 3: Cache entry exists but is corrupted
File cachedFile = fileCache.getFileInCache(inputs);
File inputsFile = new File(cachedFile.getParent(), "inputs");
FileUtils.delete(inputsFile);
assertThat(fileCache.cacheEntryExists(inputs)).isFalse();
}
@Test
public void testGetFileInCache() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File cachedFile = fileCache.getFileInCache(inputs);
assertThat(FileUtils.isFileInDirectory(cachedFile, fileCache.getCacheDirectory())).isTrue();
File outputFile = new File(outputDir, "output");
fileCache.createFile(outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
assertThat(fileCache.getCacheDirectory().list()).hasLength(1);
assertThat(cachedFile).hasContents("Some text");
File cachedFile2 =
fileCache
.createFileInCacheIfAbsent(
inputs,
(anOutputFile) -> assertThat(anOutputFile).isSameAs(cachedFile))
.getCachedFile();
assertThat(fileCache.getCacheDirectory().list()).hasLength(1);
assertThat(cachedFile2).isEqualTo(cachedFile);
}
@Test
public void testCorruptedCache_InputsFileDoesNotExist() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File outputFile = new File(outputDir, "output");
FileCache.QueryResult result =
fileCache.createFile(
outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
assertThat(result.getQueryEvent()).isEqualTo(FileCache.QueryEvent.MISSED);
assertThat(result.getCauseOfCorruption()).isNull();
assertThat(result.getCachedFile()).isNull();
// Delete the inputs file
File cachedFile = fileCache.getFileInCache(inputs);
File inputsFile = new File(cachedFile.getParent(), "inputs");
FileUtils.delete(inputsFile);
result =
fileCache.createFile(
outputFile, inputs, () -> writeStringToFile("Some text", outputFile));
assertThat(result.getQueryEvent()).isEqualTo(FileCache.QueryEvent.CORRUPTED);
assertNotNull(result.getCauseOfCorruption());
assertThat(result.getCauseOfCorruption().getMessage())
.isEqualTo(
String.format(
"Inputs file '%s' does not exist", inputsFile.getAbsolutePath()));
assertThat(result.getCachedFile()).isNull();
}
@Test
public void testCorruptedCache_InputsFileIsInvalid() throws Exception {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
FileCache.QueryResult result =
fileCache.createFileInCacheIfAbsent(
inputs, (outputFile) -> writeStringToFile("Some text", outputFile));
assertThat(result.getQueryEvent()).isEqualTo(FileCache.QueryEvent.MISSED);
assertThat(result.getCauseOfCorruption()).isNull();
assertThat(result.getCachedFile()).isNotNull();
// Modify the inputs file's contents
File cachedFile = result.getCachedFile();
assertNotNull(cachedFile);
File inputsFile = new File(cachedFile.getParent(), "inputs");
writeStringToFile("Corrupted inputs", inputsFile);
result =
fileCache.createFileInCacheIfAbsent(
inputs, (outputFile) -> writeStringToFile("Some text", outputFile));
assertThat(result.getQueryEvent()).isEqualTo(FileCache.QueryEvent.CORRUPTED);
assertNotNull(result.getCauseOfCorruption());
assertThat(result.getCauseOfCorruption().getMessage())
.contains(
String.format(
"Expected contents '%s' but found '%s'",
inputs.toString(), "Corrupted inputs"));
assertThat(result.getCachedFile()).isNotNull();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void testDeleteOldCacheEntries() throws Exception {
FileCache fileCache = FileCache.getInstanceWithMultiProcessLocking(cacheDir);
FileCache.Inputs inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("input", "foo1")
.build();
FileCache.Inputs inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("input", "foo2")
.build();
FileCache.Inputs inputs3 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("input", "foo3")
.build();
// Make the first cache entry look as if it was created 60 days ago
fileCache.createFileInCacheIfAbsent(inputs1, (outputFile) -> {});
File cacheEntryDir1 = fileCache.getFileInCache(inputs1).getParentFile();
File lockFile1 = SynchronizedFile.getLockFile(cacheEntryDir1);
cacheEntryDir1.setLastModified(System.currentTimeMillis() - Duration.ofDays(60).toMillis());
// Make the second cache entry look as if it was created 30 days ago
fileCache.createFileInCacheIfAbsent(inputs2, (outputFile) -> {});
File cacheEntryDir2 = fileCache.getFileInCache(inputs2).getParentFile();
File lockFile2 = SynchronizedFile.getLockFile(cacheEntryDir2);
cacheEntryDir2.setLastModified(System.currentTimeMillis() - Duration.ofDays(30).toMillis());
// Make the third cache entry without modifying its timestamp
fileCache.createFileInCacheIfAbsent(inputs3, (outputFile) -> {});
File cacheEntryDir3 = fileCache.getFileInCache(inputs3).getParentFile();
File lockFile3 = SynchronizedFile.getLockFile(cacheEntryDir3);
// Create some random directory inside the cache directory and make sure it won't be deleted
File notDeletedDir = new File(fileCache.getCacheDirectory(), "foo");
FileUtils.mkdirs(notDeletedDir);
// The cache directory should now contains 3 cache entry directories, 3 lock files for those
// directories, and 1 not-to-delete directory
assertThat(checkNotNull(cacheDir.listFiles()).length).isEqualTo(7);
// Delete all the cache entries that are older than or as old as 31 days
fileCache.deleteOldCacheEntries(
System.currentTimeMillis() - Duration.ofDays(31).toMillis());
// Check that only the first cache entry and its lock file are deleted
assertThat(checkNotNull(cacheDir.listFiles()).length).isEqualTo(5);
assertThat(cacheEntryDir1).doesNotExist();
assertThat(lockFile1).doesNotExist();
assertThat(fileCache.cacheEntryExists(inputs2)).isTrue();
assertThat(lockFile2).exists();
assertThat(fileCache.cacheEntryExists(inputs3)).isTrue();
assertThat(lockFile3).exists();
assertThat(notDeletedDir).exists();
// Delete all the cache entries that are older than or as old as the second cache entry
fileCache.deleteOldCacheEntries(cacheEntryDir2.lastModified());
// Check that only the third cache entry, its lock file, and the not-to-delete directory are
// kept
assertThat(checkNotNull(cacheDir.listFiles()).length).isEqualTo(3);
assertThat(cacheEntryDir1).doesNotExist();
assertThat(lockFile1).doesNotExist();
assertThat(cacheEntryDir2).doesNotExist();
assertThat(lockFile2).doesNotExist();
assertThat(fileCache.cacheEntryExists(inputs3)).isTrue();
assertThat(lockFile3).exists();
assertThat(notDeletedDir).exists();
// Check that deleting cache entries in an empty or non-existent cache directory does not
// throw an exception
FileUtils.deleteDirectoryContents(cacheDir);
assertThat(checkNotNull(cacheDir.listFiles()).length).isEqualTo(0);
fileCache.deleteOldCacheEntries(System.currentTimeMillis());
assertThat(checkNotNull(cacheDir.listFiles()).length).isEqualTo(0);
FileUtils.deletePath(cacheDir);
assertThat(cacheDir).doesNotExist();
fileCache.deleteOldCacheEntries(System.currentTimeMillis());
assertThat(cacheDir).doesNotExist();
}
@Test
public void testDeleteFileCache() throws IOException {
FileCache fileCache = FileCache.getInstanceWithSingleProcessLocking(cacheDir);
assertThat(fileCache.getCacheDirectory()).exists();
fileCache.delete();
assertThat(fileCache.getCacheDirectory()).doesNotExist();
}
@Test
public void testCreateFile_MultiThreads_SingleProcessLocking_SameInputDifferentOutputs()
throws IOException {
testCreateFile_MultiThreads_SameCacheSameInputDifferentOutputs(
FileCache.getInstanceWithSingleProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFile_MultiThreads_SingleProcessLocking_DifferentInputsDifferentOutputs()
throws IOException {
testCreateFile_MultiThreads_SameCacheDifferentInputsDifferentOutputs(
FileCache.getInstanceWithSingleProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFile_MultiThreads_SingleProcessLocking_DifferentCaches()
throws IOException {
testCreateFile_MultiThreads_DifferentCaches(
FileCache.getInstanceWithSingleProcessLocking(temporaryFolder.newFolder()),
FileCache.getInstanceWithSingleProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFile_MultiThreads_MultiProcessLocking_SameInputDifferentOutputs()
throws IOException {
testCreateFile_MultiThreads_SameCacheSameInputDifferentOutputs(
FileCache.getInstanceWithMultiProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFile_MultiThreads_MultiProcessLocking_DifferentInputsDifferentOutputs()
throws IOException {
testCreateFile_MultiThreads_SameCacheDifferentInputsDifferentOutputs(
FileCache.getInstanceWithMultiProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFile_MultiThreads_MultiProcessLocking_DifferentCaches()
throws IOException {
testCreateFile_MultiThreads_DifferentCaches(
FileCache.getInstanceWithMultiProcessLocking(temporaryFolder.newFolder()),
FileCache.getInstanceWithMultiProcessLocking(temporaryFolder.newFolder()));
}
private void testCreateFile_MultiThreads_SameCacheSameInputDifferentOutputs(
@NonNull FileCache fileCache) throws IOException {
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File[] outputFiles = {new File(outputDir, "output1"), new File(outputDir, "output2")};
String fileContent = "Some text";
ConcurrencyTester<File, Void> tester = new ConcurrencyTester<>();
prepareConcurrencyTestForCreateFile(
tester,
new FileCache[] {fileCache, fileCache},
new FileCache.Inputs[] {inputs, inputs},
outputFiles,
new String[] {fileContent, fileContent});
// Since we use the same input, we expect only one of the actions to be executed
tester.assertThatOnlyOneActionIsExecuted();
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(outputFiles[0]).hasContents(fileContent);
assertThat(outputFiles[1]).hasContents(fileContent);
}
private void testCreateFile_MultiThreads_SameCacheDifferentInputsDifferentOutputs(
@NonNull FileCache fileCache) throws IOException {
FileCache.Inputs[] inputList = {
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file1", "input1")
.build(),
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file2", "input2")
.build(),
};
File[] outputFiles = {new File(outputDir, "output1"), new File(outputDir, "output2")};
String[] fileContents = {"Foo text", "Bar text"};
ConcurrencyTester<File, Void> tester = new ConcurrencyTester<>();
prepareConcurrencyTestForCreateFile(
tester,
new FileCache[] {fileCache, fileCache},
inputList,
outputFiles,
fileContents);
// Since we use different inputs, the actions are allowed to run concurrently
tester.assertThatActionsCanRunConcurrently();
assertThat(fileCache.getHits()).isEqualTo(0);
assertThat(fileCache.getMisses()).isEqualTo(2);
assertThat(outputFiles[0]).hasContents(fileContents[0]);
assertThat(outputFiles[1]).hasContents(fileContents[1]);
}
private void testCreateFile_MultiThreads_DifferentCaches(
@NonNull FileCache fileCache1, @NonNull FileCache fileCache2) throws IOException {
// Use same input different outputs, different caches
FileCache[] fileCaches = {fileCache1, fileCache2};
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
File[] outputFiles = {new File(outputDir, "output1"), new File(outputDir, "output2")};
String[] fileContents = {"Foo text", "Bar text"};
ConcurrencyTester<File, Void> tester = new ConcurrencyTester<>();
prepareConcurrencyTestForCreateFile(
tester,
fileCaches,
new FileCache.Inputs[] {inputs, inputs},
outputFiles,
fileContents);
// Since we use different caches, even though we use the same input, the actions are allowed
// to run concurrently
tester.assertThatActionsCanRunConcurrently();
assertThat(fileCaches[0].getHits()).isEqualTo(0);
assertThat(fileCaches[0].getMisses()).isEqualTo(1);
assertThat(fileCaches[1].getHits()).isEqualTo(0);
assertThat(fileCaches[1].getMisses()).isEqualTo(1);
assertThat(outputFiles[0]).hasContents(fileContents[0]);
assertThat(outputFiles[1]).hasContents(fileContents[1]);
}
/**
* Performs a few steps common to the concurrency tests for {@link FileCache#createFile(File,
* FileCache.Inputs, ExceptionRunnable)}.
*/
private static void prepareConcurrencyTestForCreateFile(
@NonNull ConcurrencyTester<File, Void> tester,
@NonNull FileCache[] fileCaches,
@NonNull FileCache.Inputs[] inputsList,
@NonNull File[] outputFiles,
@NonNull String[] fileContents) {
for (int i = 0; i < fileCaches.length; i++) {
FileCache fileCache = fileCaches[i];
FileCache.Inputs inputs = inputsList[i];
File outputFile = outputFiles[i];
String fileContent = fileContents[i];
Function<File, Void> actionUnderTest =
(File file) -> {
try {
writeStringToFile(fileContent, file);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
};
tester.addMethodInvocationFromNewThread(
(Function<File, Void> anActionUnderTest) -> {
try {
fileCache.createFile(
outputFile, inputs, () -> anActionUnderTest.apply(outputFile));
} catch (ExecutionException | IOException exception) {
throw new RuntimeException(exception);
}
},
actionUnderTest);
}
}
@Test
public void testCreateFileInCacheIfAbsent_MultiThreads_SingleProcessLocking_SameInput()
throws IOException {
testCreateFileInCacheIfAbsent_MultiThreads_SameCacheSameInput(
FileCache.getInstanceWithSingleProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFileInCacheIfAbsent_MultiThreads_SingleProcessLocking_DifferentInputs()
throws IOException {
testCreateFileInCacheIfAbsent_MultiThreads_SameCacheDifferentInputs(
FileCache.getInstanceWithSingleProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFileInCacheIfAbsent_MultiThreads_SingleProcessLocking_DifferentCaches()
throws IOException {
testCreateFileInCacheIfAbsent_MultiThreads_DifferentCaches(
FileCache.getInstanceWithSingleProcessLocking(temporaryFolder.newFolder()),
FileCache.getInstanceWithSingleProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFileInCacheIfAbsent_MultiThreads_MultiProcessLocking_SameInput()
throws IOException {
testCreateFileInCacheIfAbsent_MultiThreads_SameCacheSameInput(
FileCache.getInstanceWithMultiProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFileInCacheIfAbsent_MultiThreads_MultiProcessLocking_DifferentInputs()
throws IOException {
testCreateFileInCacheIfAbsent_MultiThreads_SameCacheDifferentInputs(
FileCache.getInstanceWithMultiProcessLocking(temporaryFolder.newFolder()));
}
@Test
public void testCreateFileInCacheIfAbsent_MultiThreads_MultiProcessLocking_DifferentCaches()
throws IOException {
testCreateFileInCacheIfAbsent_MultiThreads_DifferentCaches(
FileCache.getInstanceWithMultiProcessLocking(temporaryFolder.newFolder()),
FileCache.getInstanceWithMultiProcessLocking(temporaryFolder.newFolder()));
}
private static void testCreateFileInCacheIfAbsent_MultiThreads_SameCacheSameInput(
@NonNull FileCache fileCache) throws IOException {
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
String fileContent = "Some text";
File[] cachedFiles = new File[2];
ConcurrencyTester<File, Void> tester = new ConcurrencyTester<>();
prepareConcurrencyTestForCreateFileInCacheIfAbsent(
tester,
new FileCache[] {fileCache, fileCache},
new FileCache.Inputs[] {inputs, inputs},
new String[] {fileContent, fileContent},
cachedFiles);
// Since we use the same input, we expect only one of the actions to be executed
tester.assertThatOnlyOneActionIsExecuted();
assertThat(fileCache.getHits()).isEqualTo(1);
assertThat(fileCache.getMisses()).isEqualTo(1);
assertThat(cachedFiles[1]).isEqualTo(cachedFiles[0]);
assertThat(cachedFiles[0]).hasContents(fileContent);
}
private static void testCreateFileInCacheIfAbsent_MultiThreads_SameCacheDifferentInputs(
@NonNull FileCache fileCache) throws IOException {
FileCache.Inputs[] inputList = {
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file1", "input1")
.build(),
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file2", "input2")
.build(),
};
String[] fileContents = {"Foo text", "Bar text"};
File[] cachedFiles = new File[2];
ConcurrencyTester<File, Void> tester = new ConcurrencyTester<>();
prepareConcurrencyTestForCreateFileInCacheIfAbsent(
tester,
new FileCache[] {fileCache, fileCache},
inputList,
fileContents,
cachedFiles);
// Since we use different inputs, the actions are allowed to run concurrently
tester.assertThatActionsCanRunConcurrently();
assertThat(fileCache.getHits()).isEqualTo(0);
assertThat(fileCache.getMisses()).isEqualTo(2);
assertThat(cachedFiles[1]).isNotEqualTo(cachedFiles[0]);
assertThat(cachedFiles[0]).hasContents(fileContents[0]);
assertThat(cachedFiles[1]).hasContents(fileContents[1]);
}
private static void testCreateFileInCacheIfAbsent_MultiThreads_DifferentCaches(
@NonNull FileCache fileCache1, @NonNull FileCache fileCache2) throws IOException {
// Use same input, different caches
FileCache[] fileCaches = {fileCache1, fileCache2};
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", "input")
.build();
String[] fileContents = {"Foo text", "Bar text"};
File[] cachedFiles = new File[2];
ConcurrencyTester<File, Void> tester = new ConcurrencyTester<>();
prepareConcurrencyTestForCreateFileInCacheIfAbsent(
tester,
fileCaches,
new FileCache.Inputs[] {inputs, inputs},
fileContents,
cachedFiles);
// Since we use different caches, even though we use the same input, the actions are allowed
// to run concurrently
tester.assertThatActionsCanRunConcurrently();
assertThat(fileCaches[0].getHits()).isEqualTo(0);
assertThat(fileCaches[0].getMisses()).isEqualTo(1);
assertThat(fileCaches[1].getHits()).isEqualTo(0);
assertThat(fileCaches[1].getMisses()).isEqualTo(1);
assertThat(cachedFiles[1]).isNotEqualTo(cachedFiles[0]);
assertThat(cachedFiles[0]).hasContents(fileContents[0]);
assertThat(cachedFiles[1]).hasContents(fileContents[1]);
}
/**
* Performs a few steps common to the concurrency tests for {@link
* FileCache#createFileInCacheIfAbsent(FileCache.Inputs, ExceptionConsumer)}.
*/
@SuppressWarnings("ReturnValueIgnored") // uses dubious type Function<File, Void>
private static void prepareConcurrencyTestForCreateFileInCacheIfAbsent(
@NonNull ConcurrencyTester<File, Void> tester,
@NonNull FileCache[] fileCaches,
@NonNull FileCache.Inputs[] inputsList,
@NonNull String[] fileContents,
@NonNull File[] cachedFiles) {
for (int i = 0; i < fileCaches.length; i++) {
FileCache fileCache = fileCaches[i];
FileCache.Inputs inputs = inputsList[i];
String fileContent = fileContents[i];
final int idx = i;
Function<File, Void> actionUnderTest =
(File file) -> {
try {
writeStringToFile(fileContent, file);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
};
tester.addMethodInvocationFromNewThread(
(Function<File, Void> anActionUnderTest) -> {
try {
cachedFiles[idx] =
fileCache
.createFileInCacheIfAbsent(
inputs, anActionUnderTest::apply)
.getCachedFile();
} catch (ExecutionException | IOException exception) {
throw new RuntimeException(exception);
}
},
actionUnderTest);
}
}
@Test
public void testCacheInputsGetKey() throws IOException {
// Test realistic example
File inputFile =
new File(
"/Users/foo/Android/Sdk/extras/android/m2repository/com/android/support/"
+ "support-annotations/23.3.0/support-annotations-23.3.0.jar");
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("file", inputFile.getPath())
.putString(
"buildToolsRevision", Revision.parseRevision("23.0.3").toString())
.putBoolean("jumboMode", true)
.putBoolean("optimize", false)
.putBoolean("multiDex", true)
.putString("classpath", "foo")
.putLong("cacheVersion", 1)
.build();
assertThat(inputs.toString())
.isEqualTo(
Joiner.on(System.lineSeparator())
.join(
"COMMAND=TEST",
"file=" + inputFile.getPath(),
"buildToolsRevision=23.0.3",
"jumboMode=true",
"optimize=false",
"multiDex=true",
"classpath=foo",
"cacheVersion=1"));
assertThat(inputs.getKey())
.isEqualTo(Hashing.sha256().hashUnencodedChars(inputs.toString()).toString());
// Test no input parameters
try {
new FileCache.Inputs.Builder(FileCache.Command.TEST).build();
fail("expected IllegalStateException");
} catch (IllegalStateException exception) {
assertThat(exception).hasMessageThat().isEqualTo("Inputs must not be empty.");
}
// Test input parameters with duplicate names
try {
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("arg", "foo")
.putBoolean("arg", false)
.build();
fail("expected IllegalStateException");
} catch (IllegalStateException exception) {
assertThat(exception).hasMessageThat().isEqualTo("Input parameter arg already exists");
}
// Test input parameters with empty strings
inputs = new FileCache.Inputs.Builder(FileCache.Command.TEST).putString("arg", "").build();
assertThat(inputs.toString())
.isEqualTo(Joiner.on(System.lineSeparator()).join("COMMAND=TEST", "arg="));
assertThat(inputs.getKey())
.isEqualTo(Hashing.sha256().hashUnencodedChars(inputs.toString()).toString());
// Test comparing inputs with different sizes
FileCache.Inputs inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putBoolean("arg1", true)
.putBoolean("arg2", true)
.build();
FileCache.Inputs inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putBoolean("arg1", true)
.putBoolean("arg2", true)
.putBoolean("arg3", true)
.build();
assertThat(inputs1.toString()).isNotEqualTo(inputs2.toString());
assertThat(inputs1.getKey()).isNotEqualTo(inputs2.getKey());
// Test comparing inputs with different names
inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putBoolean("arg1", true)
.putBoolean("arg2", true)
.build();
inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putBoolean("arg1", true)
.putBoolean("arg3", true)
.build();
assertThat(inputs1.toString()).isNotEqualTo(inputs2.toString());
assertThat(inputs1.getKey()).isNotEqualTo(inputs2.getKey());
// Test comparing inputs with different orders
inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("arg1", "foo")
.putBoolean("arg2", false)
.build();
inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putBoolean("arg2", false)
.putString("arg1", "foo")
.build();
assertThat(inputs1.toString()).isNotEqualTo(inputs2.toString());
assertThat(inputs1.getKey()).isNotEqualTo(inputs2.getKey());
// Test comparing inputs with different values
inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putBoolean("arg1", true)
.putBoolean("arg2", true)
.build();
inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putBoolean("arg1", true)
.putBoolean("arg2", false)
.build();
assertThat(inputs1.toString()).isNotEqualTo(inputs2.toString());
assertThat(inputs1.getKey()).isNotEqualTo(inputs2.getKey());
// Test comparing inputs with same size, names, order, and values
inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("arg1", "foo")
.putBoolean("arg2", false)
.build();
inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putString("arg1", "foo")
.putBoolean("arg2", false)
.build();
assertThat(inputs1.toString()).isEqualTo(inputs2.toString());
assertThat(inputs1.getKey()).isEqualTo(inputs2.getKey());
}
@Test
public void testCacheInputsFileAsInput() throws IOException {
// Test identifying an input file with FileProperties.HASH
File inputFile = temporaryFolder.newFile("inputFile");
writeStringToFile("Some text", inputFile);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putFile("fileHash", inputFile, FileCache.FileProperties.HASH)
.build();
assertThat(inputs.toString())
.isEqualTo(
Joiner.on(System.lineSeparator())
.join(
"COMMAND=TEST",
"fileHash="
+ Hashing.sha256()
.hashBytes("Some text".getBytes())));
// Test identifying an input file with FileProperties.PATH_HASH
inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putFile("file", inputFile, FileCache.FileProperties.PATH_HASH)
.build();
assertThat(inputs.toString())
.isEqualTo(
Joiner.on(System.lineSeparator())
.join(
"COMMAND=TEST",
"file.path=" + inputFile.getPath(),
"file.hash="
+ Hashing.sha256()
.hashBytes("Some text".getBytes())));
// Test identifying an input file with FileProperties.PATH_SIZE_TIMESTAMP
inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putFile("file", inputFile, FileCache.FileProperties.PATH_SIZE_TIMESTAMP)
.build();
assertThat(inputs.toString())
.isEqualTo(
Joiner.on(System.lineSeparator())
.join(
"COMMAND=TEST",
"file.path=" + inputFile.getPath(),
"file.size=" + inputFile.length(),
"file.timestamp=" + inputFile.lastModified()));
// Test input files with same hash, different paths
File fooFile = temporaryFolder.newFile("fooFile");
File barFile = temporaryFolder.newFile("barFile");
writeStringToFile("Some text", fooFile);
writeStringToFile("Some text", barFile);
FileCache.Inputs inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putFile("fileHash", fooFile, FileCache.FileProperties.HASH)
.build();
FileCache.Inputs inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putFile("fileHash", barFile, FileCache.FileProperties.HASH)
.build();
assertThat(inputs1.getKey()).isEqualTo(inputs2.getKey());
// Test input files with different hashes, same path
inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putFile("fileHash", fooFile, FileCache.FileProperties.HASH)
.build();
writeStringToFile("Updated text", fooFile);
inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putFile("fileHash", fooFile, FileCache.FileProperties.HASH)
.build();
assertThat(inputs1.getKey()).isNotEqualTo(inputs2.getKey());
}
@Test
public void testGetFileHash() throws IOException {
// Test file with some contents
File inputFile = temporaryFolder.newFile();
writeStringToFile("Some text", inputFile);
assertThat(FileCache.Inputs.Builder.getFileHash(inputFile)).hasLength(64);
// Test file with empty contents
File emptyFile = temporaryFolder.newFile();
assertThat(FileCache.Inputs.Builder.getFileHash(emptyFile))
.isEqualTo(Hashing.sha256().hashUnencodedChars("").toString());
/*
* Test that the hash computation is based on the file's contents
*/
// Update the file's contents, the hash must change
writeStringToFile("Foo text", inputFile);
String hash1 = FileCache.Inputs.Builder.getFileHash(inputFile);
writeStringToFile("Bar text", inputFile);
String hash2 = FileCache.Inputs.Builder.getFileHash(inputFile);
assertThat(hash1).isNotEqualTo(hash2);
// Two files having the same contents must have the same hash. This test also proves that
// the hash computation does not consider the path or name of the given file.
File fooFile = temporaryFolder.newFile("fooFile");
File barFile = temporaryFolder.newFile("barFile");
writeStringToFile("Some text", fooFile);
writeStringToFile("Some text", barFile);
assertThat(FileCache.Inputs.Builder.getFileHash(fooFile))
.isEqualTo(FileCache.Inputs.Builder.getFileHash(barFile));
}
@Test
public void testCacheInputsDirectoryAsInput() throws IOException {
// Test identifying an input directory with DirectoryProperties.HASH
File inputDir = temporaryFolder.newFolder("inputDir");
writeSampleContentsToDirectory(inputDir);
FileCache.Inputs inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putDirectory("directoryHash", inputDir, FileCache.DirectoryProperties.HASH)
.build();
assertThat(inputs.toString())
.contains(Joiner.on(System.lineSeparator()).join("COMMAND=TEST", "directoryHash="));
// Test identifying an input directory with DirectoryProperties.PATH_HASH
inputs =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putDirectory(
"directory", inputDir, FileCache.DirectoryProperties.PATH_HASH)
.build();
assertThat(inputs.toString())
.contains(
Joiner.on(System.lineSeparator())
.join(
"COMMAND=TEST",
"directory.path=" + inputDir.getPath(),
"directory.hash="));
// Test input directories with same hash, different paths
File fooDir = temporaryFolder.newFolder("fooDir");
File barDir = temporaryFolder.newFolder("barDir");
writeSampleContentsToDirectory(fooDir);
writeSampleContentsToDirectory(barDir);
FileCache.Inputs inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putDirectory("directoryHash", fooDir, FileCache.DirectoryProperties.HASH)
.build();
FileCache.Inputs inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putDirectory("directoryHash", barDir, FileCache.DirectoryProperties.HASH)
.build();
assertThat(inputs1.getKey()).isEqualTo(inputs2.getKey());
// Test input directories with different hashes, same path
inputs1 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putDirectory("directoryHash", fooDir, FileCache.DirectoryProperties.HASH)
.build();
writeStringToFile("Some text", new File(fooDir, "newFile.txt"));
inputs2 =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putDirectory("directoryHash", fooDir, FileCache.DirectoryProperties.HASH)
.build();
assertThat(inputs1.getKey()).isNotEqualTo(inputs2.getKey());
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void testGetDirectoryHash() throws Exception {
// Test directory with some contents
File inputDir = temporaryFolder.newFolder();
writeSampleContentsToDirectory(inputDir);
assertThat(FileCache.Inputs.Builder.getDirectoryHash(inputDir)).hasLength(64);
// Test directory with empty contents
File emptyDir = temporaryFolder.newFile();
assertThat(FileCache.Inputs.Builder.getFileHash(emptyDir))
.isEqualTo(Hashing.sha256().hashUnencodedChars("").toString());
/*
* Test that the hash computation is based on the directory's contents
*/
// Add a file in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
String hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
writeStringToFile("Some text", new File(new File(inputDir, "foo"), "newFile.txt"));
String hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Update a file in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
writeStringToFile("Updated text", new File(new File(inputDir, "foo"), "foo1.txt"));
hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Delete a file in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
FileUtils.delete(new File(new File(inputDir, "foo"), "foo1.txt"));
hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Rename a file in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
new File(new File(inputDir, "foo"), "foo1.txt")
.renameTo(new File(new File(inputDir, "foo"), "foo3.txt"));
hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Move a file in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
new File(new File(inputDir, "foo"), "foo1.txt")
.renameTo(new File(new File(inputDir, "bar"), "foo1.txt"));
hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Add a subdirectory in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
FileUtils.mkdirs(new File(new File(inputDir, "foo"), "newDir"));
hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Delete a subdirectory in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
FileUtils.delete(new File(inputDir, "bar"));
hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Rename a subdirectory in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
new File(inputDir, "foo").renameTo(new File(inputDir, "foo2"));
hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Move a subdirectory in the directory, the hash must change
writeSampleContentsToDirectory(inputDir);
hash1 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
new File(inputDir, "foo").renameTo(new File(new File(inputDir, "bar"), "foo"));
hash2 = FileCache.Inputs.Builder.getDirectoryHash(inputDir);
assertThat(hash1).isNotEqualTo(hash2);
// Two directories having the same contents must have the same hash. This test also proves
// that the hash computation does not consider the path or name of the given directory.
File fooDir = temporaryFolder.newFolder("fooDir");
File barDir = temporaryFolder.newFolder("barDir");
writeSampleContentsToDirectory(fooDir);
writeSampleContentsToDirectory(barDir);
assertThat(FileCache.Inputs.Builder.getDirectoryHash(fooDir))
.isEqualTo(FileCache.Inputs.Builder.getDirectoryHash(barDir));
}
@Test
public void testCacheSession() throws Exception {
FileCache.CacheSession session = FileCache.newSession();
FileCache.CacheSession otherSession = FileCache.newSession();
// Test file with some contents
File inputFile = temporaryFolder.newFile();
writeStringToFile("Some text", inputFile);
String fileInitialKey =
new FileCache.Inputs.Builder(FileCache.Command.TEST, session)
.putFile("file", inputFile, FileCache.FileProperties.HASH)
.build()
.getKey();
// Change file content
writeStringToFile("Some different text", inputFile);
// Take key again with different sessions.
String changedFileKeyWithoutSession =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putFile("file", inputFile, FileCache.FileProperties.HASH)
.build()
.getKey();
String changedFileKeyWithSession =
new FileCache.Inputs.Builder(FileCache.Command.TEST, session)
.putFile("file", inputFile, FileCache.FileProperties.HASH)
.build()
.getKey();
String changedFileKeyWithOtherSession =
new FileCache.Inputs.Builder(FileCache.Command.TEST, otherSession)
.putFile("file", inputFile, FileCache.FileProperties.HASH)
.build()
.getKey();
// File was changed so key must change unless we reuse the same session.
assertThat(changedFileKeyWithoutSession).isNotEqualTo(fileInitialKey);
assertThat(changedFileKeyWithSession).isEqualTo(fileInitialKey);
assertThat(changedFileKeyWithOtherSession).isNotEqualTo(fileInitialKey);
// reset sessions
session = FileCache.newSession();
otherSession = FileCache.newSession();
// Test directory with some contents
File inputDir = temporaryFolder.newFolder();
writeSampleContentsToDirectory(inputDir);
String dirInitialKey =
new FileCache.Inputs.Builder(FileCache.Command.TEST, session)
.putDirectory("dir", inputDir, FileCache.DirectoryProperties.HASH)
.build()
.getKey();
// change directory structure
java.nio.file.Files.createDirectory(new File(inputDir, "additionalDirectory").toPath());
String changedDirKeyWithoutSession =
new FileCache.Inputs.Builder(FileCache.Command.TEST)
.putDirectory("dir", inputDir, FileCache.DirectoryProperties.HASH)
.build()
.getKey();
String changedDirKeyWithSession =
new FileCache.Inputs.Builder(FileCache.Command.TEST, session)
.putDirectory("dir", inputDir, FileCache.DirectoryProperties.HASH)
.build()
.getKey();
String changedDirKeyWithOtherSession =
new FileCache.Inputs.Builder(FileCache.Command.TEST, otherSession)
.putDirectory("dir", inputDir, FileCache.DirectoryProperties.HASH)
.build()
.getKey();
// Directory content was changed so key must change unless we reuse the same session.
assertThat(changedDirKeyWithoutSession).isNotEqualTo(dirInitialKey);
assertThat(changedDirKeyWithSession).isEqualTo(dirInitialKey);
assertThat(changedDirKeyWithOtherSession).isNotEqualTo(dirInitialKey);
}
private static void writeStringToFile(@NonNull String content, @NonNull File file)
throws IOException {
Files.asCharSink(file, StandardCharsets.UTF_8).write(content);
}
private static void writeSampleContentsToDirectory(@NonNull File directory) throws IOException {
// Create a sample directory with the following structure:
// |- directory
// |- foo
// |- foo1.txt
// |- foo2.txt
// |- bar (empty directory)
// |- baz.txt
File fooDir = new File(directory, "foo");
File foo1File = new File(fooDir, "foo1.txt");
File foo2File = new File(fooDir, "foo2.txt");
File barDir = new File(directory, "bar");
File bazFile = new File(directory, "baz.txt");
FileUtils.deletePath(directory);
FileUtils.mkdirs(fooDir);
FileUtils.mkdirs(barDir);
writeStringToFile("foo1", foo1File);
writeStringToFile("foo2", foo2File);
writeStringToFile("baz", bazFile);
}
}
|
package com.pizzaiolo.authorization.constraints;
import javax.validation.Constraint;
import javax.validation.Payload;
import com.pizzaiolo.authorization.constraints.validators.IsUniqueValidator;
import com.pizzaiolo.authorization.constraints.validators.IsUniqueValidator.UpdateAction;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Constraint(validatedBy = IsUniqueValidator.class)
@Target({
TYPE, FIELD,
ANNOTATION_TYPE
})
@Retention(RUNTIME)
@Documented
public @interface IsUnique {
String message() default "{constraints.is-unique}";
Class <?> [] groups() default {};
Class <? extends Payload> [] payload() default {};
String property();
String repository();
UpdateAction action() default UpdateAction.INSERT;
@Target({
TYPE, FIELD,
ANNOTATION_TYPE
})
@Retention(RUNTIME)
@Documented
@interface List {
IsUnique[] value();
}
}
|
package org.jspringbot.keyword.selenium.web;
import org.jspringbot.KeywordInfo;
import org.jspringbot.keyword.selenium.AbstractSeleniumKeyword;
import org.springframework.stereotype.Component;
@Component
@KeywordInfo(
name = "Is Text Present",
parameters = {"text"},
description = "classpath:desc/IsTextPresent.txt"
)
public class IsTextPresent extends AbstractSeleniumKeyword {
public Object execute(Object[] params) {
return helper.isTextPresent(String.valueOf(params[0]));
}
}
|
package org.bougainvillea.spring5.jdbc.dao;
import org.bougainvillea.spring5.jdbc.po.User;
import java.util.List;
/**
* @author renqiankun
*/
public interface UserDao {
int insert(User user);
int[] batchInsert(List<User> userList);
int update(int id,User user);
int[] batchUpdate(int id,List<User> userList);
User select(int id);
User select2(int id);
List<User> selectList(int id);
int delete(int id);
int[] batchDelete(int[] id);
/**
*事务
*/
void reduceAge(int id,int num);
void addAge(int id,int num);
}
|
/*
* 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.carbondata.processing.loading.parser;
/**
* Parse the data according to implementation, The implementation classes can be struct, array or
* map datatypes.
* It remains thread safe as the state of implementation class should not change while
* calling @{@link GenericParser#parse(Object)} method
*/
public interface GenericParser<E> {
/**
* Parse the data as per the delimiter
* @param data
* @return
*/
E parse(Object data);
}
|
package com.xiaobudian.huastools.ui.activity;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.xiaobudian.huastools.AppComponent;
import com.xiaobudian.huastools.R;
import com.xiaobudian.huastools.data.SunshineApi;
import com.xiaobudian.huastools.databinding.ActivityReplyDetailsBinding;
import com.xiaobudian.huastools.model.ReplyDetail;
import com.xiaobudian.huastools.ui.component.DaggerSunshineComponent;
import com.xiaobudian.huastools.ui.module.SunshineModule;
import com.xiaobudian.huastools.ui.presenter.ReplyDetailPresenter;
import com.xiaobudian.huastools.ui.view.ReplyDetailView;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by 小不点 on 2016/4/24.
*/
public class ReplyDetailActivity extends BaseActivity implements ReplyDetailView {
@Inject
SunshineApi mSunshineApi;
@Bind(R.id.tv_title)
TextView mTvTitle;
@Bind(R.id.toolbar)
Toolbar mToolbar;
@Bind(R.id.pb_loading)
ProgressBar mPbLoading;
@Bind(R.id.tv_result)
TextView mTvResult;
@Bind(R.id.b_retry)
Button mBRetry;
@Bind(R.id.ll_view)
LinearLayout mLlView;
private ReplyDetailPresenter mReplyDetailPresenter;
private ActivityReplyDetailsBinding activityReplyDetailsBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityReplyDetailsBinding = DataBindingUtil.setContentView(this, R.layout.activity_reply_details);
ButterKnife.bind(this);
hideView();
mReplyDetailPresenter = new ReplyDetailPresenter(mSunshineApi, this);
String url = getIntent().getStringExtra("url");
mReplyDetailPresenter.loadData(url);
}
@Override
protected void setupActivityComponent(AppComponent appComponent) {
DaggerSunshineComponent.builder()
.appComponent(appComponent)
.sunshineModule(new SunshineModule(this))
.build()
.inject(this);
}
@Override
public void showView() {
mLlView.setVisibility(View.VISIBLE);
}
@Override
public void hideView() {
mLlView.setVisibility(View.GONE);
}
@Override
public void initView(ReplyDetail replyDetail) {
activityReplyDetailsBinding.setReplyDetail(replyDetail);
showView();
}
@Override
public void showLoading() {
mPbLoading.setVisibility(View.VISIBLE);
}
@Override
public void hideLoading() {
mPbLoading.setVisibility(View.GONE);
}
@Override
public void showRetry() {
mTvResult.setVisibility(View.VISIBLE);
mBRetry.setVisibility(View.VISIBLE);
}
@Override
public void hideRetry() {
mTvResult.setVisibility(View.GONE);
mBRetry.setVisibility(View.GONE);
}
@Override
public void showError(String message) {
}
@Override
public Context context() {
return this;
}
}
|
package com.dmall.component.elasticsearch;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.dmall.common.constants.Constants;
import com.dmall.common.dto.ResponsePage;
import com.dmall.common.enums.component.ESErrorEnum;
import com.dmall.common.model.exception.ComponentException;
import com.dmall.common.util.FieldUtil;
import com.dmall.common.util.JsonUtil;
import com.dmall.component.elasticsearch.entity.*;
import com.google.common.collect.Lists;
import io.searchbox.client.JestClient;
import io.searchbox.core.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @description: es公共操作类
* @author: created by hang.yu on 2019/11/6 22:56
*/
@Slf4j
public class ESDao<T> {
@Autowired
private JestClient jestClient;
@Autowired
private DMallElasticSearchProperties esProperties;
/**
* 新增或更新文档
*/
public void saveOrUpdate(T t) {
Long id = getIdValue(t);
saveOrUpdate(t, esProperties.getIndexName(), esProperties.getTypeName(), id);
}
/**
* 新增或更新文档
*/
public void saveOrUpdate(T t, String indexName, String typeName) {
Long id = getIdValue(t);
saveOrUpdate(t, indexName, typeName, id);
}
/**
* 新增或更新文档
*
* @param t 文档对象
* @param indexName 索引名称
* @param typeName 类型名称
* @param id id
*/
public void saveOrUpdate(T t, String indexName, String typeName, Long id) {
if (t == null) {
throw new ComponentException(ESErrorEnum.STORE_OBJECT_NULL);
}
basicCheck(indexName, typeName, id);
try {
Index index = new Index.Builder(t).index(indexName).type(typeName).id(String.valueOf(id)).build();
DocumentResult execute = jestClient.execute(index);
if (!execute.isSucceeded()) {
log.error("ESDao saveOrUpdate fail,{}", JsonUtil.toJson(execute));
throw new ComponentException(ESErrorEnum.BASIC_ERROR);
}
log.info("ESDao saveOrUpdate successful,{} ", id);
} catch (IOException e) {
log.error("ESDao saveOrUpdate error,", e);
throw new ComponentException(ESErrorEnum.BASIC_ERROR);
}
}
/**
* 删除文档
*
* @param id id
*/
public void delete(Long id) {
delete(esProperties.getIndexName(), esProperties.getTypeName(), id);
}
/**
* 删除文档
*
* @param indexName 索引名称
* @param typeName 类型名称
* @param id id
*/
public void delete(String indexName, String typeName, Long id) {
basicCheck(indexName, typeName, id);
Delete index = new Delete.Builder(String.valueOf(id)).index(indexName).type(typeName).build();
try {
log.info("delete from es, index:{},type:{},id:{}", indexName, typeName, id);
DocumentResult execute = jestClient.execute(index);
if (!execute.isSucceeded()) {
log.error("ESDao delete fail,{}", JsonUtil.toJson(execute));
throw new ComponentException(ESErrorEnum.BASIC_ERROR);
}
} catch (IOException e) {
log.error("ESDao delete error,", e);
throw new ComponentException(ESErrorEnum.BASIC_ERROR);
}
}
/**
* 通过search对象搜索
*/
public ResponsePage<T> search(ESSearch<T> esSearch) {
if (esSearch == null) {
throw new ComponentException(ESErrorEnum.NO_SEARCH);
}
checkEs(esSearch.getIndexName(), esSearch.getTypeName());
return search(esSearch.getIndexName(), esSearch.getTypeName(), esSearch.getSearchFields(),
esSearch.getFilterFields(),
esSearch.getRangeField(), esSearch.getHighLightField(), esSearch.getEsPage(), esSearch.getSortField(),
esSearch.getClazz());
}
/**
* 搜索的核心方法
*
* @param indexName 索引名称
* @param typeName 类型名称
* @param searchFields 查询的字段
* @param filterFields 过滤的字段
* @param highLightField 高亮的字段
* @param rangeField 范围过滤
* @param esPage 分页对象
* @param sortField 排序字段
* @param clazz 查询的返回对象
*/
private ResponsePage<T> search(String indexName, String typeName, List<SearchField> searchFields,
List<FilterField> filterFields,
RangeField rangeField, String highLightField, ESPage esPage, SortField sortField, Class<T> clazz) {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 布尔过滤器
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 过滤
if (!CollectionUtils.isEmpty(filterFields)) {
filterFields.forEach(filterField -> {
QueryBuilder termQueryBuilder =
new TermsQueryBuilder(filterField.getFieldName(), filterField.getFieldValues());
// 多个过滤条件是且的关系 用 must
boolQueryBuilder.filter(termQueryBuilder);
});
}
// 关键词搜索
if (!CollectionUtils.isEmpty(searchFields)) {
searchFields.forEach(searchField -> {
MatchQueryBuilder matchQueryBuilder =
new MatchQueryBuilder(searchField.getFieldName(), searchField.getFieldValue());
// 多个搜索用或的关系 should
boolQueryBuilder.should(matchQueryBuilder);
});
}
// 范围
if (rangeField != null) {
RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder(rangeField.getFieldName());
rangeQueryBuilder.gte(rangeField.getStartValue());
rangeQueryBuilder.lte(rangeField.getEndValue());
boolQueryBuilder.must(rangeQueryBuilder);
}
searchSourceBuilder.query(boolQueryBuilder);
// 设置高亮
if (highLightField != null) {
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field(highLightField);
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
}
// 设置分页
if (esPage != null) {
searchSourceBuilder.from(esPage.getFrom());
searchSourceBuilder.size(esPage.getSize());
}
// 排序
if (sortField != null) {
searchSourceBuilder.sort(sortField.getFieldName(), sortField.getSortOrder());
}
String dslStr = searchSourceBuilder.toString();
log.info("query dsl:\n{}", dslStr);
Search search = new Search.Builder(dslStr).addIndex(indexName).addType(typeName).build();
SearchResult execute = null;
try {
execute = jestClient.execute(search);
if (!execute.isSucceeded()) {
log.error("ESDao search fail,{}", JsonUtil.toJson(execute));
throw new ComponentException(ESErrorEnum.BASIC_ERROR);
}
} catch (IOException e) {
log.error("ESDao search error,", e);
throw new ComponentException(ESErrorEnum.BASIC_ERROR);
}
List<SearchResult.Hit<T, Void>> hits = execute.getHits(clazz);
List<T> result = Lists.newArrayList();
for (SearchResult.Hit<T, Void> hit : hits) {
T source = hit.source;
Map<String, List<String>> highlight = hit.highlight;
if (MapUtil.isNotEmpty(highlight)) {
highlight.forEach((k, v) -> {
ReflectUtil.setFieldValue(source, k, v.get(0));
});
}
result.add(source);
}
return new ResponsePage(execute.getTotal(), result);
}
/**
* 基本校验
*/
private void basicCheck(String indexName, String typeName, Long id) {
checkEs(indexName, typeName);
if (id == null) {
throw new ComponentException(ESErrorEnum.NO_ID);
}
}
/**
* 索引名和类型名不能为空
*/
private void checkEs(String indexName, String typeName) {
if (StrUtil.isBlank(indexName)) {
throw new ComponentException(ESErrorEnum.NO_INDEX_NAME);
}
if (StrUtil.isBlank(typeName)) {
throw new ComponentException(ESErrorEnum.NO_TYPE_NAME);
}
}
/**
* 获取对象的id值
*/
private Long getIdValue(Object result) {
EsId esId = FieldUtil.findAnnotationField(result, EsId.class);
Long id = null;
if (esId != null) {
String value = esId.value();
id = (Long)ReflectUtil.getFieldValue(result, value);
} else {
id = (Long)ReflectUtil.getFieldValue(result, Constants.ID);
}
return id;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.