text
stringlengths 7
1.01M
|
|---|
/*
Copyright 2022 WeAreFrank!
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 nl.nn.adapterframework.statistics;
public interface IBasics<S> extends ItemList {
public static final int NUM_BASIC_ITEMS=6;
public S takeSnapshot();
public void addValue(long value);
public void checkMinMax(long value);
public long getCount();
public long getIntervalCount(S mark);
public long getIntervalMin(S mark);
public long getIntervalMax(S mark);
public void updateIntervalMinMax(S mark, long value);
public long getMax();
public long getMin();
public long getSum();
public long getSumOfSquares();
public long getIntervalSum(S mark);
public long getIntervalSumOfSquares(S mark);
public double getAverage();
public double getIntervalAverage(S mark);
public double getVariance();
public double getIntervalVariance(S mark);
public double getStdDev();
}
|
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
*
* @author Rob Winch
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class AuthenticationPrincipalArgumentResolverTests {
@Autowired
WebApplicationContext wac;
@After
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void authenticationPrincipalExpressionWhenBeanExpressionSuppliedThenBeanUsed() throws Exception {
User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
SecurityContextHolder.setContext(context);
MockMvc mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.build();
mockMvc.perform(get("/users/self"))
.andExpect(status().isOk())
.andExpect(content().string("extracted-user"));
}
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication();
}
@Bean
public UsernameExtractor usernameExtractor() {
return new UsernameExtractor();
}
@RestController
static class UserController {
@GetMapping("/users/self")
public String usersSelf(@AuthenticationPrincipal(expression = "@usernameExtractor.extract(#this)") String userName) {
return userName;
}
}
}
static class UsernameExtractor {
public String extract(User u) {
return "extracted-" + u.getUsername();
}
}
}
|
/*
* iur-ade-citygml4j - i-Urban Revitalization ADE module for citygml4j
* https://github.com/citygml4j/iur-ade-citygml4j
*
* iur-ade-citygml4j is part of the citygml4j project
*
* Copyright 2019-2021 Virtual City Systems
* https://vc.systems/
*
* 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.citygml4j.ade.iur.model.urf;
import org.citygml4j.builder.copy.CopyBuilder;
public class Administration extends UrbanFunction {
@Override
public Object copy(CopyBuilder copyBuilder) {
return copyTo(new Administration(), copyBuilder);
}
}
|
package com.oneandone.snmpman.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.oneandone.snmpman.Snmpman;
import com.oneandone.snmpman.SnmpmanAgent;
import com.oneandone.snmpman.configuration.modifier.Modifier;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/** Representation of the configuration for a {@link SnmpmanAgent}. */
@Slf4j
@ToString(exclude = "community") @EqualsAndHashCode
public class AgentConfiguration {
/** The device factory. */
private static final DeviceFactory DEVICE_FACTORY = new DeviceFactory();
/**
* Returns the name of the agent.
* <br>
* If the {@code name} wasn't set on construction, the name will be defined by the {@link #address}.
*
* @return the name of the agent
*/
@Getter private final String name;
/**
* Returns the address of the agent.
*
* @return the address of the agent
*/
@Getter private final Address address; // e.g. 127.0.0.1/8080
/** The device configuration file path. */
private final File deviceConfiguration;
/**
* Returns the {@link Device} representation for the agent.
* <br>
* Will be set to {@link DeviceFactory#DEFAULT_DEVICE} by default.
*
* @return the device representation for the agent
*/
@Getter(lazy=true) private final Device device = initializeDevice(); // e.g. cisco
/**
* Returns the base walk file (e.g. dump of SNMP walks) for the agent.
*
* @return the base walk file for the agent
*/
@Getter private final File walk; // real walk: /opt/snmpman/...
/**
* Returns the community for the agent.
* <br>
* The community is {@code public} by default.
*
* @return the community for the agent
*/
@Getter private final String community; // e.g. 'public'
/**
* The device factory creates all {@link Device} representations.
* <br>
* It is required to instantiate the representations only one time application-wide.
*/
// TODO each Snmpman instance should have its own device factory instance
public static class DeviceFactory {
/** The default device which will be returned if no configuration specified. */
public static final Device DEFAULT_DEVICE = new Device("default", new Modifier[0], null);
/** The map of all available devices. */
private final Map<File, Device> devices = new HashMap<>();
/**
* Returns the device representation for the specified {@code path}.
* <br>
* If the {@code path} is {@code null}, or the parsing of the configuration failed, the {@link #DEFAULT_DEVICE} will be returned instead.
*
* @param path the path of the device configuration
* @return the {@link Device} representation for the specified configuration in {@code path}
*/
public Device getDevice(final File path) {
if (path == null) {
return DEFAULT_DEVICE;
}
if (devices.containsKey(path)) {
return devices.get(path);
} else {
try {
final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
final Device device = mapper.readValue(path, Device.class);
devices.put(path, device);
return device;
} catch (final IOException e) {
log.error("could not load device in path \"" + path.getAbsolutePath() + "\"", e);
return DEFAULT_DEVICE;
}
}
}
}
/**
* Constructs a new agent configuration.
* <br>
* The list of agent configurations will be parsed from within {@link Snmpman}.
*
* @param name the name of the agent or {@code null} to set the address as the name
* @param deviceConfiguration the device configuration or {@code null} will set it to
* {@link DeviceFactory#DEFAULT_DEVICE}
* @param walk the base walk file (e.g. dump of SNMP walks)
* @param ip the IP the agent should bind to
* @param port the port of the agent
* @param community the community of the agent or {@code null} will set it to {@code public}
*/
public AgentConfiguration(@JsonProperty(value = "name", required = false) final String name,
@JsonProperty(value = "device", required = false) final File deviceConfiguration,
@JsonProperty(value = "walk", required = true) final File walk,
@JsonProperty(value = "ip", required = true) final String ip,
@JsonProperty(value = "port", required = true) final int port,
@JsonProperty(value = "community", required = false) final String community) {
this.name = Optional.ofNullable(name).orElse(ip + ":" + port);
this.address = GenericAddress.parse(ip + "/" + port);
this.deviceConfiguration = deviceConfiguration;
this.walk = walk;
this.community = Optional.ofNullable(community).orElse("public");
}
/**
* FIXME
* Lazy initialization of {@link #device} required as nested use of {@link ObjectMapper}
* lead to an exception. Try to remove this call with a version update of {@code jackson}.
*
* @return the lazy initialized device
*/
private Device initializeDevice() {
return DEVICE_FACTORY.getDevice(deviceConfiguration);
}
}
|
/**
*/
package org.ecore.service.componentMode.provider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.provider.ChangeNotifier;
import org.eclipse.emf.edit.provider.ChildCreationExtenderManager;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IChangeNotifier;
import org.eclipse.emf.edit.provider.IChildCreationExtender;
import org.eclipse.emf.edit.provider.IDisposable;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.INotifyChangedListener;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.ecore.service.componentMode.ComponentModePackage;
import org.ecore.service.componentMode.util.ComponentModeAdapterFactory;
/**
* This is the factory that is used to provide the interfaces needed to support Viewers.
* The adapters generated by this factory convert EMF adapter notifications into calls to {@link #fireNotifyChanged fireNotifyChanged}.
* The adapters also support Eclipse property sheets.
* Note that most of the adapters are shared among multiple instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class ComponentModeItemProviderAdapterFactory extends ComponentModeAdapterFactory
implements ComposeableAdapterFactory, IChangeNotifier, IDisposable, IChildCreationExtender {
/**
* This keeps track of the root adapter factory that delegates to this adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComposedAdapterFactory parentAdapterFactory;
/**
* This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IChangeNotifier changeNotifier = new ChangeNotifier();
/**
* This helps manage the child creation extenders.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ChildCreationExtenderManager childCreationExtenderManager = new ChildCreationExtenderManager(
ComponentModeEditPlugin.INSTANCE, ComponentModePackage.eNS_URI);
/**
* This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<Object> supportedTypes = new ArrayList<Object>();
/**
* This constructs an instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ComponentModeItemProviderAdapterFactory() {
supportedTypes.add(IEditingDomainItemProvider.class);
supportedTypes.add(IStructuredItemContentProvider.class);
supportedTypes.add(ITreeItemContentProvider.class);
supportedTypes.add(IItemLabelProvider.class);
supportedTypes.add(IItemPropertySource.class);
}
/**
* This keeps track of the one adapter used for all {@link org.ecore.service.componentMode.ComponentModeModel} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComponentModeModelItemProvider componentModeModelItemProvider;
/**
* This creates an adapter for a {@link org.ecore.service.componentMode.ComponentModeModel}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createComponentModeModelAdapter() {
if (componentModeModelItemProvider == null) {
componentModeModelItemProvider = new ComponentModeModelItemProvider(this);
}
return componentModeModelItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.ecore.service.componentMode.ComponentModeRepository} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComponentModeRepositoryItemProvider componentModeRepositoryItemProvider;
/**
* This creates an adapter for a {@link org.ecore.service.componentMode.ComponentModeRepository}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createComponentModeRepositoryAdapter() {
if (componentModeRepositoryItemProvider == null) {
componentModeRepositoryItemProvider = new ComponentModeRepositoryItemProvider(this);
}
return componentModeRepositoryItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.ecore.service.componentMode.ComponentModeCollection} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComponentModeCollectionItemProvider componentModeCollectionItemProvider;
/**
* This creates an adapter for a {@link org.ecore.service.componentMode.ComponentModeCollection}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createComponentModeCollectionAdapter() {
if (componentModeCollectionItemProvider == null) {
componentModeCollectionItemProvider = new ComponentModeCollectionItemProvider(this);
}
return componentModeCollectionItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.ecore.service.componentMode.ComponentModeDefinition} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComponentModeDefinitionItemProvider componentModeDefinitionItemProvider;
/**
* This creates an adapter for a {@link org.ecore.service.componentMode.ComponentModeDefinition}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createComponentModeDefinitionAdapter() {
if (componentModeDefinitionItemProvider == null) {
componentModeDefinitionItemProvider = new ComponentModeDefinitionItemProvider(this);
}
return componentModeDefinitionItemProvider;
}
/**
* This returns the root adapter factory that contains this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ComposeableAdapterFactory getRootAdapterFactory() {
return parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();
}
/**
* This sets the composed adapter factory that contains this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory) {
this.parentAdapterFactory = parentAdapterFactory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isFactoryForType(Object type) {
return supportedTypes.contains(type) || super.isFactoryForType(type);
}
/**
* This implementation substitutes the factory itself as the key for the adapter.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter adapt(Notifier notifier, Object type) {
return super.adapt(notifier, this);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object adapt(Object object, Object type) {
if (isFactoryForType(type)) {
Object adapter = super.adapt(object, type);
if (!(type instanceof Class<?>) || (((Class<?>) type).isInstance(adapter))) {
return adapter;
}
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public List<IChildCreationExtender> getChildCreationExtenders() {
return childCreationExtenderManager.getChildCreationExtenders();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Collection<?> getNewChildDescriptors(Object object, EditingDomain editingDomain) {
return childCreationExtenderManager.getNewChildDescriptors(object, editingDomain);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResourceLocator getResourceLocator() {
return childCreationExtenderManager;
}
/**
* This adds a listener.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void addListener(INotifyChangedListener notifyChangedListener) {
changeNotifier.addListener(notifyChangedListener);
}
/**
* This removes a listener.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void removeListener(INotifyChangedListener notifyChangedListener) {
changeNotifier.removeListener(notifyChangedListener);
}
/**
* This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void fireNotifyChanged(Notification notification) {
changeNotifier.fireNotifyChanged(notification);
if (parentAdapterFactory != null) {
parentAdapterFactory.fireNotifyChanged(notification);
}
}
/**
* This disposes all of the item providers created by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void dispose() {
if (componentModeModelItemProvider != null)
componentModeModelItemProvider.dispose();
if (componentModeRepositoryItemProvider != null)
componentModeRepositoryItemProvider.dispose();
if (componentModeCollectionItemProvider != null)
componentModeCollectionItemProvider.dispose();
if (componentModeDefinitionItemProvider != null)
componentModeDefinitionItemProvider.dispose();
}
}
|
package com.hb0730.boot.admin.project.system.quartz.model.dto;
import com.hb0730.boot.admin.domain.model.InputConverter;
import com.hb0730.boot.admin.domain.model.dto.BaseDTO;
import com.hb0730.boot.admin.project.system.quartz.model.entity.JobEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.NotBlank;
/**
* 定时任务(quartz)
*
* @author bing_huang
* @since 3.0.0
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class JobDTO extends BaseDTO implements InputConverter<JobEntity> {
private static final long serialVersionUID = 1L;
/**
* 备注
*/
private String description;
/**
* id
*/
private Long id;
/**
* 任务名称
*/
@NotBlank(message = "任务名称不为空")
private String name;
/**
* 任务组
*/
@NotBlank(message = "任务组不为空")
private String group;
/**
* Bean名称
*/
@NotBlank(message = "调用类不为空")
private String beanName;
/**
* 方法名称
*/
@NotBlank(message = "调用方法不为空")
private String beanMethod;
/**
* 参数
*/
private String methodParams;
/**
* cron表达式
*/
@NotBlank(message = "cron表达式不为空")
private String cron;
/**
* 负责人
*/
private String personInCharge;
/**
* 负责人邮箱
*/
private String email;
}
|
package com.atguigu.gmall.sms.dao;
import com.atguigu.gmall.sms.entity.SkuLadderEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品阶梯价格
*
* @author lifeline
* @email 13001196631@163.com
* @date 2020-03-15 00:35:15
*/
@Mapper
public interface SkuLadderDao extends BaseMapper<SkuLadderEntity> {
}
|
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.hadoop.ozone.container.ozoneimpl;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
import org.apache.hadoop.hdds.protocol.proto
.StorageContainerDatanodeProtocolProtos.ContainerReportsProto;
import org.apache.hadoop.hdds.scm.ScmConfigKeys;
import org.apache.hadoop.hdfs.server.datanode.StorageLocation;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.hdds.protocol.proto
.StorageContainerDatanodeProtocolProtos.NodeReportProto;
import org.apache.hadoop.ozone.OzoneConfigKeys;
import org.apache.hadoop.ozone.container.common.helpers.ContainerData;
import org.apache.hadoop.ozone.container.common.impl.ChunkManagerImpl;
import org.apache.hadoop.ozone.container.common.impl.ContainerManagerImpl;
import org.apache.hadoop.ozone.container.common.impl.Dispatcher;
import org.apache.hadoop.ozone.container.common.impl.KeyManagerImpl;
import org.apache.hadoop.ozone.container.common.interfaces.ChunkManager;
import org.apache.hadoop.ozone.container.common.interfaces.ContainerDispatcher;
import org.apache.hadoop.ozone.container.common.interfaces.ContainerManager;
import org.apache.hadoop.ozone.container.common.interfaces.KeyManager;
import org.apache.hadoop.ozone.container.common.statemachine.background
.BlockDeletingService;
import org.apache.hadoop.ozone.container.common.transport.server.XceiverServer;
import org.apache.hadoop.ozone.container.common.transport.server
.XceiverServerGrpc;
import org.apache.hadoop.ozone.container.common.transport.server
.XceiverServerSpi;
import org.apache.hadoop.ozone.container.common.transport.server.ratis
.XceiverServerRatis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY;
import static org.apache.hadoop.ozone.OzoneConfigKeys
.OZONE_BLOCK_DELETING_SERVICE_INTERVAL;
import static org.apache.hadoop.ozone.OzoneConfigKeys
.OZONE_BLOCK_DELETING_SERVICE_INTERVAL_DEFAULT;
import static org.apache.hadoop.ozone.OzoneConfigKeys
.OZONE_BLOCK_DELETING_SERVICE_TIMEOUT;
import static org.apache.hadoop.ozone.OzoneConfigKeys
.OZONE_BLOCK_DELETING_SERVICE_TIMEOUT_DEFAULT;
import static org.apache.hadoop.ozone.OzoneConsts.CONTAINER_ROOT_PREFIX;
import static org.apache.hadoop.ozone.OzoneConsts.INVALID_PORT;
/**
* Ozone main class sets up the network server and initializes the container
* layer.
*/
public class OzoneContainer {
public static final Logger LOG =
LoggerFactory.getLogger(OzoneContainer.class);
private final Configuration ozoneConfig;
private final ContainerDispatcher dispatcher;
private final ContainerManager manager;
private final XceiverServerSpi[] server;
private final ChunkManager chunkManager;
private final KeyManager keyManager;
private final BlockDeletingService blockDeletingService;
/**
* Creates a network endpoint and enables Ozone container.
*
* @param ozoneConfig - Config
* @throws IOException
*/
public OzoneContainer(
DatanodeDetails datanodeDetails, Configuration ozoneConfig)
throws IOException {
this.ozoneConfig = ozoneConfig;
List<StorageLocation> locations = new LinkedList<>();
String[] paths = ozoneConfig.getStrings(
OzoneConfigKeys.OZONE_METADATA_DIRS);
if (paths != null && paths.length > 0) {
for (String p : paths) {
locations.add(StorageLocation.parse(
Paths.get(p).resolve(CONTAINER_ROOT_PREFIX).toString()));
}
} else {
getDataDir(locations);
}
manager = new ContainerManagerImpl();
manager.init(this.ozoneConfig, locations, datanodeDetails);
this.chunkManager = new ChunkManagerImpl(manager);
manager.setChunkManager(this.chunkManager);
this.keyManager = new KeyManagerImpl(manager, ozoneConfig);
manager.setKeyManager(this.keyManager);
long svcInterval =
ozoneConfig.getTimeDuration(OZONE_BLOCK_DELETING_SERVICE_INTERVAL,
OZONE_BLOCK_DELETING_SERVICE_INTERVAL_DEFAULT, TimeUnit.MILLISECONDS);
long serviceTimeout = ozoneConfig.getTimeDuration(
OZONE_BLOCK_DELETING_SERVICE_TIMEOUT,
OZONE_BLOCK_DELETING_SERVICE_TIMEOUT_DEFAULT, TimeUnit.MILLISECONDS);
this.blockDeletingService = new BlockDeletingService(manager,
svcInterval, serviceTimeout, TimeUnit.MILLISECONDS, ozoneConfig);
this.dispatcher = new Dispatcher(manager, this.ozoneConfig);
boolean useGrpc = this.ozoneConfig.getBoolean(
ScmConfigKeys.DFS_CONTAINER_GRPC_ENABLED_KEY,
ScmConfigKeys.DFS_CONTAINER_GRPC_ENABLED_DEFAULT);
server = new XceiverServerSpi[]{
useGrpc ? new XceiverServerGrpc(datanodeDetails,
this.ozoneConfig, this.dispatcher) :
new XceiverServer(datanodeDetails,
this.ozoneConfig, this.dispatcher),
XceiverServerRatis
.newXceiverServerRatis(datanodeDetails, this.ozoneConfig, dispatcher)
};
}
/**
* Starts serving requests to ozone container.
*
* @throws IOException
*/
public void start() throws IOException {
for (XceiverServerSpi serverinstance : server) {
serverinstance.start();
}
blockDeletingService.start();
dispatcher.init();
}
/**
* Stops the ozone container.
* <p>
* Shutdown logic is not very obvious from the following code. if you need to
* modify the logic, please keep these comments in mind. Here is the shutdown
* sequence.
* <p>
* 1. We shutdown the network ports.
* <p>
* 2. Now we need to wait for all requests in-flight to finish.
* <p>
* 3. The container manager lock is a read-write lock with "Fairness"
* enabled.
* <p>
* 4. This means that the waiting threads are served in a "first-come-first
* -served" manner. Please note that this applies to waiting threads only.
* <p>
* 5. Since write locks are exclusive, if we are waiting to get a lock it
* implies that we are waiting for in-flight operations to complete.
* <p>
* 6. if there are other write operations waiting on the reader-writer lock,
* fairness guarantees that they will proceed before the shutdown lock
* request.
* <p>
* 7. Since all operations either take a reader or writer lock of container
* manager, we are guaranteed that we are the last operation since we have
* closed the network port, and we wait until close is successful.
* <p>
* 8. We take the writer lock and call shutdown on each of the managers in
* reverse order. That is chunkManager, keyManager and containerManager is
* shutdown.
*/
public void stop() {
LOG.info("Attempting to stop container services.");
for(XceiverServerSpi serverinstance: server) {
serverinstance.stop();
}
dispatcher.shutdown();
try {
this.manager.writeLock();
this.chunkManager.shutdown();
this.keyManager.shutdown();
this.manager.shutdown();
this.blockDeletingService.shutdown();
LOG.info("container services shutdown complete.");
} catch (IOException ex) {
LOG.warn("container service shutdown error:", ex);
} finally {
this.manager.writeUnlock();
}
}
/**
* Returns a paths to data dirs.
*
* @param pathList - List of paths.
* @throws IOException
*/
private void getDataDir(List<StorageLocation> pathList) throws IOException {
for (String dir : ozoneConfig.getStrings(DFS_DATANODE_DATA_DIR_KEY)) {
StorageLocation location = StorageLocation.parse(dir);
pathList.add(location);
}
}
/**
* Returns node report of container storage usage.
*/
public NodeReportProto getNodeReport() throws IOException {
return this.manager.getNodeReport();
}
private int getPortbyType(HddsProtos.ReplicationType replicationType) {
for (XceiverServerSpi serverinstance : server) {
if (serverinstance.getServerType() == replicationType) {
return serverinstance.getIPCPort();
}
}
return INVALID_PORT;
}
/**
* Returns the container server IPC port.
*
* @return Container server IPC port.
*/
public int getContainerServerPort() {
return getPortbyType(HddsProtos.ReplicationType.STAND_ALONE);
}
/**
* Returns the Ratis container Server IPC port.
*
* @return Ratis port.
*/
public int getRatisContainerServerPort() {
return getPortbyType(HddsProtos.ReplicationType.RATIS);
}
/**
* Returns container report.
* @return - container report.
* @throws IOException
*/
public ContainerReportsProto getContainerReport() throws IOException {
return this.manager.getContainerReport();
}
// TODO: remove getContainerReports
/**
* Returns the list of closed containers.
* @return - List of closed containers.
* @throws IOException
*/
public List<ContainerData> getClosedContainerReports() throws IOException {
return this.manager.getClosedContainerReports();
}
private XceiverServerSpi getRatisSerer() {
for (XceiverServerSpi serverInstance : server) {
if (serverInstance instanceof XceiverServerRatis) {
return serverInstance;
}
}
return null;
}
private XceiverServerSpi getStandaAloneSerer() {
for (XceiverServerSpi serverInstance : server) {
if (!(serverInstance instanceof XceiverServerRatis)) {
return serverInstance;
}
}
return null;
}
@VisibleForTesting
public ContainerManager getContainerManager() {
return this.manager;
}
public void submitContainerRequest(
ContainerProtos.ContainerCommandRequestProto request,
HddsProtos.ReplicationType replicationType) throws IOException {
XceiverServerSpi serverInstance;
long containerId = getContainerIdForCmd(request);
if (replicationType == HddsProtos.ReplicationType.RATIS) {
serverInstance = getRatisSerer();
Preconditions.checkNotNull(serverInstance);
serverInstance.submitRequest(request);
LOG.info("submitting {} request over RATIS server for container {}",
request.getCmdType(), containerId);
} else {
serverInstance = getStandaAloneSerer();
Preconditions.checkNotNull(serverInstance);
getStandaAloneSerer().submitRequest(request);
LOG.info(
"submitting {} request over STAND_ALONE server for container {}",
request.getCmdType(), containerId);
}
}
private long getContainerIdForCmd(
ContainerProtos.ContainerCommandRequestProto request)
throws IllegalArgumentException {
ContainerProtos.Type type = request.getCmdType();
switch (type) {
case CloseContainer:
return request.getCloseContainer().getContainerID();
// Right now, we handle only closeContainer via queuing it over the
// over the XceiVerServer. For all other commands we throw Illegal
// argument exception here. Will need to extend the switch cases
// in case we want add another commands here.
default:
throw new IllegalArgumentException("Cmd " + request.getCmdType()
+ " not supported over HearBeat Response");
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.examples.pdmodel;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.common.PDMetadata;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.xml.XmpSerializer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.GregorianCalendar;
import javax.xml.transform.TransformerException;
/**
* This is an example on how to add metadata to a document.
*
* @author Ben Litchfield
*
*/
public final class AddMetadataFromDocInfo
{
private AddMetadataFromDocInfo()
{
//utility class
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
* @throws TransformerException
*/
public static void main( String[] args ) throws IOException, TransformerException
{
if( args.length != 2 )
{
usage();
}
else
{
PDDocument document = null;
try
{
document = PDDocument.load( new File(args[0]) );
if( document.isEncrypted() )
{
System.err.println( "Error: Cannot add metadata to encrypted document." );
System.exit( 1 );
}
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDDocumentInformation info = document.getDocumentInformation();
XMPMetadata metadata = XMPMetadata.createXMPMetadata();
AdobePDFSchema pdfSchema = metadata.createAndAddAdobePDFSchema();
pdfSchema.setKeywords( info.getKeywords() );
pdfSchema.setProducer( info.getProducer() );
XMPBasicSchema basicSchema = metadata.createAndAddXMPBasicSchema();
basicSchema.setModifyDate( info.getModificationDate() );
basicSchema.setCreateDate( info.getCreationDate() );
basicSchema.setCreatorTool( info.getCreator() );
basicSchema.setMetadataDate( new GregorianCalendar() );
DublinCoreSchema dcSchema = metadata.createAndAddDublinCoreSchema();
dcSchema.setTitle( info.getTitle() );
dcSchema.addCreator( "PDFBox" );
dcSchema.setDescription( info.getSubject() );
PDMetadata metadataStream = new PDMetadata(document);
catalog.setMetadata( metadataStream );
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(metadata, baos, false);
metadataStream.importXMPMetadata( baos.toByteArray() );
document.save( args[1] );
}
finally
{
if( document != null )
{
document.close();
}
}
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + AddMetadataFromDocInfo.class.getName() + " <input-pdf> <output-pdf>" );
}
}
|
package com.in28minutes.rest.webservices.restfulwebservices;
public class HelloWorldBean {
private String message;
public HelloWorldBean(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return String.format("HelloWorldBean [message=%s]", message);
}
}
|
package tech.teslex.telegroo.telegram.api.types.inline;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import tech.teslex.telegroo.telegram.api.types.InlineKeyboardMarkup;
/**
* Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.
*/
@EqualsAndHashCode(callSuper = true)
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InlineQueryResultCachedVideo extends InlineQueryResult {
/**
* Type of the result, must be video
*/
private String type = "video";
/**
* Unique identifier for this result, 1-64 bytes
*/
private String id;
/**
* A valid file identifier for the video file
*/
@JsonProperty(value = "video_file_id")
private String videoFileId;
/**
* Title for the result
*/
private String title;
/**
* Optional. Short description of the result
*/
@JsonProperty(required = false)
private String description;
/**
* Optional. Caption of the video to be sent, 0-1024 characters
*/
@JsonProperty(required = false)
private String caption;
/**
* Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption.
*/
@JsonProperty(value = "parse_mode", required = false)
private String parseMode;
/**
* Optional. Inline keyboard attached to the message
*/
@JsonProperty(value = "reply_markup", required = false)
private InlineKeyboardMarkup replyMarkup;
/**
* Optional. Content of the message to be sent instead of the video
*/
@JsonProperty(value = "input_message_content", required = false)
private InputMessageContent inputMessageContent;
}
|
package ru.stqa.pft.sanbox;
public class Square {
public double l;
public Square(double l) {
this.l = l;
}
public double area() {
return this.l * this.l;
}
}
|
package io.quarkus.mongodb.runtime;
import static java.lang.String.format;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jboss.logging.Logger;
import io.quarkus.kubernetes.service.binding.runtime.ServiceBinding;
import io.quarkus.kubernetes.service.binding.runtime.ServiceBindingConfigSource;
import io.quarkus.kubernetes.service.binding.runtime.ServiceBindingConverter;
/**
* ServiceBindingConverter for MongoDB to support SBO (Service Binding Operator) in Quarkus.
*
* This class supports both the <b>Standard</b> and <b>SRV</b> connection string format for
* MongoDB depending on whether port is provided or not.
*
* <br>
* Following individual properties are supported to make the connection string:
* <ul>
* <li>username</li>
* <li>password</li>
* <li>host</li>
* <li>port</li>
* <li>database</li>
* </ul>
* <i>Other than host all other properties are optinoal</i>
*
* <br>
* <br>
* Only following options are supported by default:
* <ul>
* <li>retryWrites=true</li>
* <li>w=majority</li>
* </ul>
*
*/
public class MongoServiceBindingConverter implements ServiceBindingConverter {
private static final Logger LOGGER = Logger.getLogger(MongoServiceBindingConverter.class);
private static final String BINDING_TYPE = "mongodb";
public static final String BINDING_CONFIG_SOURCE_NAME = BINDING_TYPE + "-k8s-service-binding-source";
public static final String MONGO_DB_CONNECTION_STRING = "quarkus.mongodb.connection-string";
// DB properties
public static final String DB_USER = "username";
public static final String DB_PASSWORD = "password";
public static final String DB_HOST = "host";
public static final String DB_PORT = "port";
public static final String DB_DATABASE = "database";
public static final String DB_PREFIX_STANDARD = "mongodb://";
public static final String DB_PREFIX_SRV = "mongodb+srv://";
public static final String DB_DEFAULT_OPTIONS = "?retryWrites=true&w=majority";
private static final String CONNECTION_STRING_WITH_USER = "%s%s:%s@%s/%s" + DB_DEFAULT_OPTIONS; // user:pass@hostPort/database
private static final String CONNECTION_STRING_WITH_USER_NO_DB = "%s%s:%s@%s" + DB_DEFAULT_OPTIONS; // user:pass@hostPort
private static final String CONNECTION_STRING_WITHOUT_USER = "%s%s/%s" + DB_DEFAULT_OPTIONS; // hostPort/database
private static final String CONNECTION_STRING_WITHOUT_USER_NO_DB = "%s%s" + DB_DEFAULT_OPTIONS; // hostPort
@Override
public Optional<ServiceBindingConfigSource> convert(List<ServiceBinding> serviceBindings) {
Optional<ServiceBinding> matchingByType = ServiceBinding.singleMatchingByType(BINDING_TYPE, serviceBindings);
if (matchingByType.isEmpty()) {
return Optional.empty();
}
Map<String, String> properties = new HashMap<>();
properties.put(MONGO_DB_CONNECTION_STRING, getConnectionString(matchingByType.get()));
return Optional.of(new ServiceBindingConfigSource(BINDING_CONFIG_SOURCE_NAME, properties));
}
private String getConnectionString(ServiceBinding binding) {
String user = getDbProperty(binding, DB_USER);
String password = getDbProperty(binding, DB_PASSWORD);
String hostPort = getHostPort(binding);
String database = getDbProperty(binding, DB_DATABASE);
String prefix = isPortProvided(hostPort) ? DB_PREFIX_STANDARD : DB_PREFIX_SRV;
String connectionString;
if (isBlank(user)) {
if (isBlank(database)) {
connectionString = format(CONNECTION_STRING_WITHOUT_USER_NO_DB, prefix, hostPort);
} else {
connectionString = format(CONNECTION_STRING_WITHOUT_USER, prefix, hostPort, database);
}
} else {
if (isBlank(database)) {
connectionString = format(CONNECTION_STRING_WITH_USER_NO_DB, prefix, user, password, hostPort);
} else {
connectionString = format(CONNECTION_STRING_WITH_USER, prefix, user, password, hostPort, database);
}
}
LOGGER.info(format("MongoDB connection string: [%s]", connectionString));
return connectionString;
}
private String getDbProperty(ServiceBinding binding, String dbPropertyKey) {
String dbPropertyValue = binding.getProperties().get(dbPropertyKey);
if (isBlank(dbPropertyValue)) {
LOGGER.debug(format("Property '%s' not found", dbPropertyKey));
}
return dbPropertyValue;
}
private String getHostPort(ServiceBinding binding) {
String host = getDbProperty(binding, DB_HOST);
String port = getDbProperty(binding, DB_PORT);
String hostPort = host;
if (isNotBlank(host)) {
if (isNotBlank(port)) {
hostPort = host + ":" + port;
}
} else {
LOGGER.warn("Unable to get the host property. Connection string won't be correct");
}
return hostPort;
}
private boolean isPortProvided(String hostPort) {
return hostPort != null && hostPort.contains(":");
}
private boolean isBlank(String value) {
return value == null || value.trim().length() == 0;
}
private boolean isNotBlank(String value) {
return !isBlank(value);
}
}
|
package exceptions;
public class WaitFor2PlayerException extends GenericEndpointException {
private static final long serialVersionUID = 1L;
public WaitFor2PlayerException(String errorMessage) {
super("Name: Error Players.", errorMessage);
}
}
|
package com.ctrip.framework.apollo.spring.annotation;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.spring.property.PlaceholderHelper;
import com.ctrip.framework.apollo.spring.property.SpringValue;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinition;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueRegistry;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Bean;
/**
* Spring value processor of field or method which has @Value and xml config placeholders.
*
* @author github.com/zhegexiaohuozi seimimaster@gmail.com
* @since 2017/12/20.
*/
public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor, BeanFactoryAware {
private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class);
private final ConfigUtil configUtil;
private final PlaceholderHelper placeholderHelper;
private final SpringValueRegistry springValueRegistry;
private BeanFactory beanFactory;
private Multimap<String, SpringValueDefinition> beanName2SpringValueDefinitions;
public SpringValueProcessor() {
configUtil = ApolloInjector.getInstance(ConfigUtil.class);
placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class);
springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class);
beanName2SpringValueDefinitions = LinkedListMultimap.create();
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled() && beanFactory instanceof BeanDefinitionRegistry) {
beanName2SpringValueDefinitions = SpringValueDefinitionProcessor
.getBeanName2SpringValueDefinitions((BeanDefinitionRegistry) beanFactory);
}
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) {
super.postProcessBeforeInitialization(bean, beanName);
processBeanPropertyValues(bean, beanName);
}
return bean;
}
@Override
protected void processField(Object bean, String beanName, Field field) {
// register @Value on field
Value value = field.getAnnotation(Value.class);
if (value == null) {
return;
}
Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
if (keys.isEmpty()) {
return;
}
for (String key : keys) {
SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
springValueRegistry.register(beanFactory, key, springValue);
logger.debug("Monitoring {}", springValue);
}
}
@Override
protected void processMethod(Object bean, String beanName, Method method) {
//register @Value on method
Value value = method.getAnnotation(Value.class);
if (value == null) {
return;
}
//skip Configuration bean methods
if (method.getAnnotation(Bean.class) != null) {
return;
}
if (method.getParameterTypes().length != 1) {
logger.error("Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters",
bean.getClass().getName(), method.getName(), method.getParameterTypes().length);
return;
}
Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
if (keys.isEmpty()) {
return;
}
for (String key : keys) {
SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, method, false);
springValueRegistry.register(beanFactory, key, springValue);
logger.info("Monitoring {}", springValue);
}
}
private void processBeanPropertyValues(Object bean, String beanName) {
Collection<SpringValueDefinition> propertySpringValues = beanName2SpringValueDefinitions
.get(beanName);
if (propertySpringValues == null || propertySpringValues.isEmpty()) {
return;
}
for (SpringValueDefinition definition : propertySpringValues) {
try {
PropertyDescriptor pd = BeanUtils
.getPropertyDescriptor(bean.getClass(), definition.getPropertyName());
Method method = pd.getWriteMethod();
if (method == null) {
continue;
}
SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(),
bean, beanName, method, false);
springValueRegistry.register(beanFactory, definition.getKey(), springValue);
logger.debug("Monitoring {}", springValue);
} catch (Throwable ex) {
logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(),
definition.getPropertyName());
}
}
// clear
beanName2SpringValueDefinitions.removeAll(beanName);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
|
// --------------------------------------------------------------------------------
// Copyright 2002-2021 Echo Three, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// --------------------------------------------------------------------------------
package com.echothree.ui.web.main.action.humanresources.employeecontactmechanism;
import com.echothree.view.client.web.struts.sprout.annotation.SproutForm;
@SproutForm(name="EmployeeContactMechanismCommentEdit")
public class CommentEditActionForm
extends CommentAddActionForm {
// Nothing additional beyond CommentAddActionForm
}
|
/*
* $Id: CellContext.java 3778 2010-09-07 10:10:49Z kleopatra $
*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx.renderer;
import java.awt.Color;
import java.awt.Font;
import java.io.Serializable;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
/**
* Encapsulates a snapshop of cell content and default display context
* for usage by a <code>ComponentProvider</code>.
* <p>
*
* One part is the super-set of properties that's traditionally passed into the
* core renderers' (Table-, List-, Tree-) getXXCellRendererComponent. Raw
* properties which define the context are
*
* <ul>
* <li> selected
* <li> focused
* <li> expanded
* <li> leaf
* </ul>
*
* Similarl to a ComponentAdapter, the properties are a super-set of those for
* a concrete component type. It's up to sub-classes (once the generics will be removed, until
* then the DefaultXXRenderers - PENDING JW: undecided - even after the generics removal, the
* param list in the subclasses are the same) fill any reasonable
* defaults for those not applicable to the specific component context.
*
* With those raw properties given, a CellContext looks up and returns dependent visual
* properties as appropriate for the concrete component. Typically, they are taken
* from the component if supported, or requested from the UIManager.
* Dependent properties are
*
* <ul>
* <li> foreground and background color
* <li> border
* <li> icon (relevant for trees only)
* <li> editable
* </ul>
*
* For a backdoor, the cell location (in horizontal and vertical view coordinates)
* and the originating component is accessible as well. Note that they are not necessarily
* valid for the "life" component. It's not recommended to actually use them. If needed,
* that's probably a sign the api is lacking :-)
* <p>
*
*
* <ul>
*
* <li>PENDING: still incomplete? how about Font?
* <li>PENDING: protected methods? Probably need to open up - derived
* properties should be accessible in client code.
* </ul>
*
* @author Jeanette Winzenburg
*/
public class CellContext implements Serializable {
/** the default border for unfocused cells. */
protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
/** ?? the default border for unfocused cells. ?? */
private static final Border SAFE_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1,
1);
/**
* Returns the shared border for unfocused cells.
* <p>
* PENDING: ?? copied from default renderers - why is it done like this?
*
* @return the border for unfocused cells.
*/
private static Border getNoFocusBorder() {
if (System.getSecurityManager() != null) {
return SAFE_NO_FOCUS_BORDER;
} else {
return noFocusBorder;
}
}
/** PENDING JW: maybe make this a WeakReference? Would be a more robust fix for Issue #1040-swingx. */
protected transient JComponent component;
/** PENDING JW: maybe make this a WeakReference? Would be a more robust fix for Issue #1040-swingx. */
protected transient Object value;
protected transient int row;
protected transient int column;
protected transient boolean selected;
protected transient boolean focused;
protected transient boolean expanded;
protected transient boolean leaf;
protected transient boolean dropOn;
// --------------------------- install context
/**
* Sets the state of the cell's context. Convenience method for subclasses.
*
* @param value the content value of the cell
* @param row the cell's row index in view coordinates
* @param column the cell's column index in view coordinates
* @param selected the cell's selected state
* @param focused the cell's focused state
* @param expanded the cell's expanded state
* @param leaf the cell's leaf state
*/
protected void installState(Object value, int row, int column,
boolean selected, boolean focused, boolean expanded, boolean leaf) {
this.value = value;
this.row = row;
this.column = column;
this.selected = selected;
this.focused = focused;
this.expanded = expanded;
this.leaf = leaf;
}
/**
* Replaces the value of this cell context with the given parameter and returns
* the replaced value.
*
* @param value the new value of the cell context
* @return the replaced value of the cell context
*/
public Object replaceValue(Object value) {
Object old = getValue();
this.value = value;
return old;
}
// -------------------- accessors of installed state
/**
* Returns the component the cell resides on, may be null. Subclasses are
* expected to override and return the component type they are handling.
*
* @return the component the cell resides on, may be null.
*/
public JComponent getComponent() {
return component;
}
/**
* Returns the value of the cell as set in the install.
*
* @return the content value of the cell.
*/
public Object getValue() {
return value;
}
/**
* Returns the cell's row index in view coordinates as set in the install.
*
* @return the cell's row index.
*/
public int getRow() {
return row;
}
/**
* Returns the cell's column index in view coordinates as set in the
* install.
*
* @return the cell's column index.
*/
public int getColumn() {
return column;
}
/**
* Returns the selected state as set in the install.
*
* @return the cell's selected state.
*/
public boolean isSelected() {
return selected;
}
/**
* Returns the focused state as set in the install.
*
* @return the cell's focused state.
*/
public boolean isFocused() {
return focused;
}
/**
* Returns the expanded state as set in the install.
*
* @return the cell's expanded state.
*/
public boolean isExpanded() {
return expanded;
}
/**
* Returns the leaf state as set in the install.
*
* @return the cell's leaf state.
*/
public boolean isLeaf() {
return leaf;
}
// -------------------- accessors for derived state
/**
* Returns the cell's editability. Subclasses should override to return a
* reasonable cell-related state.
* <p>
*
* Here: false.
*
* @return the cell's editable property.
*/
public boolean isEditable() {
return false;
}
/**
* Returns the icon. Subclasses should override to return a reasonable
* cell-related state.
* <p>
*
* Here: <code>null</code>.
*
* @return the cell's icon.
*/
public Icon getIcon() {
return null;
}
/**
* Returns a boolean indicating if the cell is a drop location with any of the dropOn
* modes. It's up to subclasses to implement.
* <p>
*
* Here: false.
*
* @return true if the current cell is a drop location with any of the dropOn modes,
* false otherwise
*/
protected boolean isDropOn() {
return dropOn;
}
/**
* Returns the foreground color of the renderered component or null if the
* component is null
* <p>
*
* PENDING: fallback to UI properties if comp == null?
*
* @return the foreground color of the rendered component.
*/
protected Color getForeground() {
if (isDropOn()) {
return getSelectionForeground();
}
return getComponent() != null ? getComponent().getForeground() : null;
}
/**
* Returns the background color of the renderered component or null if the
* component is null
* <p>
*
* PENDING: fallback to UI properties if comp == null?
*
* @return the background color of the rendered component.
*/
protected Color getBackground() {
if (isDropOn()) {
return getSelectionBackground();
}
return getComponent() != null ? getComponent().getBackground() : null;
}
/**
* Returns the default selection background color of the renderered
* component. Typically, the color is LF specific. It's up to subclasses to
* look it up. Here: returns null.
* <p>
*
* PENDING: return UI properties here?
*
* @return the selection background color of the rendered component.
*/
protected Color getSelectionBackground() {
return null;
}
/**
* Returns the default selection foreground color of the renderered
* component. Typically, the color is LF specific. It's up to subclasses to
* look it up. Here: returns null.
* <p>
*
* PENDING: return UI properties here?
*
* @return the selection foreground color of the rendered component.
*/
protected Color getSelectionForeground() {
return null;
}
/**
* Returns the default focus border of the renderered component. Typically,
* the border is LF specific.
*
* @return the focus border of the rendered component.
*/
protected Border getFocusBorder() {
Border border = null;
if (isSelected()) {
border = UIManager
.getBorder(getUIKey("focusSelectedCellHighlightBorder"));
}
if (border == null) {
border = UIManager.getBorder(getUIKey("focusCellHighlightBorder"));
}
return border;
}
/**
* Returns the default border of the renderered component depending on cell
* state. Typically, the border is LF specific.
* <p>
*
* Here: returns the focus border if the cell is focused, the context
* defined no focus border otherwise.
*
* @return the default border of the rendered component.
*/
protected Border getBorder() {
if (isFocused()) {
return getFocusBorder();
}
Border border = UIManager.getBorder(getUIKey("cellNoFocusBorder"));
return border != null ? border : getNoFocusBorder();
}
/**
* Returns the default focused foreground color of the renderered component.
* Typically, the color is LF specific.
*
* @return the focused foreground color of the rendered component.
*/
protected Color getFocusForeground() {
return UIManager.getColor(getUIKey("focusCellForeground"));
}
/**
* Returns the default focused background color of the renderered component.
* Typically, the color is LF specific.
*
* @return the focused background color of the rendered component.
*/
protected Color getFocusBackground() {
return UIManager.getColor(getUIKey("focusCellBackground"));
}
protected Color getDropCellForeground() {
return UIManager.getColor(getUIKey("dropCellForeground"));
}
protected Color getDropCellBackground() {
return UIManager.getColor(getUIKey("dropCellBackground"));
}
// ----------------------- convenience
/**
* Convenience method to build a component type specific lookup key for the
* UIManager.
*
* @param key the general part of the key
* @return a composed key build of a component type prefix and the input.
*/
protected String getUIKey(String key) {
return getUIPrefix() + key;
}
/**
* Returns the component type specific prefix of keys for lookup in the
* UIManager. Subclasses must override, here: returns the empty String.
*
* @return the component type specific prefix.
*/
protected String getUIPrefix() {
return "";
}
/**
* Returns the Font of the target component or null if no component installed.
* @return
*/
protected Font getFont() {
return getComponent() != null ? getComponent().getFont() : null;
}
public String getCellRendererName() {
return getUIPrefix() + "cellRenderer";
}
}
|
package com.easytoolsoft.easyreport.domain.metadata;
import com.easytoolsoft.easyreport.data.metadata.dao.ICategoryDao;
import com.easytoolsoft.easyreport.data.metadata.po.Category;
import com.easytoolsoft.easyreport.domain.BaseDomainTest;
import com.easytoolsoft.easyreport.domain.metadata.service.impl.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import static org.hamcrest.Matchers.equalTo;
@Slf4j
@PrepareForTest(CategoryService.class)
public class CategoryServiceTest extends BaseDomainTest {
@Mock
private ICategoryDao categoryDao;
@InjectMocks
private CategoryService categoryService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void addTest() throws Exception {
final Category record = Category.builder().id(0).parentId(9).build();
PowerMockito.when(categoryDao.insert(record)).thenAnswer(invocationOnMock -> {
record.setId(10);
return 1;
});
PowerMockito.when(categoryDao.selectById(9)).thenReturn(record);
PowerMockito.when(categoryService, "updateHasChild", record.getId(), true).thenReturn(1);
categoryService.add(record);
Assert.assertThat(record.getPath(), equalTo("9,10"));
}
}
|
package me.xiaobailong24.mvvmarms.http.imageloader.glide;
import android.content.Context;
import com.bumptech.glide.GlideBuilder;
/**
* @author xiaobailong24
* @date 2017/8/17
* Glide 配置接口
*/
public interface GlideAppliesOptions {
/**
* 配置 Glide 的自定义参数
*
* @param context Context
* @param builder {@link GlideBuilder} 此类被用来创建 Glide
*/
void applyGlideOptions(Context context, GlideBuilder builder);
}
|
/*
* Copyright © 2014-2015 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.api.app;
import co.cask.cdap.api.artifact.ArtifactId;
import co.cask.cdap.api.data.stream.Stream;
import co.cask.cdap.api.data.stream.StreamSpecification;
import co.cask.cdap.api.dataset.Dataset;
import co.cask.cdap.api.dataset.module.DatasetModule;
import co.cask.cdap.api.flow.Flow;
import co.cask.cdap.api.flow.FlowSpecification;
import co.cask.cdap.api.mapreduce.MapReduce;
import co.cask.cdap.api.mapreduce.MapReduceSpecification;
import co.cask.cdap.api.plugin.Plugin;
import co.cask.cdap.api.schedule.ScheduleSpecification;
import co.cask.cdap.api.service.ServiceSpecification;
import co.cask.cdap.api.spark.Spark;
import co.cask.cdap.api.spark.SparkSpecification;
import co.cask.cdap.api.worker.WorkerSpecification;
import co.cask.cdap.api.workflow.Workflow;
import co.cask.cdap.api.workflow.WorkflowSpecification;
import co.cask.cdap.internal.dataset.DatasetCreationSpec;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Application Specification used in core code.
*/
public interface ApplicationSpecification {
/**
* @return Name of the Application.
*/
String getName();
/**
* @return Version of the Application.
*/
String getAppVersion();
/**
* @return Configuration string used during the creation of the Application.
*/
@Nullable
String getConfiguration();
/**
* @return Description of the Application.
*/
String getDescription();
/**
* @return ID of the artifact used to create the application.
*/
ArtifactId getArtifactId();
/**
* @return An immutable {@link Map} from {@link Stream} name to {@link StreamSpecification}
* for {@link Stream}s configured for the Application.
*/
Map<String, StreamSpecification> getStreams();
/**
* @return An immutable {@link Map} from {@link DatasetModule} name to {@link DatasetModule} class name for
* dataset modules configured for the Application.
*/
Map<String, String> getDatasetModules();
/**
* @return An immutable {@link Map} from {@link Dataset} name to {@link DatasetCreationSpec} for {@link Dataset}s
* configured for the Application.
*/
Map<String, DatasetCreationSpec> getDatasets();
/**
* @return An immutable {@link Map} from {@link Flow} name to {@link FlowSpecification}
* for {@link Flow}s configured for the Application.
*/
Map<String, FlowSpecification> getFlows();
/**
* @return An immutable {@link Map} from {@link MapReduce} name to {@link MapReduceSpecification}
* for {@link MapReduce} jobs configured for the Application.
*/
Map<String, MapReduceSpecification> getMapReduce();
/**
* @return An immutable {@link Map} from {@link Spark} name to
* {@link SparkSpecification} for {@link Spark} jobs configured for the Application.
*/
Map<String, SparkSpecification> getSpark();
/**
* @return An immutable {@link Map} from {@link Workflow} name to {@link WorkflowSpecification}
* for {@link Workflow}s configured for the Application.
*/
Map<String, WorkflowSpecification> getWorkflows();
/**
* @return An immutable {@link Map} from service name to {@link ServiceSpecification}
* for services configured for the Application.
*/
Map<String, ServiceSpecification> getServices();
/**
* @return An immutable {@link Map} from worker name to {@link WorkerSpecification}
* for workers configured for the Application.
*/
Map<String, WorkerSpecification> getWorkers();
/**
* @return An immutable {@link Map} from Schedule name to {@link ScheduleSpecification}
*/
Map<String, ScheduleSpecification> getSchedules();
/**
* @return An immutable {@link Map} from plugin id to {@link Plugin}
*/
Map<String, Plugin> getPlugins();
}
|
package com.airback.module.project.view.ticket;
import com.hp.gagawa.java.elements.A;
import com.hp.gagawa.java.elements.Div;
import com.hp.gagawa.java.elements.Img;
import com.hp.gagawa.java.elements.Span;
import com.airback.common.i18n.GenericI18Enum;
import com.airback.configuration.SiteConfiguration;
import com.airback.core.utils.NumberUtils;
import com.airback.module.file.StorageUtils;
import com.airback.module.project.ProjectLinkGenerator;
import com.airback.module.project.domain.ProjectTicket;
import com.airback.module.project.i18n.OptionI18nEnum;
import com.airback.module.project.i18n.TimeTrackingI18nEnum;
import com.airback.module.project.ui.ProjectAssetsManager;
import com.airback.module.project.ui.components.TicketRowRender;
import com.airback.vaadin.UserUIContext;
import com.airback.vaadin.ui.ELabel;
import com.airback.vaadin.web.ui.WebThemes;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
/**
* @author airback Ltd
* @since 7.0.0
*/
public class ReadableTicketRowRenderer extends TicketRowRender {
public ReadableTicketRowRenderer(ProjectTicket ticket) {
this.ticket = ticket;
String avatarLink = StorageUtils.getAvatarPath(ticket.getAssignUserAvatarId(), 16);
Img img = new Img(ticket.getAssignUserFullName(), avatarLink).setCSSClass(WebThemes.CIRCLE_BOX)
.setTitle(ticket.getAssignUserFullName());
A ticketLink;
if (ticket.isBug() || ticket.isTask()) {
ticketLink = new A(ProjectLinkGenerator.generateProjectItemLink(ticket.getProjectShortName(), ticket.getProjectId(), ticket.getType(), ticket.getExtraTypeId() + "")).
appendText(ticket.getName());
} else {
ticketLink = new A(ProjectLinkGenerator.generateProjectItemLink(ticket.getProjectShortName(), ticket.getProjectId(), ticket.getType(), ticket.getTypeId() + "")).
appendText(ticket.getName());
}
this.with(ELabel.html(ProjectAssetsManager.getAsset(ticket.getType()).getHtml() + " " + img.write() + " " + ticketLink.write())
.withStyleName(WebThemes.LABEL_WORD_WRAP).withFullWidth());
this.addStyleName(WebThemes.BORDER_LIST_ROW);
if (ticket.isTask()) {
this.addStyleName("task");
} else if (ticket.isBug()) {
this.addStyleName("bug");
} else if (ticket.isRisk()) {
this.addStyleName("risk");
}
CssLayout footer = new CssLayout();
footer.addComponent(buildTicketCommentComp(ticket));
footer.addComponent(buildTicketPriorityComp(ticket));
footer.addComponent(buildTicketStatusComp(ticket));
footer.addComponent(buildStartdateComp(ticket));
footer.addComponent(buildEnddateComp(ticket));
footer.addComponent(buildDuedateComp(ticket));
if (!SiteConfiguration.isCommunityEdition()) {
footer.addComponent(buildBillableHoursComp(ticket));
footer.addComponent(buildNonBillableHoursComp(ticket));
}
this.with(footer);
}
private Component buildTicketCommentComp(ProjectTicket ticket) {
return ELabel.html(VaadinIcons.COMMENT_O.getHtml() + " " + NumberUtils.zeroIfNull(ticket.getNumComments()))
.withDescription(UserUIContext.getMessage(GenericI18Enum.OPT_COMMENTS)).withStyleName(WebThemes.META_INFO);
}
private Component buildTicketPriorityComp(ProjectTicket ticket) {
return ELabel.html(ProjectAssetsManager.getPriorityHtml(ticket.getPriority()) + " " +
UserUIContext.getMessage(OptionI18nEnum.Priority.class, ticket.getPriority()))
.withStyleName(WebThemes.MARGIN_LEFT_HALF, WebThemes.META_INFO);
}
private Component buildTicketStatusComp(ProjectTicket ticket) {
return ELabel.html(VaadinIcons.INFO_CIRCLE.getHtml() + " " + ticket.getStatus())
.withDescription(UserUIContext.getMessage(GenericI18Enum.FORM_STATUS)).withStyleName(WebThemes.MARGIN_LEFT_HALF, WebThemes.META_INFO);
}
private Component buildStartdateComp(ProjectTicket ticket) {
if (ticket.getStartDate() == null) {
Div divHint = new Div().setCSSClass("nonValue");
divHint.appendText(VaadinIcons.TIME_FORWARD.getHtml());
divHint.appendChild(new Span().appendText(UserUIContext.getMessage(GenericI18Enum.OPT_UNDEFINED)).setCSSClass("hide"));
return ELabel.html(divHint.write()).withDescription(UserUIContext.getMessage(GenericI18Enum.FORM_START_DATE))
.withStyleName(WebThemes.META_INFO, WebThemes.MARGIN_LEFT_HALF);
} else {
Div startDateDiv = new Div().appendText(String.format(" %s %s", VaadinIcons.TIME_FORWARD.getHtml(),
UserUIContext.formatDate(ticket.getStartDate())));
return ELabel.html(startDateDiv.write()).withDescription(UserUIContext.getMessage(GenericI18Enum.FORM_START_DATE))
.withStyleName(WebThemes.META_INFO, WebThemes.MARGIN_LEFT_HALF);
}
}
private Component buildEnddateComp(ProjectTicket ticket) {
if (ticket.getEndDate() == null) {
Div divHint = new Div().setCSSClass("nonValue");
divHint.appendText(VaadinIcons.TIME_BACKWARD.getHtml());
divHint.appendChild(new Span().appendText(UserUIContext.getMessage(GenericI18Enum.OPT_UNDEFINED)).setCSSClass("hide"));
return ELabel.html(divHint.write()).withDescription(UserUIContext.getMessage(GenericI18Enum.FORM_START_DATE))
.withStyleName(WebThemes.META_INFO, WebThemes.MARGIN_LEFT_HALF);
} else {
Div startDateDiv = new Div().appendText(String.format(" %s %s", VaadinIcons.TIME_BACKWARD.getHtml(),
UserUIContext.formatDate(ticket.getEndDate())));
return ELabel.html(startDateDiv.write()).withDescription(UserUIContext.getMessage(GenericI18Enum.FORM_END_DATE))
.withStyleName(WebThemes.META_INFO, WebThemes.MARGIN_LEFT_HALF);
}
}
private Component buildDuedateComp(ProjectTicket ticket) {
if (ticket.getDueDate() == null) {
Div divHint = new Div().setCSSClass("nonValue");
divHint.appendText(VaadinIcons.CLOCK.getHtml());
divHint.appendChild(new Span().appendText(UserUIContext.getMessage(GenericI18Enum.OPT_UNDEFINED)).setCSSClass("hide"));
return ELabel.html(divHint.write()).withDescription(UserUIContext.getMessage(GenericI18Enum.FORM_START_DATE))
.withStyleName(WebThemes.META_INFO, WebThemes.MARGIN_LEFT_HALF);
} else {
Div startDateDiv = new Div().appendText(String.format(" %s %s", VaadinIcons.CLOCK.getHtml(),
UserUIContext.formatDate(ticket.getDueDate())));
return ELabel.html(startDateDiv.write()).withDescription(UserUIContext.getMessage(GenericI18Enum.FORM_DUE_DATE))
.withStyleName(WebThemes.META_INFO, WebThemes.MARGIN_LEFT_HALF);
}
}
private Component buildBillableHoursComp(ProjectTicket ticket) {
return ELabel.html(VaadinIcons.MONEY.getHtml() + " " + NumberUtils.zeroIfNull(ticket.getBillableHours()))
.withDescription(UserUIContext.getMessage(TimeTrackingI18nEnum.OPT_BILLABLE_HOURS)).withStyleName(WebThemes.META_INFO, WebThemes.MARGIN_LEFT_HALF);
}
private Component buildNonBillableHoursComp(ProjectTicket ticket) {
return ELabel.html(VaadinIcons.GIFT.getHtml() + " " + NumberUtils.zeroIfNull(ticket.getNonBillableHours()))
.withDescription(UserUIContext.getMessage(TimeTrackingI18nEnum.OPT_NON_BILLABLE_HOURS)).withStyleName(WebThemes.META_INFO, WebThemes.MARGIN_LEFT_HALF);
}
}
|
package org.lpw.clivia.user;
import org.lpw.clivia.Permit;
import org.lpw.clivia.sms.SmsService;
import org.lpw.clivia.user.auth.AuthService;
import org.lpw.clivia.user.inviter.InviterService;
import org.lpw.photon.ctrl.context.Request;
import org.lpw.photon.ctrl.execute.Execute;
import org.lpw.photon.ctrl.template.Templates;
import org.lpw.photon.ctrl.validate.Validate;
import org.lpw.photon.ctrl.validate.Validators;
import org.lpw.photon.util.Message;
import org.springframework.stereotype.Controller;
import javax.inject.Inject;
@Controller(UserModel.NAME + ".ctrl")
@Execute(name = "/user/", key = UserModel.NAME, code = "151")
public class UserCtrl {
@Inject
private Message message;
@Inject
private Request request;
@Inject
private Templates templates;
@Inject
private SmsService smsService;
@Inject
private UserService userService;
@Inject
private InviterService inviterService;
@Execute(name = "inviter", permit = Permit.always)
public Object inviter() {
inviterService.set(request.get("code"));
return "";
}
@Execute(name = "sign-up-sms", permit = Permit.always, validates = {
@Validate(validator = Validators.MOBILE, parameter = "mobile", failureCode = 10) })
public Object signUpSms() {
return smsService.captcha(UserService.SMS_SIGN_UP, request.get("mobile"));
}
@Execute(name = "sign-up", permit = Permit.always, validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "uid", failureCode = 1),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "uid", failureCode = 2),
@Validate(validator = UserService.VALIDATOR_EXISTS_TYPE, parameter = "type", failureCode = 27),
@Validate(validator = UserService.VALIDATOR_PASSWORD, parameters = { "password",
"type" }, failureCode = 3),
@Validate(validator = UserService.VALIDATOR_SIGN_UP_ENABLE, failureCode = 99),
@Validate(validator = UserService.VALIDATOR_SIGN_UP_SMS, parameter = "sms", failureCode = 98),
@Validate(validator = AuthService.VALIDATOR_UID_NOT_EXISTS, parameters = { "uid", "password",
"type" }, failureCode = 4) })
public Object signUp() {
userService.signUp(request.get("uid"), request.get("password"), request.get("type"),
request.get("inviter"), request.get("grade"));
return sign();
}
@Execute(name = "sign-in-sms", permit = Permit.always, validates = {
@Validate(validator = Validators.MOBILE, parameter = "mobile", failureCode = 10) })
public Object signInSms() {
return smsService.captcha(UserService.SMS_SIGN_IN, request.get("mobile"));
}
@Execute(name = "sign-in", permit = Permit.always, validates = {
@Validate(validator = UserService.VALIDATOR_EXISTS_TYPE, parameter = "type", failureCode = 27),
@Validate(validator = UserService.VALIDATOR_PASSWORD, parameters = { "password",
"type" }, failureCode = 3),
@Validate(validator = UserService.VALIDATOR_SIGN_IN, parameters = { "uid", "password", "type",
"grade" }, failureCode = 6) })
public Object signIn() {
return sign();
}
@Execute(name = "sign-in-gesture", permit = Permit.always)
public Object signInGesture() {
return userService.signInGesture(request.get("id"), request.get("gesture")) ? ""
: templates.get().failure(151018, message.get(UserModel.NAME + ".gesture.failure"),
null, null);
}
@Execute(name = "sign", permit = Permit.always)
public Object sign() {
return userService.sign();
}
@Execute(name = "sign-out", permit = Permit.always)
public Object signOut() {
userService.signOut();
return "";
}
@Execute(name = "modify", permit = "0", validates = {
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "idcard", failureCode = 7),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "name", failureCode = 8),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "nick", failureCode = 9),
@Validate(validator = Validators.MOBILE, emptyable = true, parameter = "mobile", failureCode = 10),
@Validate(validator = Validators.EMAIL, emptyable = true, parameter = "email", failureCode = 11),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "email", failureCode = 12),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "weixin", failureCode = 33),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "qq", failureCode = 34),
@Validate(validator = Validators.BETWEEN, number = { 0,
2 }, parameter = "gender", failureCode = 13),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "avatar", failureCode = 32),
@Validate(validator = UserService.VALIDATOR_SIGN) })
public Object modify() {
userService.modify(request.setToModel(UserModel.class));
return sign();
}
@Execute(name = "password", permit = "0", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "new", failureCode = 14, failureArgKeys = {
UserModel.NAME + ".password.new" }),
@Validate(validator = Validators.NOT_EQUALS, parameters = { "old",
"new" }, failureCode = 15, failureArgKeys = { UserModel.NAME + ".password.new",
UserModel.NAME + ".password.old" }),
@Validate(validator = Validators.EQUALS, parameters = { "new",
"repeat" }, failureCode = 16, failureArgKeys = {
UserModel.NAME + ".password.repeat",
UserModel.NAME + ".password.new" }),
@Validate(validator = UserService.VALIDATOR_SIGN) })
public Object password() {
return userService.password(request.get("old"), request.get("new")) ? ""
: templates.get().failure(151017, message.get(UserModel.NAME + ".password.illegal"),
null, null);
}
@Execute(name = "gesture", permit = "0", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "new", failureCode = 14, failureArgKeys = {
UserModel.NAME + ".password.new" }),
@Validate(validator = Validators.NOT_EQUALS, parameters = { "old",
"new" }, failureCode = 15, failureArgKeys = { UserModel.NAME + ".password.new",
UserModel.NAME + ".password.old" }),
@Validate(validator = Validators.EQUALS, parameters = { "new",
"repeat" }, failureCode = 16, failureArgKeys = {
UserModel.NAME + ".password.repeat",
UserModel.NAME + ".password.new" }),
@Validate(validator = UserService.VALIDATOR_SIGN) })
public Object gesture() {
return userService.gesture(request.get("old"), request.get("new")) ? ""
: templates.get().failure(151018, message.get(UserModel.NAME + ".gesture.illegal"),
null, null);
}
@Execute(name = "gesture-off", permit = "0", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "gesture", failureCode = 14),
@Validate(validator = UserService.VALIDATOR_SIGN) })
public Object gestureOff() {
return userService.gestureOff(request.get("gesture")) ? ""
: templates.get().failure(151018, message.get(UserModel.NAME + ".gesture.illegal"),
null, null);
}
@Execute(name = "secret", permit = "0", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "new", failureCode = 14, failureArgKeys = {
UserModel.NAME + ".password.new" }),
@Validate(validator = Validators.NOT_EQUALS, parameters = { "old",
"new" }, failureCode = 15, failureArgKeys = { UserModel.NAME + ".password.new",
UserModel.NAME + ".password.old" }),
@Validate(validator = Validators.EQUALS, parameters = { "new",
"repeat" }, failureCode = 16, failureArgKeys = {
UserModel.NAME + ".password.repeat",
UserModel.NAME + ".password.new" }),
@Validate(validator = UserService.VALIDATOR_SIGN) })
public Object secret() {
return userService.secret(request.get("old"), request.get("new")) ? ""
: templates.get().failure(151018, message.get(UserModel.NAME + ".secret.illegal"), null,
null);
}
@Execute(name = "get", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "ids", failureCode = 21),
@Validate(validator = Validators.SIGN) })
public Object get() {
return userService.get(request.getAsArray("ids"));
}
@Execute(name = "find-by-code", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "code", failureCode = 26),
@Validate(validator = Validators.SIGN) })
public Object findByCode() {
return userService.findByCode(request.get("code"));
}
@Execute(name = "find-by-uid", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "uid", failureCode = 27),
@Validate(validator = Validators.SIGN),
@Validate(validator = AuthService.VALIDATOR_UID_EXISTS, parameter = "uid", failureCode = 28) })
public Object findByUid() {
return userService.findByUid(request.get("uid"));
}
@Execute(name = "find-sign", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "idUidCode", failureCode = 31),
@Validate(validator = Validators.SIGN) })
public Object findOrSign() {
return userService.findOrSign(request.get("idUidCode"));
}
@Execute(name = "find", permit = "0", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "idUidCode", failureCode = 31),
@Validate(validator = UserService.VALIDATOR_SIGN) })
public Object find() {
return userService.find(request.get("idUidCode"));
}
@Execute(name = "query", validates = {
@Validate(validator = Validators.MOBILE, emptyable = true, parameter = "mobile", failureCode = 10),
@Validate(validator = Validators.EMAIL, emptyable = true, parameter = "email", failureCode = 11),
@Validate(validator = Validators.SIGN) })
public Object query() {
return userService.query(request.get("uid"), request.get("idcard"), request.get("name"),
request.get("nick"), request.get("mobile"), request.get("email"), request.get("weixin"),
request.get("qq"), request.get("code"), request.getAsInt("minGrade", -1),
request.getAsInt("maxGrade", -1), request.getAsInt("state", -1),
request.get("register"), request.get("from"));
}
@Execute(name = "new", validates = {
@Validate(validator = Validators.NOT_EMPTY, parameter = "uid", failureCode = 1),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "uid", failureCode = 2),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "idcard", failureCode = 7),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "name", failureCode = 8),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "nick", failureCode = 9),
@Validate(validator = Validators.MOBILE, emptyable = true, parameter = "mobile", failureCode = 10),
@Validate(validator = Validators.EMAIL, emptyable = true, parameter = "email", failureCode = 11),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "email", failureCode = 12),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "weixin", failureCode = 33),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "qq", failureCode = 34),
@Validate(validator = Validators.BETWEEN, number = { 0,
2 }, parameter = "gender", failureCode = 13),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "avatar", failureCode = 32),
@Validate(validator = Validators.BETWEEN, number = { 0,
1 }, parameter = "state", failureCode = 24),
@Validate(validator = AuthService.VALIDATOR_UID_NOT_EXISTS, parameter = "uid", failureCode = 4) })
public Object create() {
userService.create(request.get("uid"), request.get("password"), request.get("idcard"),
request.get("name"), request.get("nick"), request.get("mobile"), request.get("email"),
request.get("weixin"), request.get("qq"), request.get("avatar"),
request.getAsInt("gender"), request.getAsSqlDate("birthday"), userService.id(),
request.getAsInt("grade"), request.getAsInt("state"));
return "";
}
@Execute(name = "update", validates = {
@Validate(validator = Validators.ID, parameter = "id", failureCode = 22),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "idcard", failureCode = 7),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "name", failureCode = 8),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "nick", failureCode = 9),
@Validate(validator = Validators.MOBILE, emptyable = true, parameter = "mobile", failureCode = 10),
@Validate(validator = Validators.EMAIL, emptyable = true, parameter = "email", failureCode = 11),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "email", failureCode = 12),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "weixin", failureCode = 33),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "qq", failureCode = 34),
@Validate(validator = Validators.BETWEEN, number = { 0,
2 }, parameter = "gender", failureCode = 13),
@Validate(validator = Validators.MAX_LENGTH, number = {
100 }, parameter = "avatar", failureCode = 32),
@Validate(validator = Validators.BETWEEN, number = { 0,
1 }, parameter = "state", failureCode = 24),
@Validate(validator = Validators.SIGN),
@Validate(validator = UserService.VALIDATOR_EXISTS, parameter = "id", failureCode = 25) })
public Object update() {
userService.update(request.setToModel(UserModel.class));
return "";
}
@Execute(name = "reset-password", validates = {
@Validate(validator = Validators.ID, parameter = "id", failureCode = 22),
@Validate(validator = Validators.SIGN),
@Validate(validator = UserService.VALIDATOR_EXISTS, parameter = "id", failureCode = 25) })
public Object resetPassword() {
String password = userService.resetPassword(request.get("id"));
return templates.get().success(password, UserModel.NAME + ".reset-password.success", password);
}
@Execute(name = "grade", validates = { @Validate(validator = Validators.ID, parameter = "id", failureCode = 22),
@Validate(validator = Validators.BETWEEN, number = { 0,
98 }, parameter = "grade", failureCode = 23),
@Validate(validator = Validators.SIGN),
@Validate(validator = UserService.VALIDATOR_EXISTS, parameter = "id", failureCode = 25) })
public Object grade() {
userService.grade(request.get("id"), request.getAsInt("grade"));
return "";
}
@Execute(name = "state", validates = { @Validate(validator = Validators.ID, parameter = "id", failureCode = 22),
@Validate(validator = Validators.BETWEEN, number = { 0,
1 }, parameter = "state", failureCode = 24),
@Validate(validator = Validators.SIGN),
@Validate(validator = UserService.VALIDATOR_EXISTS, parameter = "id", failureCode = 25) })
public Object state() {
userService.state(request.get("id"), request.getAsInt("state"));
return "";
}
@Execute(name = "count", validates = { @Validate(validator = Validators.SIGN) })
public Object count() {
return userService.count();
}
@Execute(name = "delete", validates = {
@Validate(validator = Validators.ID, parameter = "id", failureCode = 22),
@Validate(validator = Validators.SIGN),
@Validate(validator = UserService.VALIDATOR_EXISTS, parameter = "id", failureCode = 25) })
public Object delete() {
userService.delete(request.get("id"));
return "";
}
}
|
package com.ctrip.xpipe.redis.console.build;
import org.unidal.dal.jdbc.configuration.AbstractJdbcResourceConfigurator;
import org.unidal.lookup.configuration.Component;
import java.util.ArrayList;
import java.util.List;
final class FxxpipeDatabaseConfigurator extends AbstractJdbcResourceConfigurator {
@Override
public List<Component> defineComponents() {
List<Component> all = new ArrayList<Component>();
defineSimpleTableProviderComponents(all, "fxxpipe", com.ctrip.xpipe.redis.console.model._INDEX.getEntityClasses());
defineDaoComponents(all, com.ctrip.xpipe.redis.console.model._INDEX.getDaoClasses());
return all;
}
}
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.aws.greengrass.secretmanager.exception;
public class SecretCryptoException extends Exception {
public SecretCryptoException(String err) {
super(err);
}
public SecretCryptoException(Exception err) {
super(err);
}
public SecretCryptoException(String err, Exception e) {
super(err, e);
}
}
|
/*
* 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.tomcat.util.http.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
public class MediaType {
private final String type;
private final String subtype;
private final LinkedHashMap<String,String> parameters;
private final String charset;
private volatile String noCharset;
private volatile String withCharset;
protected MediaType(String type, String subtype, LinkedHashMap<String,String> parameters) {
this.type = type;
this.subtype = subtype;
this.parameters = parameters;
String cs = parameters.get("charset");
if (cs != null && cs.length() > 0 && cs.charAt(0) == '"') {
cs = HttpParser.unquote(cs);
}
this.charset = cs;
}
public String getType() {
return type;
}
public String getSubtype() {
return subtype;
}
public String getCharset() {
return charset;
}
public int getParameterCount() {
return parameters.size();
}
public String getParameterValue(String parameter) {
return parameters.get(parameter.toLowerCase(Locale.ENGLISH));
}
@Override
public String toString() {
if (withCharset == null) {
synchronized (this) {
if (withCharset == null) {
StringBuilder result = new StringBuilder();
result.append(type);
result.append('/');
result.append(subtype);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String value = entry.getValue();
if (value == null || value.length() == 0) {
continue;
}
result.append(';');
// Workaround for Adobe Read 9 plug-in on IE bug
// Can be removed after 26 June 2013 (EOL of Reader 9)
// See BZ 53814
result.append(' ');
result.append(entry.getKey());
result.append('=');
result.append(value);
}
withCharset = result.toString();
}
}
}
return withCharset;
}
public String toStringNoCharset() {
if (noCharset == null) {
synchronized (this) {
if (noCharset == null) {
StringBuilder result = new StringBuilder();
result.append(type);
result.append('/');
result.append(subtype);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (entry.getKey().equalsIgnoreCase("charset")) {
continue;
}
result.append(';');
// Workaround for Adobe Read 9 plug-in on IE bug
// Can be removed after 26 June 2013 (EOL of Reader 9)
// See BZ 53814
result.append(' ');
result.append(entry.getKey());
result.append('=');
result.append(entry.getValue());
}
noCharset = result.toString();
}
}
}
return noCharset;
}
/**
* Parses a MediaType value, either from a HTTP header or from an application.
*
* @param input a reader over the header text
* @return a MediaType parsed from the input, or null if not valid
* @throws IOException if there was a problem reading the input
*/
public static MediaType parseMediaType(StringReader input) throws IOException {
// Type (required)
String type = HttpParser.readToken(input);
if (type == null || type.length() == 0) {
return null;
}
if (HttpParser.skipConstant(input, "/") == SkipResult.NOT_FOUND) {
return null;
}
// Subtype (required)
String subtype = HttpParser.readToken(input);
if (subtype == null || subtype.length() == 0) {
return null;
}
LinkedHashMap<String,String> parameters = new LinkedHashMap<>();
SkipResult lookForSemiColon = HttpParser.skipConstant(input, ";");
if (lookForSemiColon == SkipResult.NOT_FOUND) {
return null;
}
while (lookForSemiColon == SkipResult.FOUND) {
String attribute = HttpParser.readToken(input);
String value = "";
if (HttpParser.skipConstant(input, "=") == SkipResult.FOUND) {
value = HttpParser.readTokenOrQuotedString(input, true);
}
if (attribute != null) {
parameters.put(attribute.toLowerCase(Locale.ENGLISH), value);
}
lookForSemiColon = HttpParser.skipConstant(input, ";");
if (lookForSemiColon == SkipResult.NOT_FOUND) {
return null;
}
}
return new MediaType(type, subtype, parameters);
}
}
|
/*
* 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.nifi.processors.flume;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.Sink;
import org.apache.flume.conf.Configurables;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.InputRequirement.Requirement;
import org.apache.nifi.annotation.behavior.Restricted;
import org.apache.nifi.annotation.behavior.Restriction;
import org.apache.nifi.annotation.behavior.TriggerSerially;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.annotation.lifecycle.OnStopped;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.RequiredPermission;
import org.apache.nifi.components.Validator;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.StandardValidators;
import java.util.List;
import java.util.Set;
/**
* This processor runs a Flume sink
*/
@TriggerSerially
@Tags({"flume", "hadoop", "put", "sink"})
@InputRequirement(Requirement.INPUT_REQUIRED)
@CapabilityDescription("Execute a Flume sink. Each input FlowFile is converted into a Flume Event for processing by the sink.")
@Restricted(
restrictions = {
@Restriction(
requiredPermission = RequiredPermission.EXECUTE_CODE,
explanation = "Provides operator the ability to execute arbitrary Flume configurations assuming all permissions that NiFi has.")
}
)
public class ExecuteFlumeSink extends AbstractFlumeProcessor {
public static final PropertyDescriptor SINK_TYPE = new PropertyDescriptor.Builder()
.name("Sink Type")
.description("The component type name for the sink. For some sinks, this is a short, symbolic name (e.g. hdfs)."
+ " For others, it's the fully-qualified name of the Sink class. See the Flume User Guide for details.")
.required(true)
.addValidator(createSinkValidator())
.build();
public static final PropertyDescriptor AGENT_NAME = new PropertyDescriptor.Builder()
.name("Agent Name")
.description("The name of the agent used in the Flume sink configuration")
.required(true)
.defaultValue("tier1")
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor SOURCE_NAME = new PropertyDescriptor.Builder()
.name("Sink Name")
.description("The name of the sink used in the Flume sink configuration")
.required(true)
.defaultValue("sink-1")
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor FLUME_CONFIG = new PropertyDescriptor.Builder()
.name("Flume Configuration")
.description("The Flume configuration for the sink copied from the flume.properties file")
.required(true)
.defaultValue("")
.addValidator(Validator.VALID)
.build();
public static final Relationship SUCCESS = new Relationship.Builder().name("success").build();
public static final Relationship FAILURE = new Relationship.Builder().name("failure").build();
private List<PropertyDescriptor> descriptors;
private Set<Relationship> relationships;
private volatile Sink sink;
private volatile NifiSinkSessionChannel channel;
@Override
protected void init(final ProcessorInitializationContext context) {
this.descriptors = ImmutableList.of(SINK_TYPE, AGENT_NAME, SOURCE_NAME, FLUME_CONFIG);
this.relationships = ImmutableSet.of(SUCCESS, FAILURE);
}
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return descriptors;
}
@Override
public Set<Relationship> getRelationships() {
return relationships;
}
@OnScheduled
public void onScheduled(final ProcessContext context) {
try {
channel = new NifiSinkSessionChannel(SUCCESS, FAILURE);
channel.start();
sink = SINK_FACTORY.create(context.getProperty(SOURCE_NAME).getValue(),
context.getProperty(SINK_TYPE).getValue());
sink.setChannel(channel);
String flumeConfig = context.getProperty(FLUME_CONFIG).getValue();
String agentName = context.getProperty(AGENT_NAME).getValue();
String sinkName = context.getProperty(SOURCE_NAME).getValue();
Configurables.configure(sink,
getFlumeSinkContext(flumeConfig, agentName, sinkName));
sink.start();
} catch (Throwable th) {
getLogger().error("Error creating sink", th);
throw Throwables.propagate(th);
}
}
@OnStopped
public void stopped() {
sink.stop();
channel.stop();
}
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
channel.setSession(session);
try {
sink.process();
} catch (EventDeliveryException ex) {
throw new ProcessException("Flume event delivery failed", ex);
}
}
}
|
package ramdan.file.bpp.geneva.mapping;
import ramdan.file.line.token.LineToken;
import ramdan.file.line.token.Tokens;
import ramdan.file.line.token.data.LineTokenData;
import ramdan.file.line.token.data.MultiLineData;
import java.util.ArrayList;
import java.util.List;
public class GenevaCapturePutEndHandler extends GenevaMappingHandler {
private String start;
private String end;
private boolean remove;
public GenevaCapturePutEndHandler(String start, String end, boolean remove) {
this.start = start;
this.end = end;
this.remove = remove;
}
private boolean capture;
private List<Tokens> listTokens = new ArrayList<>();
@Override
public Tokens process(LineToken lineToken) {
if(lineToken.isTagname(start)){
capture=true;
}
if(capture){
listTokens.add(lineToken);
if(lineToken.isTagname(end)){
capture=false;
}
if(remove){
return LineTokenData.REMOVE;
}
}
return super.process(lineToken);
}
@Override
protected void reset() {
super.reset();
capture=false;
listTokens = new ArrayList<>();
}
@Override
protected Tokens endTagHandle(LineToken lineToken) {
listTokens.add(super.endTagHandle(lineToken));
return MultiLineData.tokens(listTokens);
}
}
|
package com.plivo.api;
public class Plivo {
private static PlivoClient instance = null;
/**
* Initializes the global {@link PlivoClient} instance
*/
public static synchronized PlivoClient init(String authId, String authToken) {
instance = new PlivoClient(authId, authToken);
return instance;
}
/**
* Initializes the global {@link PlivoClient} instance, taking the authId and authToken from
* environment variables called PLIVO_AUTH_ID and PLIVO_AUTH_TOKEN.
*/
public static synchronized PlivoClient init() {
return init(System.getenv("PLIVO_AUTH_ID"), System.getenv("PLIVO_AUTH_TOKEN"));
}
public static PlivoClient getClient() {
return instance;
}
}
|
package WayofTime.alchemicalWizardry.common.items;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class ItemBloodRuneBlock extends ItemBlock
{
public ItemBloodRuneBlock(Block block)
{
super(block);
setHasSubtypes(true);
}
public String getUnlocalizedName(ItemStack itemstack)
{
String name;
switch (itemstack.getItemDamage())
{
case 0:
{
name = "blank";
break;
}
case 1:
{
name = "fill";
break;
}
case 2:
name = "empty";
break;
case 3:
name = "orb";
break;
case 4:
name = "betterCapacity";
break;
case 5:
name = "acceleration";
break;
default:
name = "broken";
}
return getUnlocalizedName() + "." + name;
}
public int getMetadata(int par1)
{
return par1;
}
}
|
/**
* Copyright 2009-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.
*/
package org.apache.ibatis.cache.decorators;
import java.util.Deque;
import java.util.LinkedList;
import org.apache.ibatis.cache.Cache;
/**
* FIFO 的有限缓存的队列
* 使用额外的 Linkedlist 保存
* FIFO (first in, first out) cache decorator.
*
* @author Clinton Begin
*/
public class FifoCache implements Cache {
/**
* 被装饰的 Cache
*/
private final Cache delegate;
/**
* key 保存队列
*/
private final Deque<Object> keyList;
/**
* 缓存能存放的最多的元素个数
*/
private int size;
public FifoCache(Cache delegate) {
this.delegate = delegate;
this.keyList = new LinkedList<>();
this.size = 1024;
}
@Override
public String getId() {
return delegate.getId();
}
@Override
public int getSize() {
return delegate.getSize();
}
public void setSize(int size) {
this.size = size;
}
@Override
public void putObject(Object key, Object value) {
// 放入的时候需要放到 map 与 list 中
cycleKeyList(key);
delegate.putObject(key, value);
}
@Override
public Object getObject(Object key) {
return delegate.getObject(key);
}
@Override
public Object removeObject(Object key) {
return delegate.removeObject(key);
}
@Override
public void clear() {
delegate.clear();
keyList.clear();
}
private void cycleKeyList(Object key) {
keyList.addLast(key);
// 如果超过了设置的最多的个数
if (keyList.size() > size) {
// 移除队头元素
Object oldestKey = keyList.removeFirst();
// delegate 缓存同样需要移除
delegate.removeObject(oldestKey);
}
}
}
|
package de.centerdevice.beanbouncer.handler;
public interface UnsafeInjectionHandler {
void handleUnsafeInjection(String beanName, String beanScope, String dependencyBeanName,
String dependencyBeanScope);
}
|
/*
* Copyright (C) 2019 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.tools.idea.uibuilder.palette;
import com.android.tools.idea.uibuilder.palette.Palette;
import com.intellij.openapi.util.Condition;
import com.intellij.ui.SpeedSearchComparator;
import org.jetbrains.annotations.NotNull;
/**
* A filter condition for implementing search in the palette.
*/
public class PatternFilter implements Condition<Palette.Item> {
private final SpeedSearchComparator myComparator;
private String myPattern;
public PatternFilter() {
myComparator = new SpeedSearchComparator(false);
myPattern = "";
}
public boolean setPattern(@NotNull String pattern) {
if (pattern.equals(myPattern)) {
return false;
}
myPattern = pattern;
return true;
}
@Override
public boolean value(@NotNull Palette.Item item) {
return myPattern.isEmpty() ||
myComparator.matchingFragments(myPattern, item.getTitle()) != null ||
!item.getTitle().equals(item.getTagName()) && myComparator.matchingFragments(myPattern, item.getTagName()) != null ||
item.getMetaTags().stream().anyMatch(meta -> myComparator.matchingFragments(myPattern, meta) != null);
}
public boolean hasPattern() {
return !myPattern.isEmpty();
}
}
|
package com.ghq.exception;
public class RepeatKillException extends SeckillException {
public RepeatKillException(String message) {
super(message);
}
public RepeatKillException(String message, Throwable cause) {
super(message, cause);
}
}
|
package elemental.combine.TD;
import android.app.Activity;
import android.os.Bundle;
public class About extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
}
}
|
/**
* Copyright 2009-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.builder;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import java.util.List;
import java.util.Properties;
public class ExampleObjectFactory extends DefaultObjectFactory {
private Properties properties;
@Override
public <T> T create(Class<T> type) {
return super.<T> create(type);
}
@Override
public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
return super.<T> create(type, constructorArgTypes, constructorArgs);
}
@Override
public void setProperties(Properties properties) {
super.setProperties(properties);
this.properties = properties;
}
public Properties getProperties() {
return properties;
}
}
|
/**
* Copyright 2009-2020 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.submitted.duplicate_resource_loaded;
import java.io.Reader;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.BaseDataTest;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class DuplicateResourceTest extends BaseDataTest {
@BeforeEach
void setup() throws Exception {
BaseDataTest.createBlogDataSource();
}
@Test
void shouldDemonstrateDuplicateResourceIssue() throws Exception {
final String resource = "org/apache/ibatis/submitted/duplicate_resource_loaded/Config.xml";
final Reader reader = Resources.getResourceAsReader(resource);
final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
final SqlSessionFactory factory = builder.build(reader);
try (SqlSession sqlSession = factory.openSession()) {
final Mapper mapper = sqlSession.getMapper(Mapper.class);
final List<Map<String, Object>> list = mapper.selectAllBlogs();
Assertions.assertEquals(2, list.size());
}
}
}
|
package it.castelli.connection.messages;
import it.castelli.connection.Connection;
import it.castelli.connection.ConnectionManager;
import it.castelli.connection.GameConnectionManager;
import it.castelli.gameLogic.GameManager;
import it.castelli.gameLogic.Player;
import it.castelli.gameLogic.contracts.Contract;
import it.castelli.serialization.Serializer;
/**
* Message that removes the mortgage from a given mortgage contract and removes a money amount equal to the cost of this operation from the owner (receive only)
*/
public class UnmortgageContractServerMessage implements Message
{
/**
* The game code
*/
private final int gameCode;
/**
* The contract to mortgage
*/
private final Contract contract;
/**
* Constructor for UnmortgageContractServerMessage (do not use)
*
* @param gameCode The game code
* @param contract The contract to mortgage
*/
public UnmortgageContractServerMessage(int gameCode, Contract contract)
{
this.gameCode = gameCode;
this.contract = contract;
}
@Override
public void onReceive(Connection connection, Player player)
{
GameConnectionManager gameConnectionManager = ConnectionManager.getInstance().getGames().get(gameCode);
GameManager gameManager = gameConnectionManager.getGameManager();
Contract contractToMortgage = gameManager.getSameContract(contract);
Player unmortgagingPlayer = gameManager.getSamePlayer(contractToMortgage.getOwner().toPlayer());
if (contractToMortgage.isMortgaged())
{
contractToMortgage.setMortgaged(false);
unmortgagingPlayer.removeMoney(contractToMortgage.getMortgageValue() + (int)(contractToMortgage.getMortgageValue() / 10));
}
else
{
connection.send(ServerMessages.GENERIC_MESSAGE_NAME, Serializer.toJson(new GenericServerMessage("Operazione negata", "Non potete sciogliere l'ipoteca da questa proprieta', poiche' non e' ipotecata!")));
}
gameConnectionManager.updatePlayers();
}
}
|
/*
* Copyright 2019-2021 workoss (https://www.workoss.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.workoss.boot.storage.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.util.HashMap;
import java.util.Map;
/**
* 混合配置
*
* @author workoss
*/
@ConfigurationProperties(prefix = MultiStorageClientConfig.PREFIX)
public class MultiStorageClientConfigProperties implements MultiStorageClientConfig {
private boolean enabled = true;
private boolean health = false;
private String defaultClientKey = DEFAULT_CLIENT_KEY;
/**
* 单个客户端配置
*/
@NestedConfigurationProperty
private StorageClientConfig defaultClient = new StorageClientConfig();
/**
* 多个客户端配置
*/
private Map<String, StorageClientConfig> clientConfigs = new HashMap<>();
@Override
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean isHealth() {
return health;
}
public void setHealth(boolean health) {
this.health = health;
}
@Override
public String getDefaultClientKey() {
return defaultClientKey;
}
public void setDefaultClientKey(String defaultClientKey) {
this.defaultClientKey = defaultClientKey;
}
@Override
public StorageClientConfig getDefaultClient() {
return defaultClient;
}
public void setDefaultClient(StorageClientConfig defaultClient) {
this.defaultClient = defaultClient;
}
@Override
public Map<String, StorageClientConfig> getClientConfigs() {
return clientConfigs;
}
public void setClientConfigs(Map<String, StorageClientConfig> clientConfigs) {
this.clientConfigs = clientConfigs;
}
}
|
public void setNext(ListNode next) {
this.next = next;
}
|
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.rest.api.user.authorized.apps.v1.dto;
import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
@ApiModel(description = "")
public class ErrorDTO {
@NotNull
private String code = null;
@NotNull
private String message = null;
private String description = null;
private String traceId = null;
/**
**/
@ApiModelProperty(required = true, value = "")
@JsonProperty("code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
/**
**/
@ApiModelProperty(required = true, value = "")
@JsonProperty("message")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("traceId")
public String getTraceId() {
return traceId;
}
public void setTraceId(String traceId) {
this.traceId = traceId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ErrorDTO {\n");
sb.append(" code: ").append(code).append("\n");
sb.append(" message: ").append(message).append("\n");
sb.append(" description: ").append(description).append("\n");
sb.append(" traceId: ").append(traceId).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
/*
* 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.hive.hcatalog.streaming;
public class ImpersonationFailed extends StreamingException {
public ImpersonationFailed(String username, Exception e) {
super("Failed to impersonate user " + username, e);
}
}
|
package org.apereo.cas.gua.impl;
import lombok.val;
import com.google.common.io.ByteSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apereo.cas.gua.api.UserGraphicalAuthenticationRepository;
import org.springframework.core.io.Resource;
import java.io.ByteArrayOutputStream;
/**
* This is {@link StaticUserGraphicalAuthenticationRepository}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
@RequiredArgsConstructor
@Slf4j
public class StaticUserGraphicalAuthenticationRepository implements UserGraphicalAuthenticationRepository {
private static final long serialVersionUID = 421732017215881244L;
private final transient Resource graphicResource;
@Override
public ByteSource getGraphics(final String username) {
try {
val bos = new ByteArrayOutputStream();
IOUtils.copy(this.graphicResource.getInputStream(), bos);
return ByteSource.wrap(bos.toByteArray());
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return ByteSource.empty();
}
}
|
//,temp,AssociateUcsProfileToBladeCmd.java,51,62,temp,AddUcsManagerCmd.java,58,70
//,3
public class xxx {
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
ResourceAllocationException, NetworkRuleConflictException {
try {
UcsManagerResponse rsp = mgr.addUcsManager(this);
rsp.setObjectName("ucsmanager");
rsp.setResponseName(getCommandName());
this.setResponseObject(rsp);
} catch (Exception e) {
s_logger.warn("Exception: ", e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
};
|
package com.amazon.spapi.documents;
import com.amazon.spapi.documents.impl.AESCryptoStreamFactory;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileNotFoundException;
import static org.junit.jupiter.api.Assertions.*;
class DownloadBundleTest {
private static String KEY = "sxx/wImF6BFndqSAz56O6vfiAh8iD9P297DHfFgujec=";
private static String VECTOR = "7S2tn363v0wfCfo1IX2Q1A==";
private DownloadBundle createBadFileBundle() throws Exception {
String contentType = "text/xml; charset=UTF-8";
CryptoStreamFactory cryptoStreamFactory = new AESCryptoStreamFactory.Builder(KEY, VECTOR).build();
File file = File.createTempFile("foo", null, null);
file.delete();
return new DownloadBundle(null, contentType, cryptoStreamFactory, file);
}
@Test
public void testNewInputStreamBadFile() throws Exception {
DownloadBundle downloadBundle = createBadFileBundle();
assertThrows(FileNotFoundException.class, () -> downloadBundle.newInputStream());
}
@Test
public void testNewReaderBadFile() throws Exception {
DownloadBundle downloadBundle = createBadFileBundle();
assertThrows(FileNotFoundException.class, () -> downloadBundle.newBufferedReader());
}
}
|
package ajin.mall.sys.goods.controller;
import ajin.mall.common.base.anno.RepeatSubmit;
import ajin.mall.common.base.result.BaseResult;
import ajin.mall.common.base.result.ResultEnum;
import ajin.mall.common.base.result.ResultPage;
import ajin.mall.sys.goods.form.LabelAddForm;
import ajin.mall.sys.goods.form.LabelListForm;
import ajin.mall.sys.goods.form.LabelUpdateForm;
import ajin.mall.sys.goods.service.LabelService;
import ajin.mall.sys.goods.view.LabelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* <p>
* 商品标签表 前端控制器
* </p>
*
* @author Ajin
* @since 2021-04-13
*/
@RestController
@RequestMapping("/label")
@CrossOrigin
@Api(tags = "商品标签")
public class LabelController {
@Resource
private LabelService labelService;
@RepeatSubmit
@PostMapping
@ApiOperation("添加商品标签")
public BaseResult<String> add(@RequestBody @Validated LabelAddForm labelAddForm) {
labelService.add(labelAddForm);
return new BaseResult<>(ResultEnum.ADD_OK);
}
@RepeatSubmit
@DeleteMapping("/{id}")
@ApiOperation(value = "删除商品标签", notes = "根据主键id删除")
public BaseResult<String> delete(@PathVariable("id") Long id) {
labelService.delete(id);
return new BaseResult<>(ResultEnum.DELETE_OK);
}
@RepeatSubmit
@PutMapping
@ApiOperation(value = "修改商品标签", notes = "根据主键id修改")
public BaseResult<String> update(@RequestBody @Validated LabelUpdateForm labelUpdateForm) {
labelService.update(labelUpdateForm);
return new BaseResult<>(ResultEnum.UPDATE_OK);
}
@GetMapping("/{id}")
@ApiOperation("根据id查询商品标签")
public BaseResult<LabelView> get(@PathVariable("id") Long id) {
LabelView result = labelService.get(id);
return new BaseResult<>(ResultEnum.GET_OK, result);
}
@PostMapping("/list")
@ApiOperation("根据条件查询商品标签")
public BaseResult<ResultPage<LabelView>> list(@RequestBody LabelListForm labelListForm) {
ResultPage<LabelView> result = labelService.list(labelListForm);
return new BaseResult<>(ResultEnum.GET_OK, result);
}
}
|
package com.imooc.repository;
import com.imooc.dataobject.OrderMaster;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @ Author :焦康
* @ Date :Created in 20:50 2018/12/3
* 订单
*/
public interface OrderMasterRepository extends JpaRepository<OrderMaster,String> {
// 根据openid查询订单
Page<OrderMaster> findByBuyerOpenid(String BuyerOpenid, Pageable pageable);
}
|
package androidx.appcompat.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.ActionMode.Callback;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.AutoCompleteTextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import androidx.appcompat.R;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.view.TintableBackgroundView;
import androidx.core.widget.TextViewCompat;
public class AppCompatAutoCompleteTextView extends AutoCompleteTextView implements TintableBackgroundView {
private static final int[] TINT_ATTRS = {16843126};
private final AppCompatBackgroundHelper mBackgroundTintHelper;
private final AppCompatTextHelper mTextHelper;
public AppCompatAutoCompleteTextView(Context context) {
this(context, null);
}
public AppCompatAutoCompleteTextView(Context context, AttributeSet attributeSet) {
this(context, attributeSet, R.attr.autoCompleteTextViewStyle);
}
public AppCompatAutoCompleteTextView(Context context, AttributeSet attributeSet, int i) {
super(TintContextWrapper.wrap(context), attributeSet, i);
TintTypedArray obtainStyledAttributes = TintTypedArray.obtainStyledAttributes(getContext(), attributeSet, TINT_ATTRS, i, 0);
if (obtainStyledAttributes.hasValue(0)) {
setDropDownBackgroundDrawable(obtainStyledAttributes.getDrawable(0));
}
obtainStyledAttributes.recycle();
this.mBackgroundTintHelper = new AppCompatBackgroundHelper(this);
this.mBackgroundTintHelper.loadFromAttributes(attributeSet, i);
this.mTextHelper = new AppCompatTextHelper(this);
this.mTextHelper.loadFromAttributes(attributeSet, i);
this.mTextHelper.applyCompoundDrawablesTints();
}
public void setDropDownBackgroundResource(@DrawableRes int i) {
setDropDownBackgroundDrawable(AppCompatResources.getDrawable(getContext(), i));
}
public void setBackgroundResource(@DrawableRes int i) {
super.setBackgroundResource(i);
AppCompatBackgroundHelper appCompatBackgroundHelper = this.mBackgroundTintHelper;
if (appCompatBackgroundHelper != null) {
appCompatBackgroundHelper.onSetBackgroundResource(i);
}
}
public void setBackgroundDrawable(Drawable drawable) {
super.setBackgroundDrawable(drawable);
AppCompatBackgroundHelper appCompatBackgroundHelper = this.mBackgroundTintHelper;
if (appCompatBackgroundHelper != null) {
appCompatBackgroundHelper.onSetBackgroundDrawable(drawable);
}
}
@RestrictTo({Scope.LIBRARY_GROUP_PREFIX})
public void setSupportBackgroundTintList(@Nullable ColorStateList colorStateList) {
AppCompatBackgroundHelper appCompatBackgroundHelper = this.mBackgroundTintHelper;
if (appCompatBackgroundHelper != null) {
appCompatBackgroundHelper.setSupportBackgroundTintList(colorStateList);
}
}
@Nullable
@RestrictTo({Scope.LIBRARY_GROUP_PREFIX})
public ColorStateList getSupportBackgroundTintList() {
AppCompatBackgroundHelper appCompatBackgroundHelper = this.mBackgroundTintHelper;
if (appCompatBackgroundHelper != null) {
return appCompatBackgroundHelper.getSupportBackgroundTintList();
}
return null;
}
@RestrictTo({Scope.LIBRARY_GROUP_PREFIX})
public void setSupportBackgroundTintMode(@Nullable Mode mode) {
AppCompatBackgroundHelper appCompatBackgroundHelper = this.mBackgroundTintHelper;
if (appCompatBackgroundHelper != null) {
appCompatBackgroundHelper.setSupportBackgroundTintMode(mode);
}
}
@Nullable
@RestrictTo({Scope.LIBRARY_GROUP_PREFIX})
public Mode getSupportBackgroundTintMode() {
AppCompatBackgroundHelper appCompatBackgroundHelper = this.mBackgroundTintHelper;
if (appCompatBackgroundHelper != null) {
return appCompatBackgroundHelper.getSupportBackgroundTintMode();
}
return null;
}
/* access modifiers changed from: protected */
public void drawableStateChanged() {
super.drawableStateChanged();
AppCompatBackgroundHelper appCompatBackgroundHelper = this.mBackgroundTintHelper;
if (appCompatBackgroundHelper != null) {
appCompatBackgroundHelper.applySupportBackgroundTint();
}
AppCompatTextHelper appCompatTextHelper = this.mTextHelper;
if (appCompatTextHelper != null) {
appCompatTextHelper.applyCompoundDrawablesTints();
}
}
public void setTextAppearance(Context context, int i) {
super.setTextAppearance(context, i);
AppCompatTextHelper appCompatTextHelper = this.mTextHelper;
if (appCompatTextHelper != null) {
appCompatTextHelper.onSetTextAppearance(context, i);
}
}
public InputConnection onCreateInputConnection(EditorInfo editorInfo) {
return AppCompatHintHelper.onCreateInputConnection(super.onCreateInputConnection(editorInfo), editorInfo, this);
}
public void setCustomSelectionActionModeCallback(Callback callback) {
super.setCustomSelectionActionModeCallback(TextViewCompat.wrapCustomSelectionActionModeCallback(this, callback));
}
}
|
package engineer.vel.projects.enrollmentsystem.core.dto;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import engineer.vel.projects.enrollmentsystem.repository.entity.CourseClass;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* A Data Transformation Object for {@link CourseClass}.
*
* @author Vadivel Murugesan
*
*/
@Getter
@Setter
@NoArgsConstructor
@ToString
public class CourseClassDto {
@Schema(description = "Name of the Class.", example = "classA", required = true)
@NotEmpty(message = "{add.courseclass.name.notempty}")
private String name;
@Schema(description = "Fixed Credit/Unit of the Class. Some harder classes be 4 credits while easier one could 2 or 3 credits.", example = "4", required = true)
@NotNull(message = "{add.courseclass.credit.notnull}")
@Max(value = 4, message = "{add.courseclass.credit.max}")
private Integer credit;
}
|
/*
* The MIT License (MIT) Copyright (c) 2020-2021 artipie.com
* https://github.com/artipie/cargo-adapter/LICENSE
*/
package com.artipie.cargo.meta;
import com.artipie.asto.ArtipieIOException;
import com.artipie.asto.misc.UncheckedIOConsumer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.function.BiConsumer;
/**
* Merge new package metadata into optionally existing metadata file.
* @since 0.1
*/
public final class MetadataMerge implements BiConsumer<Optional<InputStream>, OutputStream> {
/**
* String metadata to add.
*/
private final String add;
/**
* Ctor.
* @param add String metadata to add
*/
public MetadataMerge(final String add) {
this.add = add;
}
@Override
@SuppressWarnings("PMD.AssignmentInOperand")
public void accept(final Optional<InputStream> input, final OutputStream output) {
try {
if (input.isPresent()) {
// @checkstyle MagicNumberCheck (1 line)
final byte[] buffer = new byte[4 * 1024];
int len;
while ((len = input.get().read(buffer)) > 0) {
output.write(buffer, 0, len);
}
output.write("\n".getBytes(StandardCharsets.UTF_8));
}
output.write(this.add.getBytes(StandardCharsets.UTF_8));
} catch (final IOException err) {
throw new ArtipieIOException(err);
} finally {
Optional.of(output).ifPresent(new UncheckedIOConsumer<>(OutputStream::close));
input.ifPresent(new UncheckedIOConsumer<>(InputStream::close));
}
}
}
|
package com.boot.service;
import com.boot.pojo.Product;
import org.elasticsearch.search.SearchHit;
import java.io.IOException;
import java.util.List;
/**
* @author 游政杰
*/
public interface SearchService {
void initSearch() throws IOException, InterruptedException;
SearchHit[] searchProductHitByName(String text,String ip) throws IOException;
List<Product> searchProductByHit(String text,SearchHit[] searchHits,String ip) throws IOException;
//查询所有数据并分页
List<Product> searchAllProductByLimit(int from,int size) throws IOException;
//from size 为分页
List<Product> searchProductsByCondition(String text,long brandid,long classifyid,int from,int size,String ip) throws IOException;
long searchAllProductsCount() throws IOException;
//根据商品名搜索商品集合并且分页
List<Product> searchProductsByNameAndLimit(int from , int size ,String text) throws IOException;
//根据商品名搜索商品的目标数
long searchProductCountByName(String text) throws IOException;
//修改商品
void updateProduct(Product product) throws IOException;
//删除商品
void deleteProduct(long productid) throws IOException;
//批量删除商品
void batchDeleteProcts(long[] ids) throws IOException;
}
|
package org.broadinstitute.hellbender.tools.spark.sv.utils;
import com.esotericsoftware.kryo.DefaultSerializer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.broadinstitute.hellbender.utils.Utils;
import scala.Tuple2;
import java.util.Collections;
import java.util.Iterator;
import java.util.stream.Collectors;
@DefaultSerializer(PairedStrandedIntervalTree.Serializer.class)
public class PairedStrandedIntervalTree<V> implements Iterable<Tuple2<PairedStrandedIntervals, V>> {
private SVIntervalTree<Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean,V>>>> leftEnds = new SVIntervalTree<>();
public PairedStrandedIntervalTree() {}
@SuppressWarnings("unchecked")
public PairedStrandedIntervalTree(final Kryo kryo, final Input input) {
leftEnds = (SVIntervalTree<Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean, V>>>>) kryo.readClassAndObject(input);
}
public boolean put(PairedStrandedIntervals pair, V value) {
if (contains(pair)) return false;
final SVIntervalTree.Entry<Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean,V>>>> leftEntry = leftEnds.find(pair.getLeft().getInterval());
if (leftEntry != null) {
leftEntry.getValue()._2().put(pair.getRight().getInterval(), new Tuple2<>(pair.getRight().getStrand(), value));
} else {
final SVIntervalTree<Tuple2<Boolean, V>> rightEnds = new SVIntervalTree<>();
rightEnds.put(pair.getRight().getInterval(), new Tuple2<>(pair.getRight().getStrand(), value));
leftEnds.put(pair.getLeft().getInterval(), new Tuple2<>(pair.getLeft().getStrand(), rightEnds));
}
return true;
}
public int size() {
return Utils.stream(leftEnds).mapToInt(e -> e.getValue()._2.size()).sum();
}
public final class PairedStrandedIntervalTreeOverlapperIterator implements Iterator<Tuple2<PairedStrandedIntervals, V>> {
private Iterator<SVIntervalTree.Entry<Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean, V>>>>> leftOverlappers;
private Iterator<SVIntervalTree.Entry<Tuple2<Boolean, V>>> rightOverlappers;
private SVIntervalTree.Entry<Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean, V>>>> leftEntry;
private SVIntervalTree.Entry<Tuple2<Boolean, V>> rightEntry;
private final PairedStrandedIntervals query;
public PairedStrandedIntervalTreeOverlapperIterator(PairedStrandedIntervalTree<V> tree, PairedStrandedIntervals query) {
this.query = query;
leftOverlappers = tree.leftEnds.overlappers(query.getLeft().getInterval());
}
private void advance(PairedStrandedIntervals query) {
leftEntry = null;
rightEntry = null;
while (leftOverlappers.hasNext()) {
leftEntry = leftOverlappers.next();
if (! leftEntry.getValue()._1() == query.getLeft().getStrand()) {
continue;
}
rightOverlappers = leftEntry.getValue()._2().overlappers(query.getRight().getInterval());
while (rightOverlappers.hasNext()) {
rightEntry = rightOverlappers.next();
if (! rightEntry.getValue()._1() == query.getRight().getStrand()) {
continue;
}
return;
}
}
rightEntry = null;
}
@Override
public boolean hasNext() {
advance(query);
return leftEntry != null && rightEntry != null;
}
@Override
public Tuple2<PairedStrandedIntervals, V> next() {
Tuple2<PairedStrandedIntervals, V> nextVal = new Tuple2<>(
new PairedStrandedIntervals(
new StrandedInterval(leftEntry.getInterval(),
leftEntry.getValue()._1()),
new StrandedInterval(rightEntry.getInterval(),
rightEntry.getValue()._1())),
rightEntry.getValue()._2);
return nextVal;
}
@Override
public void remove() {
rightOverlappers.remove();
if (leftEntry.getValue()._2().size() == 0) {
leftOverlappers.remove();
}
}
}
public Iterator<Tuple2<PairedStrandedIntervals,V>> overlappers(PairedStrandedIntervals pair) {
return new PairedStrandedIntervalTreeOverlapperIterator(this, pair);
}
public final class PairedStrandedIntervalTreeIterator implements Iterator<Tuple2<PairedStrandedIntervals, V>> {
private final Iterator<SVIntervalTree.Entry<Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean, V>>>>> leftEndIterator;
private Iterator<SVIntervalTree.Entry<Tuple2<Boolean, V>>> rightEndIterator;
private SVIntervalTree.Entry<Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean, V>>>> leftEntry;
PairedStrandedIntervalTreeIterator(PairedStrandedIntervalTree<V> tree) {
leftEndIterator = tree.leftEnds.iterator();
if (leftEndIterator.hasNext()) {
leftEntry = leftEndIterator.next();
rightEndIterator = leftEntry.getValue()._2().iterator();
} else {
leftEntry = null;
rightEndIterator = Collections.emptyIterator();
}
}
@Override
public boolean hasNext() {
return rightEndIterator.hasNext() || leftEndIterator.hasNext();
}
@Override
public Tuple2<PairedStrandedIntervals, V> next() {
SVIntervalTree.Entry<Tuple2<Boolean, V>> rightEntry;
if (!rightEndIterator.hasNext()) {
leftEntry = leftEndIterator.next();
rightEndIterator = leftEntry.getValue()._2().iterator();
}
rightEntry = rightEndIterator.next();
return new Tuple2<>(new PairedStrandedIntervals(
new StrandedInterval(leftEntry.getInterval(),
leftEntry.getValue()._1()),
new StrandedInterval(rightEntry.getInterval(),
rightEntry.getValue()._1())),
rightEntry.getValue()._2());
}
@Override
public void remove() {
rightEndIterator.remove();
if (leftEntry.getValue()._2().size() == 0) {
leftEndIterator.remove();
}
}
}
public Iterator<Tuple2<PairedStrandedIntervals, V>> iterator() {
return new PairedStrandedIntervalTreeIterator(this);
}
public boolean contains(PairedStrandedIntervals pair) {
final int leftEndIndex = leftEnds.getIndex(pair.getLeft().getInterval());
if (leftEndIndex == -1) return false;
final SVIntervalTree.Entry<Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean, V>>>> leftEndEntry = leftEnds.findByIndex(leftEndIndex);
final Tuple2<Boolean, SVIntervalTree<Tuple2<Boolean, V>>> storedValue = leftEndEntry.getValue();
if (pair.getLeft().getStrand() != storedValue._1()) return false;
final SVIntervalTree<Tuple2<Boolean, V>> rightEnds = storedValue._2();
final int rightIndex = rightEnds.getIndex(pair.getRight().getInterval());
return rightIndex != -1 && (pair.getRight().getStrand() == rightEnds.findByIndex(rightIndex).getValue()._1());
}
public static final class Serializer<T> extends com.esotericsoftware.kryo.Serializer<PairedStrandedIntervalTree<T>> {
@Override
public void write(final Kryo kryo, final Output output, final PairedStrandedIntervalTree<T> tree ) {
tree.serialize(kryo, output);
}
@Override
public PairedStrandedIntervalTree<T> read(final Kryo kryo, final Input input, final Class<PairedStrandedIntervalTree<T>> klass ) {
return new PairedStrandedIntervalTree<>(kryo, input);
}
}
private void serialize(final Kryo kryo, final Output output) {
kryo.writeClassAndObject(output, this);
}
}
|
import java.util.Arrays;
public class Solution3 {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
if (dp[amount] == amount + 1) {
dp[amount] = -1;
}
return dp[amount];
}
public static void main(String[] args) {
Solution3 solution3 = new Solution3();
int[] coins = {2};
int amount = 3;
int res = solution3.coinChange(coins, amount);
System.out.println(res);
}
}
|
/**
* Copyright 2009-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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.type;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
class ByteTypeHandlerTest extends BaseTypeHandlerTest {
private static final TypeHandler<Byte> TYPE_HANDLER = new ByteTypeHandler();
@Override
@Test
public void shouldSetParameter() throws Exception {
TYPE_HANDLER.setParameter(ps, 1, (byte) 100, null);
verify(ps).setByte(1, (byte) 100);
}
@Override
@Test
public void shouldGetResultFromResultSetByName() throws Exception {
when(rs.getByte("column")).thenReturn((byte) 100, (byte) 0);
assertEquals(Byte.valueOf((byte) 100), TYPE_HANDLER.getResult(rs, "column"));
assertEquals(Byte.valueOf((byte) 0), TYPE_HANDLER.getResult(rs, "column"));
}
@Override
@Test
public void shouldGetResultNullFromResultSetByName() throws Exception {
when(rs.getByte("column")).thenReturn((byte) 0);
when(rs.wasNull()).thenReturn(true);
assertNull(TYPE_HANDLER.getResult(rs, "column"));
}
@Override
@Test
public void shouldGetResultFromResultSetByPosition() throws Exception {
when(rs.getByte(1)).thenReturn((byte) 100, (byte) 0);
assertEquals(Byte.valueOf((byte) 100), TYPE_HANDLER.getResult(rs, 1));
assertEquals(Byte.valueOf((byte) 0), TYPE_HANDLER.getResult(rs, 1));
}
@Override
@Test
public void shouldGetResultNullFromResultSetByPosition() throws Exception {
when(rs.getByte(1)).thenReturn((byte) 0);
when(rs.wasNull()).thenReturn(true);
assertNull(TYPE_HANDLER.getResult(rs, 1));
}
@Override
@Test
public void shouldGetResultFromCallableStatement() throws Exception {
when(cs.getByte(1)).thenReturn((byte) 100, (byte) 0);
assertEquals(Byte.valueOf((byte) 100), TYPE_HANDLER.getResult(cs, 1));
assertEquals(Byte.valueOf((byte) 0), TYPE_HANDLER.getResult(cs, 1));
}
@Override
@Test
public void shouldGetResultNullFromCallableStatement() throws Exception {
when(cs.getByte(1)).thenReturn((byte) 0);
when(cs.wasNull()).thenReturn(true);
assertNull(TYPE_HANDLER.getResult(cs, 1));
}
}
|
/*
* 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.oodt.cas.resource.util;
/**
* @author mattmann
* @version $Revision$
*
* <p>
* Metadata keys to describe the output
* of the ulimit call.
* </p>.
*/
public interface UlimitMetKeys {
String CORE_FILE_SIZE = "core file size";
String DATA_SEGMENT_SIZE = "data seg size";
String FILE_SIZE = "file size";
String MAX_LOCKED_MEMORY = "max locked memory";
String MAX_MEMORY_SIZE = "max memory size";
String MAX_OPEN_FILES = "open files";
String MAX_PIPE_SIZE = "pipe size";
String MAX_STACK_SIZE = "stack size";
String MAX_CPU_TIME = "cpu time";
String MAX_USER_PROCESSES = "max user processes";
String MAX_VIRTUAL_MEMORY = "virtual memory";
}
|
package com.portalmgr.common;
public class Pager {
private int isPage=1; //是否分页
private int page=1;
private int pageSize=10;
private int beginRow=0;
public int getPage() {
return page;
}
public int getIsPage() {
return isPage;
}
public void setIsPage(int isPage) {
this.isPage = isPage;
}
public void setPage(int page) {
this.page = page;
this.beginRow=this.pageSize*(page-1);
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
this.beginRow=pageSize*(this.page-1);
}
public int getBeginRow() {
return beginRow;
}
public void setBeginRow(int beginRow) {
this.beginRow = beginRow;
}
}
|
/*
Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this
program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package testsuite.fabric.jdbc;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.fabric.jdbc.FabricMySQLConnection;
import com.mysql.fabric.jdbc.FabricMySQLDataSource;
import testsuite.fabric.BaseFabricTestCase;
/**
* @todo this hash sharding test is incompatible with the
* default Fabric configuration for these C/J Fabric tests.
*/
public class TestHashSharding extends BaseFabricTestCase {
private FabricMySQLDataSource ds;
private FabricMySQLConnection conn;
public TestHashSharding() throws Exception {
super();
if (this.isSetForFabricTest) {
this.ds = getNewDefaultDataSource();
}
}
@Override
public void setUp() throws Exception {
if (this.isSetForFabricTest) {
this.conn = (FabricMySQLConnection) this.ds.getConnection(this.username, this.password);
// create table globally
this.conn.setServerGroupName("fabric_test1_global");
Statement stmt = this.conn.createStatement();
stmt.executeUpdate("drop table if exists employees");
stmt.executeUpdate("create table employees (emp_no INT PRIMARY KEY, first_name CHAR(40), last_name CHAR(40))");
this.conn.clearServerSelectionCriteria();
}
}
@Override
public void tearDown() throws Exception {
if (this.isSetForFabricTest) {
this.conn.close();
}
}
/**
* Run the given query and assert that the result contains at
* least one row.
*/
protected void checkRowExists(String sql) throws Exception {
Statement s = this.conn.createStatement();
ResultSet rs = s.executeQuery(sql);
assertTrue("Row should exist", rs.next());
rs.close();
s.close();
}
/**
* Run the given query and assert that the result set is empty.
*/
protected void checkRowDoesntExist(String sql) throws Exception {
Statement s = this.conn.createStatement();
ResultSet rs = s.executeQuery(sql);
assertFalse("Row should not exist", rs.next());
rs.close();
s.close();
}
/**
* Assert that a row exists in the given server group.
*/
protected void checkRowExistsInServerGroup(String sql, String groupName) throws Exception {
this.conn.clearServerSelectionCriteria();
this.conn.setServerGroupName(groupName);
checkRowExists(sql);
}
/**
* Assert that a row exists in the given shard determined by the key.
*/
protected void checkRowExistsInKeyGroup(String sql, String key) throws Exception {
this.conn.setShardKey(key);
checkRowExists(sql);
}
/**
* Assert that no row exists in the given server group.
*/
protected void checkRowDoesntExistInServerGroup(String sql, String groupName) throws Exception {
this.conn.clearServerSelectionCriteria();
this.conn.setServerGroupName(groupName);
checkRowDoesntExist(sql);
}
/**
* Assert that no row exists in the given shard determined by the key.
*/
public void checkRowDoesntExistInKeyGroup(String sql, String key) throws Exception {
this.conn.setShardKey(key);
checkRowDoesntExist(sql);
}
/**
* Check data used by basic tests is in proper groups.
* Test both by direct group selection and shard table/key selection.
*/
protected void assertBasicDataIsInProperPlaces() throws Exception {
String sql;
sql = "select * from employees where emp_no = 1";
checkRowExistsInServerGroup(sql, "fabric_test1_shard2");
checkRowDoesntExistInServerGroup(sql, "fabric_test1_shard1");
this.conn.clearServerSelectionCriteria();
this.conn.setShardTable("employees");
checkRowExistsInKeyGroup(sql, "1");
checkRowDoesntExistInKeyGroup(sql, "9");
sql = "select * from employees where emp_no = 6"; // repeat with key = 6
checkRowExistsInServerGroup(sql, "fabric_test1_shard2");
checkRowDoesntExistInServerGroup(sql, "fabric_test1_shard1");
this.conn.clearServerSelectionCriteria();
this.conn.setShardTable("employees");
checkRowExistsInKeyGroup(sql, "6");
checkRowDoesntExistInKeyGroup(sql, "19");
sql = "select * from employees where emp_no = 9"; // other shard
checkRowExistsInServerGroup(sql, "fabric_test1_shard1");
checkRowDoesntExistInServerGroup(sql, "fabric_test1_shard2");
this.conn.clearServerSelectionCriteria();
this.conn.setShardTable("employees");
checkRowExistsInKeyGroup(sql, "9");
checkRowDoesntExistInKeyGroup(sql, "6");
sql = "select * from employees where emp_no = 19"; // repeat with key = 19
checkRowExistsInServerGroup(sql, "fabric_test1_shard1");
checkRowDoesntExistInServerGroup(sql, "fabric_test1_shard2");
this.conn.clearServerSelectionCriteria();
this.conn.setShardTable("employees");
checkRowExistsInKeyGroup(sql, "19");
checkRowDoesntExistInKeyGroup(sql, "1");
}
/**
* Basic tests for shard selection with a HASH shard mapping.
*/
public void testBasicInsertByGroup() throws Exception {
if (!this.isSetForFabricTest) {
return;
}
Statement stmt;
// insert data directly by group selection
this.conn.setServerGroupName("fabric_test1_shard2");
stmt = this.conn.createStatement();
stmt.executeUpdate("insert into employees values (1, 'William', 'Gisbon')");
stmt.executeUpdate("insert into employees values (6, 'Samuel', 'Delany')");
this.conn.setServerGroupName("fabric_test1_shard1");
stmt.executeUpdate("insert into employees values (9, 'William', 'Turner')");
stmt.executeUpdate("insert into employees values (19, 'Albrecht', 'Durer')");
// check everything is where it should be
assertBasicDataIsInProperPlaces();
}
/**
* Basic tests for shard selection with a HASH shard mapping.
*/
public void testBasicInsertByKey() throws Exception {
if (!this.isSetForFabricTest) {
return;
}
Statement stmt;
// insert data using shard selection
this.conn.clearServerSelectionCriteria();
this.conn.setShardTable("employees");
stmt = this.conn.createStatement();
this.conn.setShardKey("1"); // hash = c4ca4238a0b923820dcc509a6f75849b
assertEquals("fabric_test1_shard2", this.conn.getCurrentServerGroup().getName());
stmt.executeUpdate("insert into employees values (1, 'William', 'Gisbon')");
this.conn.setShardKey("6"); // hash = 1679091c5a880faf6fb5e6087eb1b2dc
assertEquals("fabric_test1_shard2", this.conn.getCurrentServerGroup().getName());
stmt.executeUpdate("insert into employees values (6, 'Samuel', 'Delany')");
this.conn.setShardKey("9"); // hash = 45c48cce2e2d7fbdea1afc51c7c6ad26
assertEquals("fabric_test1_shard1", this.conn.getCurrentServerGroup().getName());
stmt.executeUpdate("insert into employees values (9, 'William', 'Turner')");
this.conn.setShardKey("19"); // hash = 1f0e3dad99908345f7439f8ffabdffc4
assertEquals("fabric_test1_shard1", this.conn.getCurrentServerGroup().getName());
stmt.executeUpdate("insert into employees values (19, 'Albrecht', 'Durer')");
// check everything is where it should be
assertBasicDataIsInProperPlaces();
}
}
|
/*
* 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.alibaba.ververica.cdc.connectors.postgres.table;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.connector.source.DynamicTableSource;
import org.apache.flink.table.factories.DynamicTableFactory;
import org.apache.flink.table.factories.DynamicTableSourceFactory;
import org.apache.flink.table.factories.FactoryUtil;
import org.apache.flink.table.utils.TableSchemaUtils;
import java.util.HashSet;
import java.util.Set;
import static com.alibaba.ververica.cdc.debezium.table.DebeziumOptions.DEBEZIUM_OPTIONS_PREFIX;
import static com.alibaba.ververica.cdc.debezium.table.DebeziumOptions.getDebeziumProperties;
/** Factory for creating configured instance of {@link PostgreSQLTableSource}. */
public class PostgreSQLTableFactory implements DynamicTableSourceFactory {
private static final String IDENTIFIER = "postgres-cdc";
private static final ConfigOption<String> HOSTNAME =
ConfigOptions.key("hostname")
.stringType()
.noDefaultValue()
.withDescription("IP address or hostname of the PostgreSQL database server.");
private static final ConfigOption<Integer> PORT =
ConfigOptions.key("port")
.intType()
.defaultValue(5432)
.withDescription("Integer port number of the PostgreSQL database server.");
private static final ConfigOption<String> USERNAME =
ConfigOptions.key("username")
.stringType()
.noDefaultValue()
.withDescription(
"Name of the PostgreSQL database to use when connecting to the PostgreSQL database server.");
private static final ConfigOption<String> PASSWORD =
ConfigOptions.key("password")
.stringType()
.noDefaultValue()
.withDescription(
"Password to use when connecting to the PostgreSQL database server.");
private static final ConfigOption<String> DATABASE_NAME =
ConfigOptions.key("database-name")
.stringType()
.noDefaultValue()
.withDescription("Database name of the PostgreSQL server to monitor.");
private static final ConfigOption<String> SCHEMA_NAME =
ConfigOptions.key("schema-name")
.stringType()
.noDefaultValue()
.withDescription("Schema name of the PostgreSQL database to monitor.");
private static final ConfigOption<String> TABLE_NAME =
ConfigOptions.key("table-name")
.stringType()
.noDefaultValue()
.withDescription("Table name of the PostgreSQL database to monitor.");
private static final ConfigOption<String> DECODING_PLUGIN_NAME =
ConfigOptions.key("decoding.plugin.name")
.stringType()
.defaultValue("decoderbufs")
.withDescription(
"The name of the Postgres logical decoding plug-in installed on the server.\n"
+ "Supported values are decoderbufs, wal2json, wal2json_rds, wal2json_streaming,\n"
+ "wal2json_rds_streaming and pgoutput.");
private static final ConfigOption<String> SLOT_NAME =
ConfigOptions.key("slot.name")
.stringType()
.defaultValue("flink")
.withDescription(
"The name of the PostgreSQL logical decoding slot that was created for streaming changes "
+ "from a particular plug-in for a particular database/schema. The server uses this slot "
+ "to stream events to the connector that you are configuring. Default is \"flink\".");
@Override
public DynamicTableSource createDynamicTableSource(DynamicTableFactory.Context context) {
final FactoryUtil.TableFactoryHelper helper =
FactoryUtil.createTableFactoryHelper(this, context);
helper.validateExcept(DEBEZIUM_OPTIONS_PREFIX);
final ReadableConfig config = helper.getOptions();
String hostname = config.get(HOSTNAME);
String username = config.get(USERNAME);
String password = config.get(PASSWORD);
String databaseName = config.get(DATABASE_NAME);
String schemaName = config.get(SCHEMA_NAME);
String tableName = config.get(TABLE_NAME);
int port = config.get(PORT);
String pluginName = config.get(DECODING_PLUGIN_NAME);
String slotName = config.get(SLOT_NAME);
TableSchema physicalSchema =
TableSchemaUtils.getPhysicalSchema(context.getCatalogTable().getSchema());
return new PostgreSQLTableSource(
physicalSchema,
port,
hostname,
databaseName,
schemaName,
tableName,
username,
password,
pluginName,
slotName,
getDebeziumProperties(context.getCatalogTable().getOptions()));
}
@Override
public String factoryIdentifier() {
return IDENTIFIER;
}
@Override
public Set<ConfigOption<?>> requiredOptions() {
Set<ConfigOption<?>> options = new HashSet<>();
options.add(HOSTNAME);
options.add(USERNAME);
options.add(PASSWORD);
options.add(DATABASE_NAME);
options.add(SCHEMA_NAME);
options.add(TABLE_NAME);
return options;
}
@Override
public Set<ConfigOption<?>> optionalOptions() {
Set<ConfigOption<?>> options = new HashSet<>();
options.add(PORT);
options.add(DECODING_PLUGIN_NAME);
return options;
}
}
|
//App15_1.java 简单的绘图程序
package example;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App15_1 extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
static JButton bnt1 =new JButton("画圆");
static JButton bnt2 =new JButton("画椭圆");
static JPanel pan = new MyPanel();
static App15_1 frm = new App15_1();
static int circle=0;
public static void main(String[] args)
{
frm.setVisible(true);
frm.setTitle("简单绘图应用程序");
frm.setSize(300,250);
frm.setLayout(null);
frm.add(pan);
pan.setBounds(0,0,300,250);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static class MyPanel extends JPanel implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
MyPanel()
{
this.add(bnt1); this.add(bnt2);
bnt1.addActionListener(this);
bnt2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
JButton bt=(JButton)e.getSource();
if (bt==bnt1) circle=1;
else circle=2;
@SuppressWarnings("unused")
Graphics g=this.getGraphics();
repaint();
}
public void paintComponent(Graphics g)
{
//super.paintComponent(g);
bnt1.setBounds(50,180,80,25);
bnt2.setBounds(150,180,80,25);
g.setFont(new Font("楷体",Font.ITALIC,20));
g.setColor(Color.RED);
g.drawString("画圆或椭圆",100,30);
if (circle==1) g.drawOval(100,70,70,70);
else if (circle==2) g.drawOval(80,40,70,120);
}
}
}
|
package checkers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class PresenceConditionMacroChecker {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(new File("bugs/busybox/busybox-bugs"));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
String[] parts = line.split(";");
String presenceCondition = parts[3];
presenceCondition = presenceCondition.replaceAll("\\s", "");
String[] options = presenceCondition.split("\\)\\|\\|\\(");
int numberOfMacros = 100000;
for (String option : options){
String[] macros = option.split("&&");
if (macros.length < numberOfMacros){
numberOfMacros = macros.length;
}
}
System.out.println(parts[0] + "/" + parts[1] + "/" + parts[2] + ": " + numberOfMacros + ".");
}
br.close();
}
}
|
package net.yoojia.imagemap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.caverock.androidsvg.SVG;
import net.yoojia.imagemap.core.PushMessageShape;
import net.yoojia.imagemap.core.RequestShape;
import net.yoojia.imagemap.core.Shape;
import net.yoojia.imagemap.core.ShapeExtension;
import net.yoojia.imagemap.core.SpecialShape;
import net.yoojia.imagemap.util.MatrixConverHelper;
import net.yoojia.imagemap.util.SvgHelper;
import net.yoojia.imagemap.util.SvgHelper.SvgPath;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.webkit.MimeTypeMap;
/**
* HighlightImageView基于TouchImageView的功能,在ImageView的Canvas上绘制一些形状。 Based on
* TouchImageView class, Design for draw shapes on canvas of ImageView
*/
public class HighlightImageView1 extends TouchImageView1 implements
ShapeExtension
{
public boolean isOnArea;
public int mFiterColor;
public int getmFiterColor()
{
return mFiterColor;
}
public void setmFiterColor(int mFiterColor)
{
this.mFiterColor = mFiterColor;
}
public boolean isOnArea()
{
return isOnArea;
}
public void setOnArea(boolean isOnArea)
{
this.isOnArea = isOnArea;
}
public HighlightImageView1(Context context)
{
this(context, null);
}
public HighlightImageView1(Context context, AttributeSet attrs)
{
super(context, attrs);
}
private Map<Object, Shape> shapesCache = new HashMap<Object, Shape>(0);
private OnShapeActionListener onShapeClickListener;
private SVG mSvgData;
private List<SvgPath> mSvgPaths = new ArrayList<SvgHelper.SvgPath>();
private static final int SVGTOPATH_OK = 1;
private Handler mhandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
if (msg.what == SVGTOPATH_OK)
{
bindPathToShape(getShapes(), mSvgPaths);
}
}
};
private void bindPathToShape(final List<Shape> shapes,
final List<SvgPath> svgPaths)
{
if (svgPaths.size() == 0 || shapes.size() == 0)
{
return;
}
new Thread(new Runnable()
{
@Override
public void run()
{
shape: for (int i = 0; i < shapes.size(); i++)
{
int z = shapes.size();
Shape shape = shapes.get(i);
if (!(shape instanceof SpecialShape))
{
continue shape;
}
SpecialShape ss = (SpecialShape) shape;
if (ss.getSvgPath() != null)
{
continue shape;
}
path: for (int j = 0; j < svgPaths.size(); j++)
{
SvgPath p = svgPaths.get(j);
if (p.isArea(ss.getCenterX(), ss.getCenterY()))
{
ss.setSvgPath(p);
continue shape;
}
}
}
}
}).start();
};
private void bindPathToShape(SpecialShape shape,
final List<SvgPath> svgPaths)
{
for (int j = 0; j < svgPaths.size(); j++)
{
SvgPath p = svgPaths.get(j);
// if (MatrixConverHelper.isArea(p.getPath(),
// (int) shape.getCenterX(), (int) shape.getCenterY())
// && p.getPaint().getColor() != Color.parseColor("#F8F8D6"))
// {
// p.setSelect(true);
// shape.setAreaPath(p.getPath());
// break;
// }
if (p.isArea(shape.getCenterX(), shape.getCenterY()))
{
shape.setSvgPath(p);
break;
}
}
}
public boolean isFiter = false;
public boolean isAllowRequestTranslate = false;
public boolean isAllowRequestTranslate()
{
return isAllowRequestTranslate;
}
public void setAllowRequestTranslate(boolean isAllowRequestTranslate)
{
this.isAllowRequestTranslate = isAllowRequestTranslate;
}
public void setSvg(final SVG svg)
{
if (svg == null)
{
return;
}
clearShapes();
mSvgData = svg;
new Thread(new Runnable()
{
@Override
public void run()
{
SvgHelper svgHelper = new SvgHelper(new Paint());
svgHelper.load(mSvgData);
mSvgPaths = svgHelper.getPathsForViewport(
(int) svg.getDocumentWidth(),
(int) svg.getDocumentHeight());
mhandler.sendEmptyMessage(SVGTOPATH_OK);
}
}).start();
}
public void setOnShapeClickListener(
OnShapeActionListener onShapeClickListener)
{
this.onShapeClickListener = onShapeClickListener;
}
@Override
public void addShape(Shape shape, boolean isMove)
{
shapesCache.put(shape.tag, shape);
if (shape instanceof SpecialShape)
{
bindPathToShape((SpecialShape) shape, mSvgPaths);
}
if (isMove)
{
PointF point = new PointF(shape.getCenterX(), shape.getCenterY());
requestTranslate(point);
return;
}
postInvalidate();
}
@Override
public void removeShape(Object tag)
{
if (shapesCache.containsKey(tag))
{
shapesCache.remove(tag);
postInvalidate();
}
}
/**
* 判断shape是否存在
*
* @param tag
* @return
*/
public boolean getShape(Object tag)
{
if (shapesCache.containsKey(tag))
{
return true;
} else
{
return false;
}
}
@Override
public void clearShapes()
{
shapesCache.clear();
mSvgPaths.clear();
}
public List<Shape> getShapes()
{
return new ArrayList<Shape>(shapesCache.values());
}
@Override
protected void onDraw(Canvas canvas)
{
Matrix matrix = new Matrix(getImageMatrix());
super.onDraw(canvas);
float scale = getScale();
for (Shape shape : shapesCache.values())
{
shape.postMatrixCahnge(matrix);
shape.setScale(scale);
shape.onDraw(canvas);
}
// Paint paint = new Paint();
// paint.setAntiAlias(true);
// paint.setStyle(Style.STROKE);
// paint.setStrokeWidth(6);
// paint.setColor(Color.parseColor("#8812ee"));
// for (int i = 0; i < mSvgPaths.size(); i++)
// {
// SvgPath mSvgPath = mSvgPaths.get(i);
// if (mSvgPath != null)
// {
// if (mSvgPath.isSelect())
// {
// paint.setColor(Color.parseColor("#88ff44"));
// } else
// {
// paint.setColor(Color.parseColor("#8812ee"));
// }
// canvas.save();
// canvas.setMatrix(matrix);
// switch (mSvgPath.getType())
// {
// case path:
// canvas.drawPath(mSvgPath.getPath(), paint);
// break;
// case rect:
// canvas.drawRect(mSvgPath.getRect(), paint);
// break;
// }
// canvas.restore();
// }
//
// }
onDrawWithCanvas(canvas);
}
private void requestTranslate(PointF point)
{
if (!mMapHandle.isAniming())
{
point = MatrixConverHelper.mapMatrixPoint(getImageMatrix(),
point.x, point.y);
float dx = mView_width / 2f - point.x;
float dy = mView_height / 2f - point.y;
if (Math.abs(dx) < 4 && Math.abs(dy) < 4)
{
return;
}
translateOffset(dx, dy);
}
}
@Override
public void setImageDrawable(Drawable drawable)
{
super.setImageDrawable(drawable);
}
/**
* 如果继承HighlightImageView,并需要在Canvas上绘制,可以Override这个方法来实现。 - Override this
* method for draw something on canvas when YourClass extends
* HighlightImageView.
*
* @param canvas
* 画布
*/
protected void onDrawWithCanvas(Canvas canvas)
{
}
@Override
protected boolean onViewClick(float xOnView, float yOnView)
{
for (Shape shape : shapesCache.values())
{
if (shape.inArea(xOnView, yOnView))
{
if (shape instanceof SpecialShape)
{
if (onShapeClickListener != null)
{
onShapeClickListener.onSpecialShapeClick(
(SpecialShape) shape, shape.getCenterX(),
shape.getCenterY());
}
} else if (shape instanceof PushMessageShape)
{
if (onShapeClickListener != null)
{
onShapeClickListener.onPushMessageShapeClick(
(PushMessageShape) shape, shape.getCenterX(),
shape.getCenterY());
}
}
PointF point = new PointF(shape.getCenterX(),
shape.getCenterY());
point = MatrixConverHelper.mapMatrixPoint(getImageMatrix(),
point.x, point.y);
if (isAllowTranslate)
{
float offsetX = mView_width / 2f - point.x;
float offsetY = mView_height / 2f - point.y;
translateOffset(offsetX, offsetY);
}
return true;
}
}
if (onShapeClickListener != null)
{
onShapeClickListener.outShapeClick(xOnView, yOnView);
}
return false;
}
}
|
/*
* Copyright 2021 OmniFaces
*
* 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.omnifaces.component.validator;
import java.util.HashSet;
import java.util.List;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import org.omnifaces.validator.MultiFieldValidator;
/**
* <p>
* The <code><o:validateEqual></code> validates if ALL of the given {@link UIInput} components have the same
* value.
* <p>
* The default message is
* <blockquote>{0}: Please fill out the same value for all of those fields</blockquote>
* <p>
* For general usage instructions, refer {@link ValidateMultipleFields} documentation.
*
* @author Bauke Scholtz
* @see ValidateMultipleFields
* @see ValidatorFamily
* @see MultiFieldValidator
*/
@FacesComponent(ValidateEqual.COMPONENT_TYPE)
public class ValidateEqual extends ValidateMultipleFields {
// Public constants -----------------------------------------------------------------------------------------------
/** The standard component type. */
public static final String COMPONENT_TYPE = "org.omnifaces.component.validator.ValidateEqual";
// Actions --------------------------------------------------------------------------------------------------------
/**
* Validate if all values are equal.
*/
@Override
public boolean validateValues(FacesContext context, List<UIInput> inputs, List<Object> values) {
return (new HashSet<>(values).size() == 1);
}
}
|
/*
* Copyright 2008-2016 by Emeric Vernat
*
* This file is part of Java Melody.
*
* 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 net.bull.javamelody;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test unitaire de la classe CustomResourceFilter.
* @author Emeric Vernat
*/
public class TestCustomResourceFilter { // NOPMD
private static final String MONITORING_CSS = "monitoring.css";
private static final Map<String, String> CUSTOM_RESOURCES = Collections
.singletonMap(MONITORING_CSS, "customMonitoring.css");
private FilterConfig config;
private CustomResourceFilter customResourceFilter;
/**
* Initialisation.
*/
@Before
public void setUp() {
Utils.initialize();
config = createNiceMock(FilterConfig.class);
expect(config.getInitParameterNames())
.andReturn(Collections.enumeration(Arrays.asList(MONITORING_CSS)));
for (final Map.Entry<String, String> entry : CUSTOM_RESOURCES.entrySet()) {
expect(config.getInitParameter(entry.getKey())).andReturn(entry.getValue());
}
final ServletContext context = createNiceMock(ServletContext.class);
replay(context);
Parameters.initialize(context);
expect(config.getServletContext()).andReturn(context).anyTimes();
customResourceFilter = new CustomResourceFilter();
}
/**
* Finalisation.
*/
@After
public void tearDown() {
if (customResourceFilter != null) {
customResourceFilter.destroy();
}
}
/**
* testRessource.
* @throws IOException e
* @throws ServletException e
*/
@Test
public void testCustomResource() throws IOException, ServletException {
doTestResource(MONITORING_CSS);
}
/**
* testRessource.
* @throws IOException e
* @throws ServletException e
*/
@Test
public void testResource() throws IOException, ServletException {
doTestResource("alert.png");
}
/**
* testRessource.
* @throws IOException e
* @throws ServletException e
*/
@Test
public void testNoResource() throws IOException, ServletException {
doTestResource(null);
}
private void doTestResource(String resource) throws IOException, ServletException {
final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
final RequestDispatcher requestDispatcher = createNiceMock(RequestDispatcher.class);
final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
final FilterChain chain = createNiceMock(FilterChain.class);
expect(request.getParameter("resource")).andReturn(resource);
if (CUSTOM_RESOURCES.get(resource) != null) {
expect(request.getRequestDispatcher(CUSTOM_RESOURCES.get(resource)))
.andReturn(requestDispatcher);
}
replay(config);
replay(request);
replay(response);
replay(chain);
replay(requestDispatcher);
customResourceFilter.init(config);
customResourceFilter.doFilter(request, response, chain);
verify(config);
verify(request);
verify(response);
verify(chain);
verify(requestDispatcher);
}
}
|
/*
* 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 com.bouye.gw2.sab.preloader;
import javafx.application.Preloader;
import javafx.application.Preloader.ProgressNotification;
import javafx.application.Preloader.StateChangeNotification;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/**
* Simple Preloader Using the ProgressBar Control
*
* @author fabriceb
*/
public class SAB_Preloader extends Preloader {
ProgressBar bar;
Stage stage;
private Scene createPreloaderScene() {
bar = new ProgressBar();
BorderPane p = new BorderPane();
p.setCenter(bar);
return new Scene(p, 300, 150);
}
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
stage.setScene(createPreloaderScene());
stage.show();
}
@Override
public void handleStateChangeNotification(StateChangeNotification scn) {
if (scn.getType() == StateChangeNotification.Type.BEFORE_START) {
stage.hide();
}
}
@Override
public void handleProgressNotification(ProgressNotification pn) {
bar.setProgress(pn.getProgress());
}
}
|
package ru.job4j.chess.figures;
/**
* ImpossibleMoveException - class for exceptions.
* ImpossibleMoveException extends RuntimeException class.
* ImpossibleMoveException throws when the Figure is tried to be moved incorrectly.
* @author Alexander Kordyukov (alex-programm@yandex.ru)
* @version $Id$
* @since 0.1
*/
public class ImpossibleMoveException extends RuntimeException {
/**
* Constructor
* @param msg - exception message.
*/
public ImpossibleMoveException(String msg) {
super(msg);
}
}
|
package ru.job4j.array;
/**
* 5.1. Создать программу для сортировки массива методом перестановки. [#195].
* @author ZapovA
* @since 14.9.17
*/
public class BubbleSort {
/**
* Метод для сортировки массива методом перестановки.
* @param array - входной массив.
* @return отсортированный.
*/
public int[] sort(int[] array) {
for (int i = array.length - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
return array;
}
}
|
/*
* Copyright 2019 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.cloud.videointelligence.v1beta2.stub;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.grpc.ProtoOperationTransformers;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.cloud.videointelligence.v1beta2.AnnotateVideoProgress;
import com.google.cloud.videointelligence.v1beta2.AnnotateVideoRequest;
import com.google.cloud.videointelligence.v1beta2.AnnotateVideoResponse;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.longrunning.Operation;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
import org.threeten.bp.Duration;
// AUTO-GENERATED DOCUMENTATION AND CLASS
/**
* Settings class to configure an instance of {@link VideoIntelligenceServiceStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (videointelligence.googleapis.com) and default port (443) are
* used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object. For
* example, to set the total timeout of annotateVideoAsync to 30 seconds:
*
* <pre>
* <code>
* VideoIntelligenceServiceStubSettings.Builder videoIntelligenceServiceSettingsBuilder =
* VideoIntelligenceServiceStubSettings.newBuilder();
* videoIntelligenceServiceSettingsBuilder.annotateVideoSettings().getRetrySettings().toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30));
* VideoIntelligenceServiceStubSettings videoIntelligenceServiceSettings = videoIntelligenceServiceSettingsBuilder.build();
* </code>
* </pre>
*/
@Generated("by gapic-generator")
@BetaApi
public class VideoIntelligenceServiceStubSettings
extends StubSettings<VideoIntelligenceServiceStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build();
private final UnaryCallSettings<AnnotateVideoRequest, Operation> annotateVideoSettings;
private final OperationCallSettings<
AnnotateVideoRequest, AnnotateVideoResponse, AnnotateVideoProgress>
annotateVideoOperationSettings;
/** Returns the object with the settings used for calls to annotateVideo. */
public UnaryCallSettings<AnnotateVideoRequest, Operation> annotateVideoSettings() {
return annotateVideoSettings;
}
/** Returns the object with the settings used for calls to annotateVideo. */
@BetaApi("The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings<AnnotateVideoRequest, AnnotateVideoResponse, AnnotateVideoProgress>
annotateVideoOperationSettings() {
return annotateVideoOperationSettings;
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public VideoIntelligenceServiceStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcVideoIntelligenceServiceStub.create(this);
} else {
throw new UnsupportedOperationException(
"Transport not supported: " + getTransportChannelProvider().getTransportName());
}
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return "videointelligence.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return InstantiatingGrpcChannelProvider.newBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultGrpcTransportProviderBuilder().build();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(VideoIntelligenceServiceStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected VideoIntelligenceServiceStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
annotateVideoSettings = settingsBuilder.annotateVideoSettings().build();
annotateVideoOperationSettings = settingsBuilder.annotateVideoOperationSettings().build();
}
/** Builder for VideoIntelligenceServiceStubSettings. */
public static class Builder
extends StubSettings.Builder<VideoIntelligenceServiceStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final UnaryCallSettings.Builder<AnnotateVideoRequest, Operation> annotateVideoSettings;
private final OperationCallSettings.Builder<
AnnotateVideoRequest, AnnotateVideoResponse, AnnotateVideoProgress>
annotateVideoOperationSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"idempotent",
ImmutableSet.copyOf(
Lists.<StatusCode.Code>newArrayList(
StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE)));
definitions.put("non_idempotent", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(1000L))
.setRetryDelayMultiplier(2.5)
.setMaxRetryDelay(Duration.ofMillis(120000L))
.setInitialRpcTimeout(Duration.ofMillis(120000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofMillis(120000L))
.setTotalTimeout(Duration.ofMillis(600000L))
.build();
definitions.put("default", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this((ClientContext) null);
}
protected Builder(ClientContext clientContext) {
super(clientContext);
annotateVideoSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
annotateVideoOperationSettings = OperationCallSettings.newBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(annotateVideoSettings);
initDefaults(this);
}
private static Builder createDefault() {
Builder builder = new Builder((ClientContext) null);
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setEndpoint(getDefaultEndpoint());
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.annotateVideoSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default"));
builder
.annotateVideoOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<AnnotateVideoRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(AnnotateVideoResponse.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(AnnotateVideoProgress.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(20000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelay(Duration.ofMillis(45000L))
.setInitialRpcTimeout(Duration.ZERO) // ignored
.setRpcTimeoutMultiplier(1.0) // ignored
.setMaxRpcTimeout(Duration.ZERO) // ignored
.setTotalTimeout(Duration.ofMillis(86400000L))
.build()));
return builder;
}
protected Builder(VideoIntelligenceServiceStubSettings settings) {
super(settings);
annotateVideoSettings = settings.annotateVideoSettings.toBuilder();
annotateVideoOperationSettings = settings.annotateVideoOperationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(annotateVideoSettings);
}
// NEXT_MAJOR_VER: remove 'throws Exception'
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) throws Exception {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to annotateVideo. */
public UnaryCallSettings.Builder<AnnotateVideoRequest, Operation> annotateVideoSettings() {
return annotateVideoSettings;
}
/** Returns the builder for the settings used for calls to annotateVideo. */
@BetaApi(
"The surface for use by generated code is not stable yet and may change in the future.")
public OperationCallSettings.Builder<
AnnotateVideoRequest, AnnotateVideoResponse, AnnotateVideoProgress>
annotateVideoOperationSettings() {
return annotateVideoOperationSettings;
}
@Override
public VideoIntelligenceServiceStubSettings build() throws IOException {
return new VideoIntelligenceServiceStubSettings(this);
}
}
}
|
// This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.twc.models;
import com.aliyun.tea.*;
public class SyncInnerProvisionResponse extends TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
@NameInMap("req_msg_id")
public String reqMsgId;
// 结果码,一般OK表示调用成功
@NameInMap("result_code")
public String resultCode;
// 异常信息的文本描述
@NameInMap("result_msg")
public String resultMsg;
public static SyncInnerProvisionResponse build(java.util.Map<String, ?> map) throws Exception {
SyncInnerProvisionResponse self = new SyncInnerProvisionResponse();
return TeaModel.build(map, self);
}
public SyncInnerProvisionResponse setReqMsgId(String reqMsgId) {
this.reqMsgId = reqMsgId;
return this;
}
public String getReqMsgId() {
return this.reqMsgId;
}
public SyncInnerProvisionResponse setResultCode(String resultCode) {
this.resultCode = resultCode;
return this;
}
public String getResultCode() {
return this.resultCode;
}
public SyncInnerProvisionResponse setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
return this;
}
public String getResultMsg() {
return this.resultMsg;
}
}
|
//孙瑞洲改 2019.8.8
package com.zhuangfei.timetable.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 课程实体类<br/>
* 1.增加了extras,可以保存一些自己需要的东西<br/>
* @author Administrator 刘壮飞
*
*/
public class Schedule implements Serializable,Comparable<Schedule>{
/**
* 课程名
*/
private String name="";
/**
* 教室
*/
private String room="";
/**
* 教师
*/
private String teacher="";
/**
* 第几周至第几周上
*/
private List<Integer> weekList=new ArrayList<>();
/**
* 开始上课的节次
*/
private int start=0;
/**
* 上课节数
*/
private int step=0;
/**
* 周几上
*/
private int day=0;
/**
* 一个随机数,用于对应课程的颜色
*/
private int colorRandom = 0;
private int courseId;
/**
* 额外信息
*/
private Map<String,Object> extras=new HashMap<>();
public Schedule(String name, String room, String teacher,
List<Integer> weekList, int start, int step, int day,
int colorRandom) {
super();
this.name = name;
this.room = room;
this.teacher = teacher;
this.weekList = weekList;
this.start = start;
this.step = step;
this.day = day;
this.colorRandom = colorRandom;
}
public Map<String,Object> getExtras(){
return extras;
}
public void setExtras(Map<String,Object> map){
this.extras=map;
}
public void putExtras(String key,Object val){
getExtras().put(key,val);
}
public void setCourseId(int id){courseId=id;}
public int getCourseId(){return courseId;}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public void setWeekList(List<Integer> weekList) {
this.weekList = weekList;
}
public List<Integer> getWeekList() {
return weekList;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getColorRandom() {
return colorRandom;
}
public void setColorRandom(int colorRandom) {
this.colorRandom = colorRandom;
}
public Schedule() {
super();
}
@Override
public int compareTo(Schedule o) {
if(getStart()<o.getStart()){
return -1;
}else if(getStart()==o.getStart()){
return 0;
}else{
return 1;
}
}
}
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import static com.google.errorprone.util.ASTHelpers.getType;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Types;
import java.util.List;
/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
summary =
"The first argument to nCopies is the number of copies, and the second is the item to copy",
severity = ERROR)
public class NCopiesOfChar extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
staticMethod().onClass("java.util.Collections").named("nCopies");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!MATCHER.matches(tree, state)) {
return NO_MATCH;
}
List<? extends ExpressionTree> arguments = tree.getArguments();
Symtab syms = state.getSymtab();
Types types = state.getTypes();
if (types.isSameType(types.unboxedTypeOrType(getType(arguments.get(1))), syms.intType)
&& types.isSameType(types.unboxedTypeOrType(getType(arguments.get(0))), syms.charType)) {
return describeMatch(
tree,
SuggestedFix.builder()
.replace(arguments.get(0), state.getSourceForNode(arguments.get(1)))
.replace(arguments.get(1), state.getSourceForNode(arguments.get(0)))
.build());
}
return NO_MATCH;
}
}
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2014 The ZAP Development Team
*
* 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.zaproxy.zap.extension.multiFuzz;
import java.awt.Component;
import java.util.ArrayList;
import org.zaproxy.zap.extension.httppanel.Message;
/**
* Interface for UI components which display target messages and highlight fuzzing targets within them.
*
* @param <M> the message type
* @param <L> the associated {@link FuzzLocation} implementation
* @param <G> the associated {@link FuzzGap} implementation
*/
public interface FuzzComponent<M extends Message, L extends FuzzLocation<M>, G extends FuzzGap<M, L, ?>> {
/**
* Returns the {@link FuzzLocation} in the message that has been selected by the user in the component.
* @return the FuzzLocation
*/
L selection();
/**
* Highlights a new set of locations in the component.
* @param allLocs list of locations to be highlighted
*/
void highlight(ArrayList<G> allLocs);
/**
* The component itself
* @return the component
*/
Component messageView();
/**
* Changes the user selection in the Component to a specific {@link FuzzLocation} in the message.
* @param f the target {@link FuzzLocation}
*/
void markUp(L f);
/**
* Searches through the message and cycles through parts matching a certain String representation. The current match is being selected.
* @param text search String
*/
void search(String text);
/**
* Sets the message displayed
* @param message the new message
*/
void setMessage(M message);
}
|
package ro.ciprianradu.rentacar.http.registerlocation;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import ro.ciprianradu.rentacar.http.HttpResponse;
import ro.ciprianradu.rentacar.http.HttpStatus;
import ro.ciprianradu.rentacar.http.dtos.Location;
import ro.ciprianradu.rentacar.usecases.registerlocation.RegisterLocationInputData;
import ro.ciprianradu.rentacar.usecases.registerlocation.RegisterLocationInputPort;
import ro.ciprianradu.rentacar.usecases.registerlocation.RegisterLocationOutputData;
import ro.ciprianradu.rentacar.usecases.registerlocation.RegisterLocationOutputPort;
/**
* Unit tests for {@link RegisterLocationAdapter}
*/
class RegisterLocationAdapterTest {
@Test
public void test_RegisterLocationAdapter_null_throwsException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
new RegisterLocationAdapter(null);
});
}
@Test
public void test_RegisterLocationAdapter_instantiates() {
final RegisterLocationAdapter registerLocationAdapter = new RegisterLocationAdapter(
new MockRegisterLocationInputPort());
Assertions.assertNotNull(registerLocationAdapter);
}
@Test
public void test_registerLocation_nullLocation_returnsBadRequest() {
final RegisterLocationAdapter registerLocationAdapter = new RegisterLocationAdapter(
new MockRegisterLocationInputPort());
final HttpResponse httpResponse = registerLocationAdapter.registerLocation(null);
Assertions.assertEquals(HttpStatus.BAD_REQUEST, httpResponse.getStatus());
}
@Test
public void test_registerLocation_nullLocationName_returnsBadRequest() {
final RegisterLocationAdapter registerLocationAdapter = new RegisterLocationAdapter(
new MockRegisterLocationInputPort());
final Location location = new Location();
final HttpResponse httpResponse = registerLocationAdapter.registerLocation(location);
Assertions.assertEquals(HttpStatus.BAD_REQUEST, httpResponse.getStatus());
}
@Test
public void test_registerLocation_locationName_returnsCreated() {
final RegisterLocationAdapter registerLocationAdapter = new RegisterLocationAdapter(
new MockRegisterLocationInputPort());
final Location location = new Location();
location.setName("name");
final HttpResponse httpResponse = registerLocationAdapter.registerLocation(location);
Assertions.assertEquals(HttpStatus.CREATED, httpResponse.getStatus());
}
@Test
public void test_registerLocation_sameLocationName_returnsCreated() {
final RegisterLocationAdapter registerLocationAdapter = new RegisterLocationAdapter(
new MockRegisterLocationInputPort());
final Location location = new Location();
location.setName("name");
HttpResponse httpResponse = registerLocationAdapter.registerLocation(location);
Assertions.assertEquals(HttpStatus.CREATED, httpResponse.getStatus());
httpResponse = registerLocationAdapter.registerLocation(location);
Assertions.assertEquals(HttpStatus.CONFLICT, httpResponse.getStatus());
}
private static class MockRegisterLocationInputPort implements RegisterLocationInputPort {
private List<String> registeredLoations = new ArrayList<>();
@Override
public void registerLocation(final RegisterLocationInputData inputData,
final RegisterLocationOutputPort outputPort) {
boolean registered;
if (registeredLoations.contains(inputData.getName())) {
registered = false;
} else {
registeredLoations.add(inputData.getName());
registered = true;
}
outputPort.present(new RegisterLocationOutputData(registered));
}
}
}
|
package datadog.trace.instrumentation.jakarta3;
import static datadog.trace.agent.tooling.bytebuddy.matcher.DDElementMatchers.hasSuperMethod;
import static datadog.trace.agent.tooling.bytebuddy.matcher.DDElementMatchers.safeHasSuperType;
import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.named;
import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.namedOneOf;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.startSpan;
import static datadog.trace.instrumentation.jakarta3.JakartaRsAnnotationsDecorator.DECORATE;
import static java.util.Collections.singletonMap;
import static net.bytebuddy.matcher.ElementMatchers.declaresMethod;
import static net.bytebuddy.matcher.ElementMatchers.isAnnotatedWith;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import com.google.auto.service.AutoService;
import datadog.trace.agent.tooling.Instrumenter;
import datadog.trace.bootstrap.ContextStore;
import datadog.trace.bootstrap.InstrumentationContext;
import datadog.trace.bootstrap.instrumentation.api.AgentScope;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import jakarta.ws.rs.container.AsyncResponse;
import java.lang.reflect.Method;
import java.util.Map;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
@AutoService(Instrumenter.class)
public final class JakartaRsAnnotationsInstrumentation extends Instrumenter.Tracing {
private static final String JAKARTA_ENDPOINT_OPERATION_NAME = "jakarta-rs.request";
public JakartaRsAnnotationsInstrumentation() {
super("jakarta-rs", "jakartars", "jakarta-rs-annotations");
}
@Override
public Map<String, String> contextStore() {
return singletonMap("jakarta.ws.rs.container.AsyncResponse", AgentSpan.class.getName());
}
@Override
public ElementMatcher<ClassLoader> classLoaderMatcher() {
// Optimization for expensive typeMatcher.
return JakartaRsAsyncResponseInstrumentation.CLASS_LOADER_MATCHER;
}
@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return safeHasSuperType(
isAnnotatedWith(named("jakarta.ws.rs.Path"))
.<TypeDescription>or(declaresMethod(isAnnotatedWith(named("jakarta.ws.rs.Path")))));
}
@Override
public String[] helperClassNames() {
return new String[] {
"datadog.trace.agent.tooling.ClassHierarchyIterable",
"datadog.trace.agent.tooling.ClassHierarchyIterable$ClassIterator",
packageName + ".JakartaRsAnnotationsDecorator",
};
}
@Override
public void adviceTransformations(AdviceTransformation transformation) {
transformation.applyAdvice(
isMethod()
.and(
hasSuperMethod(
isAnnotatedWith(
namedOneOf(
"jakarta.ws.rs.Path",
"jakarta.ws.rs.DELETE",
"jakarta.ws.rs.GET",
"jakarta.ws.rs.HEAD",
"jakarta.ws.rs.OPTIONS",
"jakarta.ws.rs.POST",
"jakarta.ws.rs.PUT")))),
JakartaRsAnnotationsInstrumentation.class.getName() + "$JakartaRsAnnotationsAdvice");
}
public static class JakartaRsAnnotationsAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static AgentScope nameSpan(
@Advice.This final Object target,
@Advice.Origin final Method method,
@Advice.AllArguments final Object[] args,
@Advice.Local("asyncResponse") AsyncResponse asyncResponse) {
ContextStore<AsyncResponse, AgentSpan> contextStore = null;
for (final Object arg : args) {
if (arg instanceof AsyncResponse) {
asyncResponse = (AsyncResponse) arg;
contextStore = InstrumentationContext.get(AsyncResponse.class, AgentSpan.class);
if (contextStore.get(asyncResponse) != null) {
/**
* We are probably in a recursive call and don't want to start a new span because it
* would replace the existing span in the asyncResponse and cause it to never finish. We
* could work around this by using a list instead, but we likely don't want the extra
* span anyway.
*/
return null;
}
break;
}
}
// Rename the parent span according to the path represented by these annotations.
final AgentSpan parent = activeSpan();
final AgentSpan span = startSpan(JAKARTA_ENDPOINT_OPERATION_NAME);
span.setMeasured(true);
DECORATE.onJakartaRsSpan(span, parent, target.getClass(), method);
DECORATE.afterStart(span);
final AgentScope scope = activateSpan(span);
scope.setAsyncPropagation(true);
if (contextStore != null && asyncResponse != null) {
contextStore.put(asyncResponse, span);
}
return scope;
}
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void stopSpan(
@Advice.Enter final AgentScope scope,
@Advice.Thrown final Throwable throwable,
@Advice.Local("asyncResponse") final AsyncResponse asyncResponse) {
if (scope == null) {
return;
}
final AgentSpan span = scope.span();
if (throwable != null) {
DECORATE.onError(span, throwable);
DECORATE.beforeFinish(span);
span.finish();
scope.close();
return;
}
if (asyncResponse != null && !asyncResponse.isSuspended()) {
// Clear span from the asyncResponse. Logically this should never happen. Added to be safe.
InstrumentationContext.get(AsyncResponse.class, AgentSpan.class).put(asyncResponse, null);
}
if (asyncResponse == null || !asyncResponse.isSuspended()) {
DECORATE.beforeFinish(span);
span.finish();
}
// else span finished by AsyncResponseAdvice
scope.close();
}
}
}
|
package com.wolanx.echo.iothub.model.vo;
import lombok.Data;
import java.util.Date;
/**
* @author wolanx
*/
@Data
public class DeviceVO {
private Long id;
private Integer type;
private String productKey;
private String deviceName;
private String deviceSecret;
private Date lastOnlineTs;
// other
private Boolean isOnline;
}
|
package generator.helper.groups.character;
/**
* Represents a character group mapped to a flag which indicates whether it is
* activated or not.
*
* @author Chris
*/
public class CharacterGroup {
// Fields
private String name;
private char[] characters;
private boolean active;
// Constructors
/**
* Creates a character group which is active by default.
*
* @param characters
*/
public CharacterGroup(String name, char[] characters) {
this(name, characters, true);
}
/**
* Creates a character group which can be active or inactive.
*
* @param characters
* @param active
*/
public CharacterGroup(String name, char[] characters, boolean active) {
this.name = name;
this.characters = characters;
this.active = active;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char[] getCharacters() {
return characters;
}
public void setCharacters(char[] characters) {
this.characters = characters;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
|
package org.riversun.xternal.simpleslackapi.impl;
import org.riversun.xternal.simpleslackapi.SlackUser;
import org.riversun.xternal.simpleslackapi.events.SlackEventType;
import org.riversun.xternal.simpleslackapi.events.SlackTeamJoin;
public class SlackTeamJoinImpl implements SlackTeamJoin {
private final SlackUser slackUser;
SlackTeamJoinImpl(SlackUser slackUser) {
this.slackUser = slackUser;
}
@Override
public SlackUser getUser() {
return slackUser;
}
@Override
public SlackEventType getEventType() {
return SlackEventType.SLACK_TEAM_JOIN;
}
}
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.dmn.api.definition.v1_1;
import java.util.HashSet;
import java.util.Set;
import javax.validation.Valid;
import org.jboss.errai.common.client.api.annotations.MapsTo;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.jboss.errai.databinding.client.api.Bindable;
import org.kie.workbench.common.dmn.api.definition.DMNViewDefinition;
import org.kie.workbench.common.dmn.api.definition.HasVariable;
import org.kie.workbench.common.dmn.api.property.background.BackgroundSet;
import org.kie.workbench.common.dmn.api.property.dimensions.RectangleDimensionsSet;
import org.kie.workbench.common.dmn.api.property.dmn.Id;
import org.kie.workbench.common.dmn.api.property.dmn.Name;
import org.kie.workbench.common.dmn.api.property.font.FontSet;
import org.kie.workbench.common.forms.adf.definitions.annotations.FieldParam;
import org.kie.workbench.common.forms.adf.definitions.annotations.FormDefinition;
import org.kie.workbench.common.forms.adf.definitions.annotations.FormField;
import org.kie.workbench.common.forms.adf.definitions.settings.FieldPolicy;
import org.kie.workbench.common.stunner.core.definition.annotation.Definition;
import org.kie.workbench.common.stunner.core.definition.annotation.PropertySet;
import org.kie.workbench.common.stunner.core.definition.annotation.definition.Category;
import org.kie.workbench.common.stunner.core.definition.annotation.definition.Labels;
import org.kie.workbench.common.stunner.core.factory.graph.NodeFactory;
import org.kie.workbench.common.stunner.core.util.HashUtil;
import static org.kie.workbench.common.forms.adf.engine.shared.formGeneration.processing.fields.fieldInitializers.nestedForms.SubFormFieldInitializer.COLLAPSIBLE_CONTAINER;
import static org.kie.workbench.common.forms.adf.engine.shared.formGeneration.processing.fields.fieldInitializers.nestedForms.SubFormFieldInitializer.FIELD_CONTAINER_PARAM;
@Portable
@Bindable
@Definition(graphFactory = NodeFactory.class)
@FormDefinition(policy = FieldPolicy.ONLY_MARKED, startElement = "id", defaultFieldSettings = {@FieldParam(name = FIELD_CONTAINER_PARAM, value = COLLAPSIBLE_CONTAINER)})
public class BusinessKnowledgeModel extends DRGElement implements HasVariable,
DMNViewDefinition {
@Category
public static final transient String stunnerCategory = Categories.NODES;
@Labels
private final Set<String> stunnerLabels = new HashSet<String>() {{
add("business-knowledge-model");
}};
@PropertySet
@FormField(afterElement = "name")
@Valid
protected InformationItem variable;
protected FunctionDefinition encapsulatedLogic;
@PropertySet
@FormField(afterElement = "variable")
@Valid
protected BackgroundSet backgroundSet;
@PropertySet
@FormField(afterElement = "backgroundSet")
@Valid
protected FontSet fontSet;
@PropertySet
@FormField(afterElement = "fontSet")
@Valid
protected RectangleDimensionsSet dimensionsSet;
public BusinessKnowledgeModel() {
this(new Id(),
new org.kie.workbench.common.dmn.api.property.dmn.Description(),
new Name(),
new InformationItem(),
new FunctionDefinition(),
new BackgroundSet(),
new FontSet(),
new RectangleDimensionsSet());
}
public BusinessKnowledgeModel(final @MapsTo("id") Id id,
final @MapsTo("description") org.kie.workbench.common.dmn.api.property.dmn.Description description,
final @MapsTo("name") Name name,
final @MapsTo("variable") InformationItem variable,
final @MapsTo("encapsulatedLogic") FunctionDefinition encapsulatedLogic,
final @MapsTo("backgroundSet") BackgroundSet backgroundSet,
final @MapsTo("fontSet") FontSet fontSet,
final @MapsTo("dimensionsSet") RectangleDimensionsSet dimensionsSet) {
super(id,
description,
name);
this.variable = variable;
this.encapsulatedLogic = encapsulatedLogic;
this.backgroundSet = backgroundSet;
this.fontSet = fontSet;
this.dimensionsSet = dimensionsSet;
}
// -----------------------
// Stunner core properties
// -----------------------
public String getStunnerCategory() {
return stunnerCategory;
}
public Set<String> getStunnerLabels() {
return stunnerLabels;
}
@Override
public BackgroundSet getBackgroundSet() {
return backgroundSet;
}
public void setBackgroundSet(final BackgroundSet backgroundSet) {
this.backgroundSet = backgroundSet;
}
@Override
public FontSet getFontSet() {
return fontSet;
}
public void setFontSet(final FontSet fontSet) {
this.fontSet = fontSet;
}
@Override
public RectangleDimensionsSet getDimensionsSet() {
return dimensionsSet;
}
public void setDimensionsSet(final RectangleDimensionsSet dimensionsSet) {
this.dimensionsSet = dimensionsSet;
}
// -----------------------
// DMN properties
// -----------------------
@Override
public InformationItem getVariable() {
return variable;
}
@Override
public void setVariable(final InformationItem variable) {
this.variable = variable;
}
@Override
public DMNModelInstrumentedBase asDMNModelInstrumentedBase() {
return this;
}
public FunctionDefinition getEncapsulatedLogic() {
return encapsulatedLogic;
}
public void setEncapsulatedLogic(final FunctionDefinition value) {
this.encapsulatedLogic = value;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof BusinessKnowledgeModel)) {
return false;
}
final BusinessKnowledgeModel that = (BusinessKnowledgeModel) o;
if (id != null ? !id.equals(that.id) : that.id != null) {
return false;
}
if (description != null ? !description.equals(that.description) : that.description != null) {
return false;
}
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
if (variable != null ? !variable.equals(that.variable) : that.variable != null) {
return false;
}
if (encapsulatedLogic != null ? !encapsulatedLogic.equals(that.encapsulatedLogic) : that.encapsulatedLogic != null) {
return false;
}
if (backgroundSet != null ? !backgroundSet.equals(that.backgroundSet) : that.backgroundSet != null) {
return false;
}
if (fontSet != null ? !fontSet.equals(that.fontSet) : that.fontSet != null) {
return false;
}
return dimensionsSet != null ? dimensionsSet.equals(that.dimensionsSet) : that.dimensionsSet == null;
}
@Override
public int hashCode() {
return HashUtil.combineHashCodes(id != null ? id.hashCode() : 0,
description != null ? description.hashCode() : 0,
name != null ? name.hashCode() : 0,
variable != null ? variable.hashCode() : 0,
encapsulatedLogic != null ? encapsulatedLogic.hashCode() : 0,
backgroundSet != null ? backgroundSet.hashCode() : 0,
fontSet != null ? fontSet.hashCode() : 0,
dimensionsSet != null ? dimensionsSet.hashCode() : 0);
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.config;
import java.util.List;
import org.w3c.dom.Element;
import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.jdbc.datasource.init.CompositeDatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
/**
* Internal utility methods used with JDBC configuration.
*
* @author Juergen Hoeller
* @author Stephane Nicoll
* @since 3.1
*/
abstract class DatabasePopulatorConfigUtils {
public static void setDatabasePopulator(Element element, BeanDefinitionBuilder builder) {
List<Element> scripts = DomUtils.getChildElementsByTagName(element, "script");
if (!scripts.isEmpty()) {
builder.addPropertyValue("databasePopulator", createDatabasePopulator(element, scripts, "INIT"));
builder.addPropertyValue("databaseCleaner", createDatabasePopulator(element, scripts, "DESTROY"));
}
}
private static BeanDefinition createDatabasePopulator(Element element, List<Element> scripts, String execution) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CompositeDatabasePopulator.class);
boolean ignoreFailedDrops = element.getAttribute("ignore-failures").equals("DROPS");
boolean continueOnError = element.getAttribute("ignore-failures").equals("ALL");
ManagedList<BeanMetadataElement> delegates = new ManagedList<>();
for (Element scriptElement : scripts) {
String executionAttr = scriptElement.getAttribute("execution");
if (!StringUtils.hasText(executionAttr)) {
executionAttr = "INIT";
}
if (!execution.equals(executionAttr)) {
continue;
}
BeanDefinitionBuilder delegate = BeanDefinitionBuilder.genericBeanDefinition(ResourceDatabasePopulator.class);
delegate.addPropertyValue("ignoreFailedDrops", ignoreFailedDrops);
delegate.addPropertyValue("continueOnError", continueOnError);
// Use a factory bean for the resources so they can be given an order if a pattern is used
BeanDefinitionBuilder resourcesFactory = BeanDefinitionBuilder.genericBeanDefinition(SortedResourcesFactoryBean.class);
resourcesFactory.addConstructorArgValue(new TypedStringValue(scriptElement.getAttribute("location")));
delegate.addPropertyValue("scripts", resourcesFactory.getBeanDefinition());
if (StringUtils.hasLength(scriptElement.getAttribute("encoding"))) {
delegate.addPropertyValue("sqlScriptEncoding", new TypedStringValue(scriptElement.getAttribute("encoding")));
}
String separator = getSeparator(element, scriptElement);
if (separator != null) {
delegate.addPropertyValue("separator", new TypedStringValue(separator));
}
delegates.add(delegate.getBeanDefinition());
}
builder.addPropertyValue("populators", delegates);
return builder.getBeanDefinition();
}
@Nullable
private static String getSeparator(Element element, Element scriptElement) {
String scriptSeparator = scriptElement.getAttribute("separator");
if (StringUtils.hasLength(scriptSeparator)) {
return scriptSeparator;
}
String elementSeparator = element.getAttribute("separator");
if (StringUtils.hasLength(elementSeparator)) {
return elementSeparator;
}
return null;
}
}
|
/* ====================================================================
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.poi.hssf.extractor;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
*
*/
public final class TestExcelExtractor extends TestCase {
private static ExcelExtractor createExtractor(String sampleFileName) {
InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName);
try {
return new ExcelExtractor(new POIFSFileSystem(is));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void testSimple() throws IOException {
ExcelExtractor extractor = createExtractor("Simple.xls");
try {
assertEquals("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.getText());
// Now turn off sheet names
extractor.setIncludeSheetNames(false);
assertEquals("replaceMe\n", extractor.getText());
} finally {
extractor.close();
}
}
public void testNumericFormula() {
ExcelExtractor extractor = createExtractor("sumifformula.xls");
assertEquals(
"Sheet1\n" +
"1000\t1\t5\n" +
"2000\t2\n" +
"3000\t3\n" +
"4000\t4\n" +
"5000\t5\n" +
"Sheet2\nSheet3\n",
extractor.getText()
);
extractor.setFormulasNotResults(true);
assertEquals(
"Sheet1\n" +
"1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" +
"2000\t2\n" +
"3000\t3\n" +
"4000\t4\n" +
"5000\t5\n" +
"Sheet2\nSheet3\n",
extractor.getText()
);
}
public void testwithContinueRecords() {
ExcelExtractor extractor = createExtractor("StringContinueRecords.xls");
extractor.getText();
// Has masses of text
// Until we fixed bug #41064, this would've
// failed by now
assertTrue(extractor.getText().length() > 40960);
}
public void testStringConcat() {
ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls");
// Comes out as NaN if treated as a number
// And as XYZ if treated as a string
assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", extractor.getText());
extractor.setFormulasNotResults(true);
assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText());
}
public void testStringFormula() {
ExcelExtractor extractor = createExtractor("StringFormulas.xls");
// Comes out as NaN if treated as a number
// And as XYZ if treated as a string
assertEquals("Sheet1\nXYZ\nSheet2\nSheet3\n", extractor.getText());
extractor.setFormulasNotResults(true);
assertEquals("Sheet1\nUPPER(\"xyz\")\nSheet2\nSheet3\n", extractor.getText());
}
public void testEventExtractor() throws Exception {
// First up, a simple file with string
// based formulas in it
EventBasedExcelExtractor extractor = new EventBasedExcelExtractor(
new POIFSFileSystem(
HSSFTestDataSamples.openSampleFileStream("SimpleWithFormula.xls")
)
);
try {
extractor.setIncludeSheetNames(true);
String text = extractor.getText();
assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", text);
extractor.setIncludeSheetNames(false);
extractor.setFormulasNotResults(true);
text = extractor.getText();
assertEquals("replaceme\nreplaceme\nCONCATENATE(A1,A2)\n", text);
// Now, a slightly longer file with numeric formulas
extractor = new EventBasedExcelExtractor(
new POIFSFileSystem(
HSSFTestDataSamples.openSampleFileStream("sumifformula.xls")
)
);
extractor.setIncludeSheetNames(false);
extractor.setFormulasNotResults(true);
text = extractor.getText();
assertEquals(
"1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" +
"2000\t2\n" +
"3000\t3\n" +
"4000\t4\n" +
"5000\t5\n",
text
);
} finally {
extractor.close();
}
}
public void testWithComments() {
ExcelExtractor extractor = createExtractor("SimpleWithComments.xls");
extractor.setIncludeSheetNames(false);
// Check without comments
assertEquals(
"1\tone\n" +
"2\ttwo\n" +
"3\tthree\n",
extractor.getText()
);
// Now with
extractor.setIncludeCellComments(true);
assertEquals(
"1\tone Comment by Yegor Kozlov: Yegor Kozlov: first cell\n" +
"2\ttwo Comment by Yegor Kozlov: Yegor Kozlov: second cell\n" +
"3\tthree Comment by Yegor Kozlov: Yegor Kozlov: third cell\n",
extractor.getText()
);
}
public void testWithBlank() {
ExcelExtractor extractor = createExtractor("MissingBits.xls");
String def = extractor.getText();
extractor.setIncludeBlankCells(true);
String padded = extractor.getText();
assertTrue(def.startsWith(
"Sheet1\n" +
"&[TAB]\t\n" +
"Hello\n" +
"11\t23\n"
));
assertTrue(padded.startsWith(
"Sheet1\n" +
"&[TAB]\t\n" +
"Hello\n" +
"11\t\t\t23\n"
));
}
public void testFormatting() throws Exception {
ExcelExtractor extractor = createExtractor("Formatting.xls");
extractor.setIncludeBlankCells(false);
extractor.setIncludeSheetNames(false);
String text = extractor.getText();
// Note - not all the formats in the file
// actually quite match what they claim to
// be, as some are auto-local builtins...
assertTrue(text.startsWith(
"Dates, all 24th November 2006\n"
));
assertTrue(
text.indexOf(
"yyyy/mm/dd\t2006/11/24\n"
) > -1
);
assertTrue(
text.indexOf(
"yyyy-mm-dd\t2006-11-24\n"
) > -1
);
assertTrue(
text.indexOf(
"dd-mm-yy\t24-11-06\n"
) > -1
);
assertTrue("Had: " + text + ", but should contain 'nn.nn\\t10.52\\n'",
text.indexOf(
"nn.nn\t10.52\n"
) > -1
);
assertTrue(
text.indexOf(
"nn.nnn\t10.520\n"
) > -1
);
assertTrue(
text.indexOf(
"\u00a3nn.nn\t\u00a310.52\n"
) > -1
);
}
/**
* Embeded in a non-excel file
*/
public void testWithEmbeded() throws Exception {
POIFSFileSystem fs = new POIFSFileSystem(
POIDataSamples.getDocumentInstance().openResourceAsStream("word_with_embeded.doc")
);
DirectoryNode objPool = (DirectoryNode) fs.getRoot().getEntry("ObjectPool");
DirectoryNode dirA = (DirectoryNode) objPool.getEntry("_1269427460");
DirectoryNode dirB = (DirectoryNode) objPool.getEntry("_1269427461");
HSSFWorkbook wbA = new HSSFWorkbook(dirA, fs, true);
HSSFWorkbook wbB = new HSSFWorkbook(dirB, fs, true);
ExcelExtractor exA = new ExcelExtractor(wbA);
try {
ExcelExtractor exB = new ExcelExtractor(wbB);
try {
assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n",
exA.getText());
assertEquals("Sample Excel", exA.getSummaryInformation().getTitle());
assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n",
exB.getText());
assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle());
} finally {
exB.close();
}
} finally {
exA.close();
}
}
/**
* Excel embeded in excel
*/
public void testWithEmbededInOwn() throws Exception {
POIDataSamples ssSamples = POIDataSamples.getSpreadSheetInstance();
POIFSFileSystem fs = new POIFSFileSystem(
ssSamples.openResourceAsStream("excel_with_embeded.xls")
);
DirectoryNode dirA = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B5");
DirectoryNode dirB = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B4");
HSSFWorkbook wbA = new HSSFWorkbook(dirA, fs, true);
HSSFWorkbook wbB = new HSSFWorkbook(dirB, fs, true);
ExcelExtractor exA = new ExcelExtractor(wbA);
try {
ExcelExtractor exB = new ExcelExtractor(wbB);
try {
assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n",
exA.getText());
assertEquals("Sample Excel", exA.getSummaryInformation().getTitle());
assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n",
exB.getText());
assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle());
// And the base file too
ExcelExtractor ex = new ExcelExtractor(fs);
try {
assertEquals("Sheet1\nI have lots of embeded files in me\nSheet2\nSheet3\n",
ex.getText());
assertEquals("Excel With Embeded", ex.getSummaryInformation().getTitle());
} finally {
ex.close();
}
} finally {
exB.close();
}
} finally {
exA.close();
}
}
/**
* Test that we get text from headers and footers
*/
public void test45538() {
String[] files = {
"45538_classic_Footer.xls", "45538_form_Footer.xls",
"45538_classic_Header.xls", "45538_form_Header.xls"
};
for(int i=0; i<files.length; i++) {
ExcelExtractor extractor = createExtractor(files[i]);
String text = extractor.getText();
assertTrue("Unable to find expected word in text\n" + text, text.indexOf("testdoc") >=0);
assertTrue("Unable to find expected word in text\n" + text, text.indexOf("test phrase") >= 0);
}
}
public void testPassword() {
Biff8EncryptionKey.setCurrentUserPassword("password");
ExcelExtractor extractor = createExtractor("password.xls");
String text = extractor.getText();
Biff8EncryptionKey.setCurrentUserPassword(null);
assertTrue(text.contains("ZIP"));
}
public void testNullPointerException() {
ExcelExtractor extractor = createExtractor("ar.org.apsme.www_Form%20Inscripcion%20Curso%20NO%20Socios.xls");
assertNotNull(extractor);
assertNotNull(extractor.getText());
}
}
|
package com.atguigu.gmall.sms.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 首页专题表【jd首页下面很多专题,每个专题链接新的页面,展示专题商品信息】
*
* @author fcy
* @email lxf@atguigu.com
* @date 2020-01-27 14:10:38
*/
@ApiModel
@Data
@TableName("sms_home_subject")
public class HomeSubjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
@ApiModelProperty(name = "id",value = "id")
private Long id;
/**
* 专题名字
*/
@ApiModelProperty(name = "name",value = "专题名字")
private String name;
/**
* 专题标题
*/
@ApiModelProperty(name = "title",value = "专题标题")
private String title;
/**
* 专题副标题
*/
@ApiModelProperty(name = "subTitle",value = "专题副标题")
private String subTitle;
/**
* 显示状态
*/
@ApiModelProperty(name = "status",value = "显示状态")
private Integer status;
/**
* 详情连接
*/
@ApiModelProperty(name = "url",value = "详情连接")
private String url;
/**
* 排序
*/
@ApiModelProperty(name = "sort",value = "排序")
private Integer sort;
/**
* 专题图片地址
*/
@ApiModelProperty(name = "img",value = "专题图片地址")
private String img;
}
|
package org.cloudfoundry.identity.uaa.mfa;
import com.google.common.collect.Lists;
import org.cloudfoundry.identity.uaa.login.util.RandomValueStringGenerator;
import org.cloudfoundry.identity.uaa.zone.IdentityZone;
import org.cloudfoundry.identity.uaa.zone.IdentityZoneProvisioning;
import org.cloudfoundry.identity.uaa.zone.MfaConfig;
import org.cloudfoundry.identity.uaa.zone.MultitenancyFixture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.provider.ArgumentsSource;
import java.util.Arrays;
import java.util.stream.Stream;
import static org.cloudfoundry.identity.uaa.constants.OriginKeys.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
class MfaCheckerTests {
private IdentityZone identityZone;
private MfaChecker mfaChecker;
private IdentityZoneProvisioning mockIdentityZoneProvisioning;
private RandomValueStringGenerator randomValueStringGenerator;
@BeforeEach
void setUp() {
randomValueStringGenerator = new RandomValueStringGenerator();
identityZone = MultitenancyFixture.identityZone(randomValueStringGenerator.generate(), randomValueStringGenerator.generate());
mockIdentityZoneProvisioning = mock(IdentityZoneProvisioning.class);
when(mockIdentityZoneProvisioning.retrieve(any())).thenReturn(identityZone);
mfaChecker = new MfaChecker(mockIdentityZoneProvisioning);
}
static class BooleanArgumentsProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
return Stream.of(
Arguments.of(true),
Arguments.of(false)
);
}
}
@ParameterizedTest
@ArgumentsSource(BooleanArgumentsProvider.class)
void isMfaEnabled(final boolean isMfaEnabled) {
identityZone.getConfig().getMfaConfig().setEnabled(isMfaEnabled);
assertEquals(isMfaEnabled, mfaChecker.isMfaEnabled(identityZone));
}
@ParameterizedTest
@ArgumentsSource(BooleanArgumentsProvider.class)
void isMfaEnabledForZoneId(final boolean isMfaEnabled) {
final String zoneId = randomValueStringGenerator.generate();
identityZone.getConfig().getMfaConfig().setEnabled(isMfaEnabled);
assertEquals(isMfaEnabled, mfaChecker.isMfaEnabledForZoneId(zoneId));
verify(mockIdentityZoneProvisioning).retrieve(zoneId);
}
@Test
void mfaIsRequiredWhenCorrectOriginsAreConfigured() {
final String randomIdp = randomValueStringGenerator.generate();
identityZone.getConfig().getMfaConfig().setIdentityProviders(
Lists.newArrayList("uaa", "george", randomIdp));
assertThat(mfaChecker.isRequired(identityZone, "uaa"), is(true));
assertThat(mfaChecker.isRequired(identityZone, "george"), is(true));
assertThat(mfaChecker.isRequired(identityZone, randomIdp), is(true));
assertThat(mfaChecker.isRequired(identityZone, "other"), is(false));
assertThat(mfaChecker.isRequired(identityZone, null), is(false));
assertThat(mfaChecker.isRequired(identityZone, ""), is(false));
assertThat(mfaChecker.isRequired(identityZone, randomValueStringGenerator.generate()), is(false));
}
@Test
void mfaConfig_getIdentityProviders_returnsUaaAndLdap() {
assertThat(MfaConfig.DEFAULT_MFA_IDENTITY_PROVIDERS, is(Arrays.asList(UAA, LDAP)));
identityZone.getConfig().getMfaConfig().setIdentityProviders(
Lists.newArrayList());
assertThat(mfaChecker.isRequired(identityZone, UAA), is(true));
assertThat(mfaChecker.isRequired(identityZone, LDAP), is(true));
assertThat(mfaChecker.isRequired(identityZone, SAML), is(false));
assertThat(mfaChecker.isRequired(identityZone, "other"), is(false));
}
}
|
package com.plivo.plivoaddressbook.utils;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.text.TextUtils;
import com.plivo.plivoaddressbook.model.Call;
import com.plivo.plivoaddressbook.model.Contact;
import java.util.ArrayList;
import java.util.List;
import static androidx.core.content.PermissionChecker.checkSelfPermission;
public class ContactUtils {
public static final String[] CONTACTS_COLUMNS = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI
};
private Context context;
public ContactUtils(Context context) {
this.context = context;
}
public List<Call> getCallLog() {
List<Call> calls = new ArrayList<>();
Cursor c = getCallLogProvider();
c.moveToFirst();
do{
String callerID = c.getString(c.getColumnIndex(CallLog.Calls._ID));
String callerNumber = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
long callDateandTime = c.getLong(c.getColumnIndex(CallLog.Calls.DATE));
long callDuration = c.getLong(c.getColumnIndex(CallLog.Calls.DURATION));
int callType = c.getInt(c.getColumnIndex(CallLog.Calls.TYPE));
calls.add(new Call.Builder()
.setType(
callType == CallLog.Calls.INCOMING_TYPE ? Call.TYPE.INCOMING:
callType == CallLog.Calls.OUTGOING_TYPE ? Call.TYPE.OUTGOING:
Call.TYPE.MISSED)
.setCreatedAt(callDateandTime)
.setId(callerID)
.setDuration(callDuration)
.setContact(getContact(callerNumber))
.build());
} while(c.moveToNext());
c.close();
return calls;
}
private Cursor getCallLogProvider() {
if (checkSelfPermission(context, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
return null;
}
String[] projection = new String[] {
CallLog.Calls._ID,
CallLog.Calls.NUMBER,
CallLog.Calls.DATE,
CallLog.Calls.DURATION,
CallLog.Calls.TYPE
};
Cursor c = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
projection,
null,
null,
CallLog.Calls.DATE + " DESC");
return c.getCount() > 0 ? c : null;
}
public Contact getContact(String phone_number) {
Cursor c = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
CONTACTS_COLUMNS,
ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?",
new String[]{phone_number},
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " COLLATE LOCALIZED ASC");
if (c.moveToNext()) {
String displayName = c.getString(c.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME_PRIMARY));
String displayNumber = c.getString(c.getColumnIndex(ContactsContract.PhoneLookup.NUMBER));
String displayThumbnailUri = c.getString(c.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI));
c.close();
return new Contact.Builder()
.setName(displayName)
.setPhoneNumber(displayNumber)
.setPhotoUri(Uri.parse(displayThumbnailUri))
.build();
}
return new Contact.Builder()
.setName(phone_number)
.setPhoneNumber(phone_number)
.build();
}
public List<Contact> getAllContacts() {
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
CONTACTS_COLUMNS,
null,
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " ASC");
List<Contact> contactList = new ArrayList<>();
while (c.moveToNext()) {
String name=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
String phoneNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(new Contact.Builder()
.setName(name)
.setPhoneNumber(phoneNumber)
.build());
}
c.close();
return contactList;
}
}
|
package me.galaxy.sample;
import me.galaxy.task.EnableTask;
import me.galaxy.task.Task;
import me.galaxy.task.TaskResult;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.concurrent.Future;
@EnableTask
@Service
public class TestService {
@Task(name = "send", retryTimes = 3)
public ListenableFuture<String> send(String msg) {
try {
Thread.sleep(1000);
System.out.println(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
throw new RuntimeException("错误");
// return new TaskResult<String>("ok");
}
@Task(retryTimes = 1)
public void send2() {
try {
Thread.sleep(1000);
System.out.println("haha");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
/**
* Copyright (c) 2008-2010 Ardor Labs, Inc.
*
* This file is part of Ardor3D.
*
* Ardor3D is free software: you can redistribute it and/or modify it
* under the terms of its license which may be found in the accompanying
* LICENSE file or at <http://www.ardor3d.com/LICENSE>.
*/
package com.ardor3d.scenegraph;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Quaternion;
import com.ardor3d.math.Transform;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.IndexMode;
import com.ardor3d.renderer.RenderContext;
import com.ardor3d.util.export.InputCapsule;
import com.ardor3d.util.export.OutputCapsule;
import com.ardor3d.util.export.Savable;
import com.ardor3d.util.geom.BufferUtils;
import com.google.common.collect.MapMaker;
/**
* MeshData contains all the commonly used buffers for rendering a mesh.
*/
public class MeshData implements Savable {
/** The Constant logger. */
private static final Logger logger = Logger.getLogger(MeshData.class.getName());
/** A cache of ids for interleaved use. */
private transient Map<Object, Integer> _vboIdCache = null;
/** Number of vertices represented by this data. */
protected int _vertexCount;
/** Number of primitives represented by this data. */
protected transient int[] _primitiveCounts = new int[1];
/** Buffer data holding buffers and number of coordinates per vertex */
protected FloatBufferData _vertexCoords;
protected FloatBufferData _normalCoords;
protected FloatBufferData _colorCoords;
protected FloatBufferData _fogCoords;
protected FloatBufferData _tangentCoords;
protected List<FloatBufferData> _textureCoords = new ArrayList<FloatBufferData>(1);
/** Interleaved data (for VBO id use). */
protected FloatBufferData _interleaved;
/** Index data. */
protected IndexBufferData<?> _indexBuffer;
protected int[] _indexLengths;
protected IndexMode[] _indexModes = new IndexMode[] { IndexMode.Triangles };
/**
* Gets the vertex count.
*
* @return the vertex count
*/
public int getVertexCount() {
return _vertexCount;
}
/**
* Gets the vertex buffer.
*
* @return the vertex buffer
*/
public FloatBuffer getVertexBuffer() {
if (_vertexCoords == null) {
return null;
}
return _vertexCoords.getBuffer();
}
/**
* Sets the vertex buffer.
*
* @param vertexBuffer
* the new vertex buffer
*/
public void setVertexBuffer(final FloatBuffer vertexBuffer) {
if (vertexBuffer == null) {
setVertexCoords(null);
} else {
setVertexCoords(new FloatBufferData(vertexBuffer, 3));
}
refreshInterleaved();
}
/**
* Gets the vertex coords.
*
* @return the vertex coords
*/
public FloatBufferData getVertexCoords() {
return _vertexCoords;
}
private void refreshInterleaved() {
if (_interleaved != null) {
_interleaved.setNeedsRefresh(true);
}
}
/**
* Sets the vertex coords.
*
* @param bufferData
* the new vertex coords
*/
public void setVertexCoords(final FloatBufferData bufferData) {
_vertexCoords = bufferData;
updateVertexCount();
refreshInterleaved();
}
/**
* Gets the normal buffer.
*
* @return the normal buffer
*/
public FloatBuffer getNormalBuffer() {
if (_normalCoords == null) {
return null;
}
return _normalCoords.getBuffer();
}
/**
* Sets the normal buffer.
*
* @param normalBuffer
* the new normal buffer
*/
public void setNormalBuffer(final FloatBuffer normalBuffer) {
if (normalBuffer == null) {
_normalCoords = null;
} else {
_normalCoords = new FloatBufferData(normalBuffer, 3);
}
refreshInterleaved();
}
/**
* Gets the normal coords.
*
* @return the normal coords
*/
public FloatBufferData getNormalCoords() {
return _normalCoords;
}
/**
* Sets the normal coords.
*
* @param bufferData
* the new normal coords
*/
public void setNormalCoords(final FloatBufferData bufferData) {
_normalCoords = bufferData;
refreshInterleaved();
}
/**
* Gets the color buffer.
*
* @return the color buffer
*/
public FloatBuffer getColorBuffer() {
if (_colorCoords == null) {
return null;
}
return _colorCoords.getBuffer();
}
/**
* Sets the color buffer.
*
* @param colorBuffer
* the new color buffer
*/
public void setColorBuffer(final FloatBuffer colorBuffer) {
if (colorBuffer == null) {
_colorCoords = null;
} else {
_colorCoords = new FloatBufferData(colorBuffer, 4);
}
refreshInterleaved();
}
/**
* Gets the color coords.
*
* @return the color coords
*/
public FloatBufferData getColorCoords() {
return _colorCoords;
}
/**
* Sets the color coords.
*
* @param bufferData
* the new color coords
*/
public void setColorCoords(final FloatBufferData bufferData) {
_colorCoords = bufferData;
refreshInterleaved();
}
/**
* Gets the fog buffer.
*
* @return the fog buffer
*/
public FloatBuffer getFogBuffer() {
if (_fogCoords == null) {
return null;
}
return _fogCoords.getBuffer();
}
/**
* Sets the fog buffer.
*
* @param fogBuffer
* the new fog buffer
*/
public void setFogBuffer(final FloatBuffer fogBuffer) {
if (fogBuffer == null) {
_fogCoords = null;
} else {
_fogCoords = new FloatBufferData(fogBuffer, 3);
}
}
/**
* Gets the fog coords.
*
* @return the fog coords
*/
public FloatBufferData getFogCoords() {
return _fogCoords;
}
/**
* Sets the fog coords.
*
* @param bufferData
* the new fog coords
*/
public void setFogCoords(final FloatBufferData bufferData) {
_fogCoords = bufferData;
}
/**
* Gets the tangent buffer.
*
* @return the tangent buffer
*/
public FloatBuffer getTangentBuffer() {
if (_tangentCoords == null) {
return null;
}
return _tangentCoords.getBuffer();
}
/**
* Sets the tangent buffer.
*
* @param tangentBuffer
* the new tangent buffer
*/
public void setTangentBuffer(final FloatBuffer tangentBuffer) {
if (tangentBuffer == null) {
_tangentCoords = null;
} else {
_tangentCoords = new FloatBufferData(tangentBuffer, 3);
}
}
/**
* Gets the tangent coords.
*
* @return the tangent coords
*/
public FloatBufferData getTangentCoords() {
return _tangentCoords;
}
/**
* Sets the tangent coords.
*
* @param bufferData
* the new tangent coords
*/
public void setTangentCoords(final FloatBufferData bufferData) {
_tangentCoords = bufferData;
}
/**
* Gets the texture buffer.
*
* @param index
* the index
*
* @return the texture buffer
*/
public FloatBuffer getTextureBuffer(final int index) {
if (_textureCoords.size() <= index) {
return null;
}
final FloatBufferData textureCoord = _textureCoords.get(index);
if (textureCoord == null) {
return null;
}
return textureCoord.getBuffer();
}
/**
* Sets the texture buffer.
*
* @param textureBuffer
* the texture buffer
* @param index
* the index
*/
public void setTextureBuffer(final FloatBuffer textureBuffer, final int index) {
while (_textureCoords.size() <= index) {
_textureCoords.add(null);
}
_textureCoords.set(index, new FloatBufferData(textureBuffer, 2));
refreshInterleaved();
}
/**
* Gets the texture coords.
*
* @return the texture coords
*/
public List<FloatBufferData> getTextureCoords() {
return _textureCoords;
}
/**
* Gets the texture coords.
*
* @param index
* the index
*
* @return the texture coords
*/
public FloatBufferData getTextureCoords(final int index) {
if (_textureCoords.size() <= index) {
return null;
}
return _textureCoords.get(index);
}
/**
* Sets the texture coords.
*
* @param textureCoords
* the new texture coords
*/
public void setTextureCoords(final List<FloatBufferData> textureCoords) {
_textureCoords = textureCoords;
refreshInterleaved();
}
/**
* Sets the texture coords.
*
* @param textureCoords
* the texture coords
* @param index
* the index
*/
public void setTextureCoords(final FloatBufferData textureCoords, final int index) {
while (_textureCoords.size() <= index) {
_textureCoords.add(null);
}
_textureCoords.set(index, textureCoords);
refreshInterleaved();
}
/**
* Retrieves the interleaved buffer, if set or created through packInterleaved.
*
* @return the interleaved buffer
*/
public FloatBuffer getInterleavedBuffer() {
if (_interleaved == null) {
return null;
}
return _interleaved.getBuffer();
}
/**
* Gets the interleaved data.
*
* @return the interleaved data
*/
public FloatBufferData getInterleavedData() {
return _interleaved;
}
/**
* Sets the interleaved buffer.
*
* @param interleavedBuffer
* the interleaved buffer
*/
public void setInterleavedData(final FloatBufferData interleavedData) {
_interleaved = interleavedData;
refreshInterleaved();
}
/**
* Update the vertex count based on the current limit of the vertex buffer.
*/
public void updateVertexCount() {
if (_vertexCoords == null) {
_vertexCount = 0;
} else {
_vertexCount = _vertexCoords.getTupleCount();
}
// update primitive count if we are using arrays
if (_indexBuffer == null) {
updatePrimitiveCounts();
}
}
/**
* <code>copyTextureCoords</code> copies the texture coordinates of a given texture unit to another location. If the
* texture unit is not valid, then the coordinates are ignored. Coords are multiplied by the given factor.
*
* @param fromIndex
* the coordinates to copy.
* @param toIndex
* the texture unit to set them to. Must not be the same as the fromIndex.
* @param factor
* a multiple to apply when copying
*/
public void copyTextureCoordinates(final int fromIndex, final int toIndex, final float factor) {
if (_textureCoords == null) {
return;
}
if (fromIndex < 0 || fromIndex >= _textureCoords.size() || _textureCoords.get(fromIndex) == null) {
return;
}
if (toIndex < 0 || toIndex == fromIndex) {
return;
}
// make sure we are big enough
while (toIndex >= _textureCoords.size()) {
_textureCoords.add(null);
}
FloatBufferData dest = _textureCoords.get(toIndex);
final FloatBufferData src = _textureCoords.get(fromIndex);
if (dest == null || dest.getBuffer().capacity() != src.getBuffer().limit()) {
dest = new FloatBufferData(BufferUtils.createFloatBuffer(src.getBuffer().capacity()),
src.getValuesPerTuple());
_textureCoords.set(toIndex, dest);
}
dest.getBuffer().clear();
final int oldLimit = src.getBuffer().limit();
src.getBuffer().clear();
for (int i = 0, len = dest.getBuffer().capacity(); i < len; i++) {
dest.getBuffer().put(factor * src.getBuffer().get());
}
src.getBuffer().limit(oldLimit);
dest.getBuffer().limit(oldLimit);
}
/**
* <code>copyTextureCoords</code> copies the texture coordinates of a given texture unit to another location. If the
* texture unit is not valid, then the coordinates are ignored. Coords are multiplied by the given S and T factors.
*
* @param fromIndex
* the coordinates to copy.
* @param toIndex
* the texture unit to set them to. Must not be the same as the fromIndex.
* @param factorS
* a multiple to apply to the S channel when copying
* @param factorT
* a multiple to apply to the T channel when copying
*/
public void copyTextureCoordinates(final int fromIndex, final int toIndex, final float factorS, final float factorT) {
if (_textureCoords == null) {
return;
}
if (fromIndex < 0 || fromIndex >= _textureCoords.size() || _textureCoords.get(fromIndex) == null) {
return;
}
if (toIndex < 0 || toIndex == fromIndex) {
return;
}
// make sure we are big enough
while (toIndex >= _textureCoords.size()) {
_textureCoords.add(null);
}
FloatBufferData dest = _textureCoords.get(toIndex);
final FloatBufferData src = _textureCoords.get(fromIndex);
if (dest == null || dest.getBuffer().capacity() != src.getBuffer().limit()) {
dest = new FloatBufferData(BufferUtils.createFloatBuffer(src.getBuffer().capacity()),
src.getValuesPerTuple());
_textureCoords.set(toIndex, dest);
}
dest.getBuffer().clear();
final int oldLimit = src.getBuffer().limit();
src.getBuffer().clear();
for (int i = 0, len = dest.getBuffer().capacity(); i < len; i++) {
if (i % 2 == 0) {
dest.getBuffer().put(factorS * src.getBuffer().get());
} else {
dest.getBuffer().put(factorT * src.getBuffer().get());
}
}
src.getBuffer().limit(oldLimit);
dest.getBuffer().limit(oldLimit);
}
/**
* <code>getNumberOfUnits</code> returns the number of texture units this geometry is currently using.
*
* @return the number of texture units in use.
*/
public int getNumberOfUnits() {
if (_textureCoords == null) {
return 0;
}
return _textureCoords.size();
}
/**
* Gets the index buffer.
*
* @return the index buffer
*/
public Buffer getIndexBuffer() {
if (_indexBuffer == null) {
return null;
}
return _indexBuffer.getBuffer();
}
/**
* Sets the index buffer.
*
* @param indices
* the new index buffer
*/
public void setIndexBuffer(final IntBuffer indices) {
if (indices == null) {
_indexBuffer = null;
} else {
_indexBuffer = new IntBufferData(indices);
}
updatePrimitiveCounts();
refreshInterleaved();
}
/**
* Sets the index buffer.
*
* @param indices
* the new index buffer
*/
public void setIndexBuffer(final ShortBuffer indices) {
if (indices == null) {
_indexBuffer = null;
} else {
_indexBuffer = new ShortBufferData(indices);
}
updatePrimitiveCounts();
refreshInterleaved();
}
/**
* Sets the index buffer.
*
* @param indices
* the new index buffer
*/
public void setIndexBuffer(final ByteBuffer indices) {
if (indices == null) {
_indexBuffer = null;
} else {
_indexBuffer = new ByteBufferData(indices);
}
updatePrimitiveCounts();
refreshInterleaved();
}
/**
* Gets the indices.
*
* @return the indices
*/
public IndexBufferData<?> getIndices() {
return _indexBuffer;
}
/**
* Sets the indices
*
* @param bufferData
* the new indices
*/
public void setIndices(final IndexBufferData<?> bufferData) {
_indexBuffer = bufferData;
updatePrimitiveCounts();
refreshInterleaved();
}
/**
* Gets the index mode.
*
* @return the IndexMode of the first section of this MeshData.
* @deprecated Please switch to {@link #getIndexMode(int)}
*/
@Deprecated
public IndexMode getIndexMode() {
return getIndexMode(0);
}
/**
* Sets the index mode.
*
* @param indexMode
* the new IndexMode to use for the first section of this MeshData.
*/
public void setIndexMode(final IndexMode indexMode) {
_indexModes[0] = indexMode;
updatePrimitiveCounts();
refreshInterleaved();
}
/**
* Gets the index lengths.
*
* @return the index lengths
*/
public int[] getIndexLengths() {
return _indexLengths;
}
/**
* Sets the index lengths.
*
* @param indexLengths
* the new index lengths
*/
public void setIndexLengths(final int[] indexLengths) {
_indexLengths = indexLengths;
updatePrimitiveCounts();
refreshInterleaved();
}
/**
* Gets the index modes.
*
* @return the index modes
*/
public IndexMode[] getIndexModes() {
return _indexModes;
}
/**
* Gets the index mode.
*
* @param sectionIndex
* the section index
*
* @return the index mode
*/
public IndexMode getIndexMode(final int sectionIndex) {
if (sectionIndex < 0 || sectionIndex >= getSectionCount()) {
throw new IllegalArgumentException("invalid section index: " + sectionIndex);
}
return _indexModes.length > sectionIndex ? _indexModes[sectionIndex] : _indexModes[_indexModes.length - 1];
}
/**
* Note: Also updates primitive counts.
*
* @param indexModes
* the index modes to use for this MeshData.
*/
public void setIndexModes(final IndexMode[] indexModes) {
_indexModes = indexModes;
updatePrimitiveCounts();
refreshInterleaved();
}
/**
* Gets the section count.
*
* @return the number of sections (lengths, indexModes, etc.) this MeshData contains.
*/
public int getSectionCount() {
return _indexLengths != null ? _indexLengths.length : 1;
}
/**
* Gets the total primitive count.
*
* @return the sum of the primitive counts on all sections of this mesh data.
*/
public int getTotalPrimitiveCount() {
int count = 0;
for (int i = 0; i < _primitiveCounts.length; i++) {
count += _primitiveCounts[i];
}
return count;
}
/**
* Gets the primitive count.
*
* @param section
* the section
*
* @return the number of primitives (triangles, quads, lines, points, etc.) on a given section of this mesh data.
*/
public int getPrimitiveCount(final int section) {
return _primitiveCounts[section];
}
/**
* Returns the vertex indices of a specified primitive.
*
* @param primitiveIndex
* which triangle, quad, etc
* @param section
* which section to pull from (corresponds to array position in indexmodes and lengths)
* @param store
* an int array to store the results in. if null, or the length < the size of the primitive, a new array
* is created and returned.
*
* @return the primitive's vertex indices as an array
*
* @throws IndexOutOfBoundsException
* if primitiveIndex is outside of range [0, count-1] where count is the number of primitives in the
* given section.
* @throws ArrayIndexOutOfBoundsException
* if section is out of range [0, N-1] where N is the number of sections in this MeshData object.
*/
public int[] getPrimitive(final int primitiveIndex, final int section, final int[] store) {
final int count = getPrimitiveCount(section);
if (primitiveIndex >= count || primitiveIndex < 0) {
throw new IndexOutOfBoundsException("Invalid primitiveIndex '" + primitiveIndex + "'. Count is " + count);
}
final IndexMode mode = getIndexMode(section);
final int rSize = mode.getVertexCount();
int[] result = store;
if (result == null || result.length < rSize) {
result = new int[rSize];
}
for (int i = 0; i < rSize; i++) {
if (getIndexBuffer() != null) {
result[i] = getIndices().get(getVertexIndex(primitiveIndex, i, section));
} else {
result[i] = getVertexIndex(primitiveIndex, i, section);
}
}
return result;
}
/**
* Gets the primitive.
*
* @param primitiveIndex
* the primitive index
* @param section
* the section
* @param store
* the store
*
* @return the primitive
*/
public Vector3[] getPrimitive(final int primitiveIndex, final int section, final Vector3[] store) {
final int count = getPrimitiveCount(section);
if (primitiveIndex >= count || primitiveIndex < 0) {
throw new IndexOutOfBoundsException("Invalid primitiveIndex '" + primitiveIndex + "'. Count is " + count);
}
final IndexMode mode = getIndexMode(section);
final int rSize = mode.getVertexCount();
Vector3[] result = store;
if (result == null || result.length < rSize) {
result = new Vector3[rSize];
}
for (int i = 0; i < rSize; i++) {
if (result[i] == null) {
result[i] = new Vector3();
}
if (getIndexBuffer() != null) {
// indexed geometry
BufferUtils.populateFromBuffer(result[i], getVertexBuffer(),
getIndices().get(getVertexIndex(primitiveIndex, i, section)));
} else {
// non-indexed geometry
BufferUtils
.populateFromBuffer(result[i], getVertexBuffer(), getVertexIndex(primitiveIndex, i, section));
}
}
return result;
}
/**
* Gets the vertex index.
*
* @param primitiveIndex
* which triangle, quad, etc.
* @param point
* which point on the triangle, quad, etc. (triangle has three points, so this would be 0-2, etc.)
* @param section
* which section to pull from (corresponds to array position in indexmodes and lengths)
*
* @return the position you would expect to find the given point in the index buffer
*/
public int getVertexIndex(final int primitiveIndex, final int point, final int section) {
int index = 0;
// move our offset up to the beginning of our section
for (int i = 0; i < section; i++) {
index += _indexLengths[i];
}
// Ok, now pull primitive index based on indexmode.
switch (getIndexMode(section)) {
case Triangles:
index += (primitiveIndex * 3) + point;
break;
case TriangleStrip:
// XXX: Do we need to flip point 0 and 1 on odd primitiveIndex values?
// if (point < 2 && primitiveIndex % 2 == 1) {
// index += primitiveIndex + (point == 0 ? 1 : 0);
// } else {
index += primitiveIndex + point;
// }
break;
case TriangleFan:
if (point == 0) {
index += 0;
} else {
index += primitiveIndex + point;
}
break;
case Quads:
index += (primitiveIndex * 4) + point;
break;
case QuadStrip:
index += (primitiveIndex * 2) + point;
break;
case Points:
index += primitiveIndex;
break;
case Lines:
index += (primitiveIndex * 2) + point;
break;
case LineStrip:
case LineLoop:
index += primitiveIndex + point;
break;
default:
logger.warning("unimplemented index mode: " + getIndexMode(0));
return -1;
}
return index;
}
/**
* Random vertex.
*
* @param store
* the vector object to store the result in. if null, a new one is created.
*
* @return a random vertex from the vertices stored in this MeshData. null is returned if there are no vertices.
*/
public Vector3 randomVertex(final Vector3 store) {
if (_vertexCoords == null) {
return null;
}
Vector3 result = store;
if (result == null) {
result = new Vector3();
}
final int i = MathUtils.nextRandomInt(0, getVertexCount() - 1);
BufferUtils.populateFromBuffer(result, _vertexCoords.getBuffer(), i);
return result;
}
/**
* Random point on primitives.
*
* @param store
* the vector object to store the result in. if null, a new one is created.
*
* @return a random point from the surface of a primitive stored in this MeshData. null is returned if there are no
* vertices or indices.
*/
public Vector3 randomPointOnPrimitives(final Vector3 store) {
if (_vertexCoords == null || _indexBuffer == null) {
return null;
}
Vector3 result = store;
if (result == null) {
result = new Vector3();
}
// randomly pick a section (if there are more than 1)
final int section = MathUtils.nextRandomInt(0, getSectionCount() - 1);
// randomly pick a primitive in that section
final int primitiveIndex = MathUtils.nextRandomInt(0, getPrimitiveCount(section) - 1);
// Now, based on IndexMode, pick a point on that primitive
final IndexMode mode = getIndexMode(section);
final boolean hasIndices = getIndexBuffer() != null;
switch (mode) {
case Triangles:
case TriangleFan:
case TriangleStrip:
case Quads:
case QuadStrip: {
int pntA = getVertexIndex(primitiveIndex, 0, section);
int pntB = getVertexIndex(primitiveIndex, 1, section);
int pntC = getVertexIndex(primitiveIndex, 2, section);
if (hasIndices) {
pntA = getIndices().get(pntA);
pntB = getIndices().get(pntB);
pntC = getIndices().get(pntC);
}
double b = MathUtils.nextRandomDouble();
double c = MathUtils.nextRandomDouble();
if (mode != IndexMode.Quads && mode != IndexMode.QuadStrip) {
// keep it in the triangle by reflecting it across the center diagonal BC
if (b + c > 1) {
b = 1 - b;
c = 1 - c;
}
}
final double a = 1 - b - c;
final Vector3 work = Vector3.fetchTempInstance();
BufferUtils.populateFromBuffer(work, getVertexBuffer(), pntA);
work.multiplyLocal(a);
result.set(work);
BufferUtils.populateFromBuffer(work, getVertexBuffer(), pntB);
work.multiplyLocal(b);
result.addLocal(work);
BufferUtils.populateFromBuffer(work, getVertexBuffer(), pntC);
work.multiplyLocal(c);
result.addLocal(work);
Vector3.releaseTempInstance(work);
break;
}
case Points: {
int pnt = getVertexIndex(primitiveIndex, 0, section);
if (hasIndices) {
pnt = getIndices().get(pnt);
}
BufferUtils.populateFromBuffer(result, getVertexBuffer(), pnt);
break;
}
case Lines:
case LineLoop:
case LineStrip: {
int pntA = getVertexIndex(primitiveIndex, 0, section);
int pntB = getVertexIndex(primitiveIndex, 1, section);
if (hasIndices) {
pntA = getIndices().get(pntA);
pntB = getIndices().get(pntB);
}
final Vector3 work = Vector3.fetchTempInstance();
BufferUtils.populateFromBuffer(result, getVertexBuffer(), pntA);
BufferUtils.populateFromBuffer(work, getVertexBuffer(), pntB);
Vector3.lerp(result, work, MathUtils.nextRandomDouble(), result);
Vector3.releaseTempInstance(work);
break;
}
}
return result;
}
/**
* Translate points.
*
* @param x
* the x
* @param y
* the y
* @param z
* the z
*/
public void translatePoints(final double x, final double y, final double z) {
translatePoints(new Vector3(x, y, z));
}
/**
* Translate points.
*
* @param amount
* the amount
*/
public void translatePoints(final Vector3 amount) {
for (int x = 0; x < _vertexCount; x++) {
BufferUtils.addInBuffer(amount, _vertexCoords.getBuffer(), x);
}
}
public void transformVertices(final Transform transform) {
final Vector3 store = new Vector3();
for (int x = 0; x < _vertexCount; x++) {
BufferUtils.populateFromBuffer(store, _vertexCoords.getBuffer(), x);
transform.applyForward(store, store);
BufferUtils.setInBuffer(store, _vertexCoords.getBuffer(), x);
}
}
public void transformNormals(final Transform transform, final boolean normalize) {
final Vector3 store = new Vector3();
for (int x = 0; x < _vertexCount; x++) {
BufferUtils.populateFromBuffer(store, _normalCoords.getBuffer(), x);
transform.applyForwardVector(store, store);
if (normalize) {
store.normalizeLocal();
}
BufferUtils.setInBuffer(store, _normalCoords.getBuffer(), x);
}
}
/**
* Rotate points.
*
* @param rotate
* the rotate
*/
public void rotatePoints(final Quaternion rotate) {
final Vector3 store = new Vector3();
for (int x = 0; x < _vertexCount; x++) {
BufferUtils.populateFromBuffer(store, _vertexCoords.getBuffer(), x);
rotate.apply(store, store);
BufferUtils.setInBuffer(store, _vertexCoords.getBuffer(), x);
}
}
/**
* Rotate normals.
*
* @param rotate
* the rotate
*/
public void rotateNormals(final Quaternion rotate) {
final Vector3 store = new Vector3();
for (int x = 0; x < _vertexCount; x++) {
BufferUtils.populateFromBuffer(store, _normalCoords.getBuffer(), x);
rotate.apply(store, store);
BufferUtils.setInBuffer(store, _normalCoords.getBuffer(), x);
}
}
/**
* Update primitive counts.
*/
private void updatePrimitiveCounts() {
final int maxIndex = _indexBuffer != null ? _indexBuffer.getBufferLimit() : _vertexCount;
final int maxSection = _indexLengths != null ? _indexLengths.length : 1;
if (_primitiveCounts.length != maxSection) {
_primitiveCounts = new int[maxSection];
}
for (int i = 0; i < maxSection; i++) {
final int size = _indexLengths != null ? _indexLengths[i] : maxIndex;
final int count = IndexMode.getPrimitiveCount(getIndexMode(i), size);
_primitiveCounts[i] = count;
}
}
/**
* @param glContext
* the object representing the OpenGL context a vbo belongs to. See
* {@link RenderContext#getGlContextRep()}
* @return the vbo id of a vbo in the given context. If the vbo is not found in the given context, 0 is returned.
*/
public int getVBOInterleavedID(final Object glContext) {
if (_vboIdCache != null && _vboIdCache.containsKey(glContext)) {
return _vboIdCache.get(glContext);
}
return 0;
}
/**
* Sets the id for a vbo based on interleaving this MeshData's buffer, in regards to the given OpenGL context.
*
* @param glContext
* the object representing the OpenGL context a vbo belongs to. See
* {@link RenderContext#getGlContextRep()}
* @param vboId
* the vbo id of a vbo. To be valid, this must be != 0.
* @throws IllegalArgumentException
* if vboId is equal to 0.
*/
public void setVBOInterleavedID(final Object glContext, final int vboId) {
if (vboId == 0) {
throw new IllegalArgumentException("vboId must != 0");
}
if (_vboIdCache == null) {
_vboIdCache = new MapMaker().initialCapacity(1).weakKeys().makeMap();
}
_vboIdCache.put(glContext, vboId);
}
public MeshData makeCopy() {
final MeshData data = new MeshData();
data._vertexCount = _vertexCount;
data._primitiveCounts = new int[_primitiveCounts.length];
System.arraycopy(_primitiveCounts, 0, data._primitiveCounts, 0, _primitiveCounts.length);
if (_vertexCoords != null) {
data._vertexCoords = _vertexCoords.makeCopy();
}
if (_normalCoords != null) {
data._normalCoords = _normalCoords.makeCopy();
}
if (_colorCoords != null) {
data._colorCoords = _colorCoords.makeCopy();
}
if (_fogCoords != null) {
data._fogCoords = _fogCoords.makeCopy();
}
if (_tangentCoords != null) {
data._tangentCoords = _tangentCoords.makeCopy();
}
for (final FloatBufferData tCoord : _textureCoords) {
if (tCoord != null) {
data._textureCoords.add(tCoord.makeCopy());
} else {
data._textureCoords.add(null);
}
}
if (_indexBuffer != null) {
data._indexBuffer = _indexBuffer.makeCopy();
}
if (_indexLengths != null) {
data._indexLengths = new int[_indexLengths.length];
System.arraycopy(_indexLengths, 0, data._indexLengths, 0, _indexLengths.length);
}
data._indexModes = new IndexMode[_indexModes.length];
System.arraycopy(_indexModes, 0, data._indexModes, 0, _indexModes.length);
return data;
}
// /////////////////
// Methods for Savable
// /////////////////
public Class<? extends MeshData> getClassTag() {
return this.getClass();
}
public void write(final OutputCapsule capsule) throws IOException {
capsule.write(_vertexCount, "vertexCount", 0);
capsule.write(_vertexCoords, "vertexBuffer", null);
capsule.write(_normalCoords, "normalBuffer", null);
capsule.write(_colorCoords, "colorBuffer", null);
capsule.write(_fogCoords, "fogBuffer", null);
capsule.write(_tangentCoords, "tangentBuffer", null);
capsule.writeSavableList(_textureCoords, "textureCoords", new ArrayList<FloatBufferData>(1));
capsule.write((Savable) _indexBuffer, "indexBuffer", null);
capsule.write(_interleaved, "interleaved", null);
capsule.write(_indexLengths, "indexLengths", null);
capsule.write(_indexModes, "indexModes");
}
public void read(final InputCapsule capsule) throws IOException {
_vertexCount = capsule.readInt("vertexCount", 0);
_vertexCoords = (FloatBufferData) capsule.readSavable("vertexBuffer", null);
_normalCoords = (FloatBufferData) capsule.readSavable("normalBuffer", null);
_colorCoords = (FloatBufferData) capsule.readSavable("colorBuffer", null);
_fogCoords = (FloatBufferData) capsule.readSavable("fogBuffer", null);
_tangentCoords = (FloatBufferData) capsule.readSavable("tangentBuffer", null);
_textureCoords = capsule.readSavableList("textureCoords", new ArrayList<FloatBufferData>(1));
_indexBuffer = (IndexBufferData<?>) capsule.readSavable("indexBuffer", null);
_interleaved = (FloatBufferData) capsule.readSavable("interleaved", null);
_indexLengths = capsule.readIntArray("indexLengths", null);
_indexModes = capsule.readEnumArray("indexModes", IndexMode.class, new IndexMode[] { IndexMode.Triangles });
updatePrimitiveCounts();
}
}
|
package live.punkpanda.p2.apnsvoip;
import live.punkpanda.p2.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.X509KeyManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.Socket;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class ClientCertificateKeyManagerVoip implements X509KeyManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientCertificateKeyManagerVoip.class);
private final CertificateFactory certificateFactory;
ClientCertificateKeyManagerVoip() {
try {
certificateFactory = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new AssertionError(e);
}
}
@Override
public String[] getClientAliases(String s, Principal[] principals) {
return new String[0];
}
@Override
public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
return "apple";
}
@Override
public String[] getServerAliases(String s, Principal[] principals) {
return new String[0];
}
@Override
public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
return null;
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
final ApnsVoipPushService.ApnsVoipConfiguration config = Configuration.getInstance().getApnsVoipConfiguration();
final String certificateFile = config == null ? null : config.getCertificate();
if (certificateFile == null) {
LOGGER.error("No client certificate configured");
return new X509Certificate[0];
}
final File file = new File(certificateFile);
try {
final FileInputStream fileInputStream = new FileInputStream(file);
final Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(fileInputStream);
final List<X509Certificate> x509Certificates = new ArrayList<>();
for(Certificate certificate : certificates) {
if (certificate instanceof X509Certificate) {
x509Certificates.add((X509Certificate) certificate);
}
}
return x509Certificates.toArray(new X509Certificate[0]);
} catch (FileNotFoundException | CertificateException e) {
LOGGER.error("Unable to load client certificates", e);
return new X509Certificate[0];
}
}
@Override
public PrivateKey getPrivateKey(String s) {
//openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in /home/daniel/Projects/letsencrypt.sh/certs/gultsch.de/privkey.pem -out privatekey.pem
final ApnsVoipPushService.ApnsVoipConfiguration config = Configuration.getInstance().getApnsVoipConfiguration();
final String privateKeyFile = config == null ? null : config.getPrivateKey();
if (privateKeyFile == null) {
LOGGER.error("Unable to load private key for client certificate authentication. No key configured");
return null;
}
final File file = new File(privateKeyFile);
try {
final String key = Files.lines(file.toPath()).filter(l -> !l.startsWith("----")).collect(Collectors.joining());
final KeyFactory kf = KeyFactory.getInstance("RSA");
final byte[] encodedKey = Base64.getDecoder().decode(key);
final PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(encodedKey);
return kf.generatePrivate(keySpecPKCS8);
} catch (Exception e) {
LOGGER.error("Unable to load private key for client certificate authentication", e);
return null;
}
}
}
|
/*
* Copyright (c) 2010, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of California, Berkeley
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Author: Marco Guazzone (marco.guazzone@gmail.com), 2013.
*/
package radlab.rain.workload.rubbos;
import java.io.IOException;
import java.util.Map;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import radlab.rain.IScoreboard;
/**
* View-Comment operation.
*
* @author <a href="mailto:marco.guazzone@gmail.com">Marco Guazzone</a>
*/
public class ViewCommentOperation extends RubbosOperation
{
public ViewCommentOperation(boolean interactive, IScoreboard scoreboard)
{
super(interactive, scoreboard);
this._operationName = "View-Comment";
this._operationIndex = RubbosGenerator.VIEW_COMMENT_OP;
}
@Override
public void execute() throws Throwable
{
StringBuilder response = null;
// Extract a View-Comment parameters from last response
String scriptName = this.getGenerator().getViewCommentURL();
int pos = scriptName.lastIndexOf('/');
scriptName = scriptName.substring(pos >= 0 ? (pos+1) : 0);
Map<String,String> params = this.getUtility().findViewCommentParamsInHtml(this.getSessionState().getLastResponse(), scriptName);
if (params == null
|| params.isEmpty()
|| !params.containsKey("commentId")
|| !params.containsKey("filter")
|| !params.containsKey("display")
|| !params.containsKey("storyId")
|| !params.containsKey("comment_table"))
{
//this.getLogger().warning("No valid parameter has been found in the last HTML response. Last response is: " + this.getSessionState().getLastResponse() + ". Operation interrupted.");
this.setFailed(false);
this.getGenerator().forceNextOperation(RubbosGenerator.BACK_SPECIAL_OP);
return;
}
URIBuilder uri = new URIBuilder(this.getGenerator().getViewCommentURL());
uri.setParameter("commentId", params.get("commentId"));
uri.setParameter("filter", params.get("filter"));
uri.setParameter("display", params.get("display"));
uri.setParameter("storyId", params.get("storyId"));
uri.setParameter("comment_table", params.get("comment_table"));
HttpGet reqGet = new HttpGet(uri.build());
response = this.getHttpTransport().fetch(reqGet);
this.trace(reqGet.getURI().toString());
if (!this.getGenerator().checkHttpResponse(response.toString()))
{
this.getLogger().severe("Problems in performing request to URL: " + reqGet.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response);
throw new IOException("Problems in performing request to URL: " + reqGet.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")");
}
// Save session data
this.getSessionState().setLastResponse(response.toString());
this.setFailed(!this.getUtility().checkRubbosResponse(response.toString()));
}
}
|
package org.bndly.common.ical.impl.base;
/*-
* #%L
* iCal Impl
* %%
* Copyright (C) 2013 - 2020 Cybercon GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.bndly.common.ical.api.base.Duration;
/**
* Created by alexp on 11.05.15.
*/
public class DurationImpl implements Duration {
private int weeks;
private int days;
private int hours;
private int minutes;
private int seconds;
public DurationImpl(int weeks, int days, int hours, int minutes, int seconds) {
this.weeks = weeks;
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
@Override
public int getWeeks() {
return weeks;
}
@Override
public int getDays() {
return days;
}
@Override
public int getHours() {
return hours;
}
@Override
public int getMinutes() {
return minutes;
}
@Override
public int getSeconds() {
return seconds;
}
}
|
/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.intel.dcsg.cpg.io.file;
import com.intel.mtwilson.pipe.Filter;
import java.io.File;
import java.io.FilenameFilter;
/**
*
* @author jbuhacoff
*/
public class FilenameEndsWithFilter implements FilenameFilter, Filter<File> {
private String endsWith;
public FilenameEndsWithFilter() {
endsWith = null;
}
public FilenameEndsWithFilter(String endsWith) {
this.endsWith = endsWith;
}
/**
* If you are looking for files with an extension like .jar you need
* to include the dot ".jar"
*
* There is no default value; if the value is not set then no files
* will be accepted at all.
*
* @param endsWith
*/
public void setEndsWith(String endsWith) {
this.endsWith = endsWith;
}
public String getEndsWith() {
return endsWith;
}
@Override
public boolean accept(File dir, String name) {
if( endsWith == null || name == null ) { return false; }
return name.endsWith(endsWith);
}
@Override
public boolean accept(File item) {
return item.getName().endsWith(endsWith);
}
}
|
package com.lilithsthrone.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import com.lilithsthrone.game.PropertyValue;
import com.lilithsthrone.game.character.effects.StatusEffect;
import com.lilithsthrone.main.Main;
import javafx.application.Platform;
/**
* Collection of utility functions for date, time and number format conversion.
*
* @since 0.2.11
* @version 0.3.1
* @author Addi
*/
public enum Units {
FORMATTER;
public final int MIN_PRECISION = 0;
public final int MAX_PRECISION = 2;
public final List<String> imperialCountries = Arrays.asList("US", "LR", "MM");
public final List<String> twelveHourCountries = Arrays.asList("US", "UK", "PH", "CA", "AU", "NZ", "IN", "EG", "SA", "CO", "PK", "MY", "SG", "ZA");
DateTimeFormatter shortDate;
DateTimeFormatter longDate;
DateTimeFormatter time;
NumberFormat number;
Locale defaultLocale;
Units() {
defaultLocale = Locale.getDefault();
if (Main.getProperties() == null) {
new NullPointerException("Unit formatters initialized before properties. Assuming auto locale.").printStackTrace();
updateFormats(true);
} else {
updateSettings();
updateFormats(Main.getProperties().hasValue(PropertyValue.autoLocale));
}
}
/**
* Resets the 24-hour and imperial system settings to reflect automatically detected values.
*/
public void updateSettings() {
if (Main.getProperties().hasValue(PropertyValue.autoLocale)) {
String countryCode = defaultLocale.getCountry().toUpperCase();
boolean isMetric = !imperialCountries.contains(countryCode);
Main.getProperties().setValue(PropertyValue.metricSizes, isMetric);
Main.getProperties().setValue(PropertyValue.metricFluids, isMetric);
Main.getProperties().setValue(PropertyValue.metricWeights, isMetric);
Main.getProperties().setValue(PropertyValue.metricWeights, isMetric);
Main.getProperties().setValue(PropertyValue.twentyFourHourTime, !twelveHourCountries.contains(countryCode));
Main.getProperties().setValue(PropertyValue.internationalDate, isMetric);
}
}
/**
* Resets the date formatter depending on the system locale (if automatic) or the imperial number flag (if manual).
* @param autoLocale Determines if automatic or manual detection is used
*/
public void updateDateFormat(boolean autoLocale) {
Locale.setDefault(autoLocale ? defaultLocale : Locale.ENGLISH);
shortDate = (autoLocale ? DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
: DateTimeFormatter.ofPattern(Main.getProperties().hasValue(PropertyValue.internationalDate) ? "MM/dd/yy" : "dd.MM.yy"))
.withZone(ZoneId.systemDefault());
longDate = DateTimeFormatter.ofPattern("d'%o %m' yyyy")
.withZone(ZoneId.systemDefault());
}
/**
* Resets the time formatter depending on the system locale (if automatic) or the 24 hour time flag (if manual).
* @param autoLocale Determines if automatic or manual detection is used
*/
public void updateTimeFormat(boolean autoLocale) {
time = (autoLocale ? DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
: DateTimeFormatter.ofPattern(Main.getProperties().hasValue(PropertyValue.twentyFourHourTime) ? "HH:mm" : "hh:mm a"))
.withZone(ZoneId.systemDefault());
}
/**
* Resets the number formatter depending on the system locale (if automatic), defaulting to English otherwise.
* In all cases, output numbers are rounded correctly to the 2nd fraction digit.
* @param autoLocale Determines if automatic or manual detection is used
*/
public void updateNumberFormat(boolean autoLocale) {
number = NumberFormat.getNumberInstance(autoLocale ? Locale.getDefault() : Locale.ENGLISH);
number.setRoundingMode(RoundingMode.HALF_UP);
number.setMinimumFractionDigits(MIN_PRECISION);
number.setMaximumFractionDigits(MAX_PRECISION);
Platform.runLater(StatusEffect::updateAttributeModifiers);
}
/**
* Resets every formatter. See {@link Units#updateDateFormat(boolean)}, {@link Units#updateTimeFormat(boolean)} and
* {@link Units#updateNumberFormat(boolean)} for details.
* @param autoLocale Determines if automatic or manual detection is used
*/
public void updateFormats(boolean autoLocale) {
updateDateFormat(autoLocale);
updateTimeFormat(autoLocale);
updateNumberFormat(autoLocale);
}
/**
* Formats a number with the current number formatter.
* @param amount The floating point number to format
* @return A string containing the localized number
*/
public static String number(double amount) {
return FORMATTER.number.format(amount);
}
/**
* Convenience overload of {@link Units#number(double)} for integers.
* @param amount The integer number to format
*/
public static String number(long amount) {
return FORMATTER.number.format(amount);
}
/**
* Formats a number using the specified amount of minimum and maximum fractional places. Otherwise equal to
* {@link Units#number(double)}.
* @param minPrecision Minimum fractional digits
* @param maxPrecision Maximum fractional digits
*/
public static String number(double amount, int minPrecision, int maxPrecision) {
// Apply new settings and generate output
NumberFormat formatter = FORMATTER.number;
formatter.setMinimumFractionDigits(minPrecision);
formatter.setMaximumFractionDigits(maxPrecision);
String output = formatter.format(amount);
// Restore default settings
formatter.setMinimumFractionDigits(FORMATTER.MIN_PRECISION);
formatter.setMaximumFractionDigits(FORMATTER.MAX_PRECISION);
return output;
}
/**
* Specifies the length of dates, where SHORT will use the default numeric style and LONG will use the text style.
*/
public enum DateType {
SHORT,
LONG
}
/**
* Formats a short date and time. See {@link Units#dateTime(TemporalAccessor, DateType)} for details.
*/
public static String dateTime(TemporalAccessor timePoint) {
return dateTime(timePoint, DateType.SHORT);
}
/**
* Formats a point in time with the current date and time formatter, separated with ", ".
* @param timePoint The point in time to convert
* @param type The style of the date, see {@link DateType} for details
* @return A string containing the localized date and time
*/
public static String dateTime(TemporalAccessor timePoint, DateType type) {
return date(timePoint, type) + ", " + time(timePoint);
}
/**
* Formats a short date. See {@link Units#date(TemporalAccessor, DateType)} for details.
*/
public static String date(TemporalAccessor timePoint) {
return date(timePoint, DateType.SHORT);
}
/**
* Similar to {@link Units#dateTime(TemporalAccessor)}, except that this function only outputs the date.
*/
public static String date(TemporalAccessor timePoint, DateType type) {
if (type == DateType.SHORT)
return FORMATTER.shortDate.format(timePoint);
return FORMATTER.longDate.format(timePoint)
.replaceFirst("%o", getOrdinal(timePoint.get(ChronoField.DAY_OF_MONTH)))
.replaceFirst("%m", getMonthName(timePoint.get(ChronoField.MONTH_OF_YEAR)));
}
/**
* Similar to {@link Units#dateTime(TemporalAccessor)}, except that this function only outputs the time.
*/
public static String time(TemporalAccessor timePoint) {
return FORMATTER.time.format(timePoint);
}
/**
* Specifies the display of values, where NUMERIC is a rounded number, PRECISE is a number rounded to at most 2
* places in the metric and eights in the imperial system and TEXT is a more aggressively rounded full text form.
*/
public enum ValueType {
NUMERIC,
PRECISE,
TEXT
}
/**
* Specifies the length of units, where NONE means that they will be omitted, SHORT means the abbreviation, LONG
* means the full text unit and LONG_SINGULAR means full text singular units concatenated with "-" instead of " ".
*/
public enum UnitType {
NONE,
SHORT,
LONG,
LONG_SINGULAR
}
/**
* Shortcut for {@link Units#size(double, ValueType, UnitType)} with numeric value and short unit.
*/
public static String size(double cm) {
return size(cm, ValueType.NUMERIC, UnitType.SHORT);
}
/**
* Shortcut for {@link Units#size(double, ValueType, UnitType)} with numeric value.
*/
public static String size(double cm, UnitType uType) {
return size(cm, ValueType.NUMERIC, uType);
}
/**
* Formats a size, given in centimetres, with the current number formatter and units depending on the imperial unit
* setting as well as the given type.
* @param cm Amount of centimetres to convert
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the localized, wrapped, converted size and its associated unit
*/
public static String size(double cm, ValueType vType, UnitType uType) {
if (Main.getProperties().hasValue(PropertyValue.metricSizes))
return sizeAsMetric(cm, vType, uType);
else
return sizeAsImperial(cm, vType, uType);
}
private final static String INCH_SYMBOL = """;
private final static String FOOT_SYMBOL = "'";
/**
* Converts a size, given in centimetres, to the imperial form.
* @param cm Amount of centimetres to format
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the imperial, formatted size, including unit
*/
@SuppressWarnings("incomplete-switch")
public static String sizeAsImperial(double cm, ValueType vType, UnitType uType) {
// Convert centimetres to inches
double inches = cm / 2.54;
// Wrap inches to feet
double roundingFactor = (vType == ValueType.PRECISE || Math.abs(inches) < 1) ? 0.25 : 1;
long feet = (long) (roundTo(inches, roundingFactor) / 12);
double remainingInches = roundTo(inches, roundingFactor) % 12;
StringBuilder output = new StringBuilder();
boolean both = uType != UnitType.NONE && vType != ValueType.TEXT
&& feet != 0 && remainingInches != 0;
boolean wrap = (vType == ValueType.TEXT && Math.abs(inches) >= 11.5)
|| both || (feet != 0 && remainingInches == 0);
double usedValue = wrap ? feet : inches;
// Append first unit, which may be either feet or inches
output.append(value(usedValue, vType, true));
switch (uType) {
case NONE:
break;
case SHORT:
output.append(wrap ? FOOT_SYMBOL : INCH_SYMBOL);
break;
case LONG:
if (Math.floor(inches) == 0 && vType != ValueType.PRECISE) {
output.setLength(0);
return output.append("less than ")
.append(vType == ValueType.TEXT ? "one" : "1")
.append(" inch").toString();
}
output.append(" ");
if (Math.abs(usedValue) >= 1 + roundingFactor / 2 || usedValue == 0.0) output.append(wrap ? "feet" : "inches");
else output.append(wrap ? "foot" : "inch");
break;
case LONG_SINGULAR:
output.append("-").append(wrap ? "foot" : "inch");
}
// Append second unit for long or short notation and if neither value is 0
if (both) {
if (uType == UnitType.LONG) output.append(" and ");
if (uType == UnitType.LONG_SINGULAR) output.append("-");
remainingInches = Math.abs(roundTo(remainingInches, roundingFactor));
output.append(value(remainingInches, vType, true));
switch (uType) {
case SHORT:
output.append(INCH_SYMBOL);
break;
case LONG:
output.append(" ").append(remainingInches >= 1 + roundingFactor / 2 ? "inches" : "inch");
break;
case LONG_SINGULAR:
break;
}
}
return output.toString();
}
/**
* Formats a size, given in centimetres, to the metric form.
* @param cm Amount of centimetres to convert
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the metric, formatted size, including unit
*/
public static String sizeAsMetric(double cm, ValueType vType, UnitType uType) {
double m = cm / 100;
return valueWithUnit(cm, "cm", "centimetre", m, "m", "metre", vType, uType, false);
}
/**
* Shortcut for {@link Units#fluid(double, ValueType, UnitType)} with numeric value and short unit.
*/
public static String fluid(double ml) {
return fluid(ml, ValueType.NUMERIC, UnitType.SHORT);
}
/**
* Shortcut for {@link Units#fluid(double, ValueType, UnitType)} with numeric value.
*/
public static String fluid(double ml, UnitType uType) {
return fluid(ml, ValueType.NUMERIC, uType);
}
/**
* Shortcut for {@link Units#fluid(double, ValueType, UnitType)} with short units.
*/
public static String fluid(double ml, ValueType vType) {
return fluid(ml, vType, UnitType.SHORT);
}
/**
* Formats a fluid volume, given in millilitres, with the current number formatter and units depending on the
* imperial unit setting as well as the given type.
* @param ml Amount of millilitres to convert
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the localized, wrapped, converted volume and its associated unit
*/
public static String fluid(double ml, ValueType vType, UnitType uType) {
if (Main.getProperties().hasValue(PropertyValue.metricFluids))
return fluidAsMetric(ml, vType, uType);
else
return fluidAsImperial(ml, vType, uType);
}
/**
* Converts a fluid volume, given in millilitres, to the imperial form.
* @param ml Amount of millilitres to convert
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the imperial, formatted volume, including unit
*/
public static String fluidAsImperial(double ml, ValueType vType, UnitType uType) {
// Convert millilitres to ounces
double oz = ml / 28.4131;
double gal = oz / 160;
return valueWithUnit(oz, "oz", "ounce", gal, "gal", "gallon", vType, uType, true);
}
/**
* Formats a fluid volume, given in millilitres, to the metric form.
* @param ml Amount of millilitres to format
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the metric, formatted volume, including unit
*/
public static String fluidAsMetric(double ml, ValueType vType, UnitType uType) {
double l = ml / 1000;
return valueWithUnit(ml, "mL", "millilitre", l, "L", "litre", vType, uType, false); // Innoxia's note: I usually prefer the lowercase l for ml and l, but LT's font makes it look bad.
}
/**
* Shortcut for {@link Units#weight(double, ValueType, UnitType)} with numeric value and short unit.
*/
public static String weight(double grams) {
return weight(grams, ValueType.NUMERIC, UnitType.SHORT);
}
/**
* Shortcut for {@link Units#weight(double, ValueType, UnitType)} with numeric value.
*/
public static String weight(double grams, UnitType uType) {
return weight(grams, ValueType.NUMERIC, uType);
}
/**
* Formats a weight, given in grams, with the current number formatter and units depending on the imperial unit
* setting as well as the given type.
* @param grams Amount of grams to convert
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the localized, wrapped, converted weight and its associated unit
*/
public static String weight(double grams, ValueType vType, UnitType uType) {
if (Main.getProperties().hasValue(PropertyValue.metricWeights))
return weightAsMetric(grams, vType, uType);
else
return weightAsImperial(grams, vType, uType);
}
/**
* Converts a weight, given in grams, to the imperial form.
* @param grams Amount of grams to convert
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the imperial, formatted weight, including unit
*/
public static String weightAsImperial(double grams, ValueType vType, UnitType uType) {
// Convert grams to ounces
double oz = grams / 28.34952;
double lb = oz / 16;
return valueWithUnit(oz, "oz", "ounce", lb, "lb", "pound", vType, uType, true);
}
/**
* Formats a weight, given in grams, to the metric form.
* @param grams Amount of grams to format
* @param vType The format of the value, see {@link ValueType}
* @param uType The format of the units, see {@link UnitType}
* @return A string containing the metric, formatted weight, including unit
*/
public static String weightAsMetric(double grams, ValueType vType, UnitType uType) {
double kg = grams / 1000;
return valueWithUnit(grams, "g", "gram", kg, "kg", "kilogram", vType, uType, false);
}
private static String value(double value, ValueType vType, boolean useQuarters) {
switch (vType) {
case PRECISE:
if (useQuarters) return withQuarters(value);
return number(value);
case TEXT:
return Util.intToString((int) aggressiveRound(value));
default:
if (useQuarters) return Math.abs(value) < 0.875 ? withQuarters(value) : number(Math.round(value));
return number(adaptiveRound(value));
}
}
private static String valueWithUnit(double value, String shortUnit, String unit,
double wrappedValue, String shortWrappedUnit, String wrappedUnit,
ValueType vType, UnitType uType, boolean useQuarters) {
StringBuilder output = new StringBuilder();
boolean wrap = Math.abs(wrappedValue) >= 1 && vType != ValueType.PRECISE;
double usedValue = wrap ? wrappedValue : value;
if (useQuarters) usedValue = roundTo(usedValue, 0.25);
// Append value with increased precision if it is wrapped and numeric
output.append(value(usedValue, wrap && vType == ValueType.NUMERIC ? ValueType.PRECISE : vType, useQuarters));
// Append unit
switch (uType) {
case NONE:
break;
case SHORT:
output.append(" ").append(wrap ? shortWrappedUnit : shortUnit);
break;
case LONG:
if (Math.floor(value) == 0 && vType != ValueType.PRECISE) {
output.setLength(0);
return output.append("less than ")
.append(vType == ValueType.TEXT ? "one " : "1 ")
.append(unit).toString();
}
output.append(" ").append(wrap ? wrappedUnit : unit);
if (Math.abs(usedValue) > 1 || usedValue == 0.0) output.append("s");
break;
case LONG_SINGULAR:
output.append("-").append((wrap ? wrappedUnit : unit));
}
return output.toString();
}
/**
* Formats the given value with eighth fraction symbols instead of fractional digits.
* @param value The number to format
* @return A string containing the formatted number with an optional eighth symbol
*/
public static String withQuarters(double value) {
boolean negative = value < 0;
value = roundTo(Math.abs(value), 0.25);
double floor = Math.floor(value);
if (value == floor) return (negative ? '-' : "") + number(floor);
int quarters = (int) Math.round((value - floor) / 0.25);
return (negative ? '-' : "") + (floor == 0 ? "" : number(floor)) + getQuarterSymbol(quarters);
}
private static String getQuarterSymbol(int quarters) {
switch (quarters) {
case 1: return "¼";
case 2: return "½";
case 3: return "¾";
default: return "";
}
}
private final static String[] suffixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
/**
* Selects the correct ordinal for a given value. Only the ordinal itself is returned.
* @param value The number to select an ordinal for
* @return A string containing the ordinal
*/
public static String getOrdinal(int value) {
switch (value % 100) {
case 11:
case 12:
case 13:
return "th";
default:
return suffixes[value % 10];
}
}
public static String getMonthName(int month) {
switch (month) {
case 1: return "January";
case 2: return "February";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
}
return "";
}
/**
* Rounds a given number to a given amount of fractional places.
* @param value Number to round
* @param places Amount of fractional places
* @return A correctly rounded float
*/
public static float round(double value, int places) {
if (places < 0) throw new IllegalArgumentException("Amount of fractional places cannot be less than 0.");
return BigDecimal.valueOf(value).setScale(places, RoundingMode.HALF_UP).floatValue();
}
/**
* Rounds a given number to the nearest multiple of the second parameter. Note that {@link Units#round(double, int)} is
* more precise and should be preferred.
* @param value Number to round
* @param nearest Number to round to
* @return A rounded float
*/
public static float roundTo(double value, double nearest) {
return (float) (Math.round(value / nearest) * nearest);
}
/**
* Convenience overload of {@link Units#roundTo(double, double)} for integers.
* @param nearest Integer number to round to
* @return A rounded integer
*/
public static long roundTo(double value, long nearest) {
return Math.round(value / nearest) * nearest;
}
/**
* Rounds a given number based on its value. Values below 2 are rounded to 1 fractional digit, values below 10 are
* rounded to the nearest 0.5, otherwise the number is rounded to the nearest integer.
* @param value Number to round
* @return A variably rounded double
*/
public static double adaptiveRound(double value) {
double absoluteValue = Math.abs(value);
if (absoluteValue <= 2) return round(value, 1);
if (absoluteValue <= 10) return roundTo(value, 0.5);
return Math.round(value);
}
/**
* Rounds a given number based on its value, possibly exceeding the original value by more than 1. Values below 10
* are rounded to the nearest integer, values below 50 are rounded to the nearest 5, otherwise the number is rounded
* to the nearest 10.
* @param value Number to round
* @return A variably rounded long
*/
public static long aggressiveRound(double value) {
double absoluteValue = Math.abs(value);
if (absoluteValue <= 10) return Math.round(value);
if (absoluteValue <= 50) return roundTo(value, 5);
return roundTo(value, 10);
}
}
|
package cn.hub.jackeroo.system.mapper;
import cn.hub.jackeroo.system.entity.SysDict;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
/**
* <p>
* 数据字典 Mapper 接口
* </p>
*
* @author jackeroo
* @since 2020-10-10
*/
public interface SysDictMapper extends BaseMapper<SysDict> {
List<SysDict> findList(SysDict entity);
}
|
package com.zekunwang.nytimessearch.models;
import com.loopj.android.http.RequestParams;
import org.parceler.Parcel;
import android.util.Log;
import java.util.HashMap;
@Parcel
public class Setting {
public Date beginDate;
public int sort;
public boolean art;
public boolean fashion;
public boolean sports;
public Setting() {
beginDate = new Date();
}
public Setting(Setting setting) {
this.beginDate = new Date(setting.beginDate);
this.sort = setting.sort;
this.art = setting.art;
this.fashion = setting.fashion;
this.sports = setting.sports;
}
public RequestParams getQuery() {
RequestParams param = new RequestParams();;
if (beginDate.year != 0) {
param.put("begin_date", beginDate.toQuery()); // set begin date query
}
if (sort != 0) {
param.put("sort", (sort == 1 ? "newest" : "oldest")); // set sort query
}
if (art || fashion || sports) {
StringBuilder sb = new StringBuilder("news_desk:(");
if (art) {
sb.append("\"Arts\"");
}
if (fashion) {
if (sb.length() > 11) {
sb.append(',');
}
sb.append("\"Fashion & Style\"");
}
if (sports) {
if (sb.length() > 11) {
sb.append(',');
}
sb.append("\"Sports\"");
}
sb.append(')');
param.put("fq", sb.toString());
}
return param;
}
}
|
package com.fjuul.sdk.analytics.entities;
import androidx.annotation.NonNull;
public class ActivityMeasure {
double seconds;
float metMinutes;
@NonNull
public double getSeconds() {
return seconds;
}
@NonNull
public float getMetMinutes() {
return metMinutes;
}
}
|
package <%= appPackage %>.data.source;
import <%= appPackage %>.data.FakeTasksRemoteDataSource;
import <%= appPackage %>.data.source.local.TasksLocalDataSource;
import javax.inject.Singleton;
import dagger.Binds;
import dagger.Module;
/**
* This is used by Dagger to inject the required arguments into the {@link TasksRepository}.
*/
@Module
abstract class TasksRepositoryModule {
@Singleton
@Binds
@Local
abstract TasksDataSource provideTasksLocalDataSource(TasksLocalDataSource dataSource);
@Singleton
@Binds
@Remote
abstract TasksDataSource provideTasksRemoteDataSource(FakeTasksRemoteDataSource dataSource);
}
|
package com.raysonfang.sqltranslator.sql.dialect.oracle.function;
import com.alibaba.druid.sql.ast.SQLDataType;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.druid.sql.ast.SQLOrderBy;
import com.alibaba.druid.sql.ast.expr.*;
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
import com.alibaba.druid.sql.dialect.oracle.ast.expr.OracleSysdateExpr;
import com.alibaba.druid.util.StringUtils;
import com.raysonfang.sqltranslator.sql.dialect.mysql.util.MySqlUtil;
import com.raysonfang.sqltranslator.sql.dialect.oracle.util.OracleSQLDataTypeTransformUtil;
import org.springframework.util.ObjectUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* oracle函数 转换成 mysql函数
*
* @author rayson.fang
* @date 2021/02/05 12:38
**/
public class OracleToMySqlFunctionTransform implements OracleFunction {
@Override
public void transformFunctionExpr(SQLExpr sqlExpr) {
if (sqlExpr instanceof SQLMethodInvokeExpr) { //函数
forEachMethod(sqlExpr);
alias(sqlExpr);
} else if (sqlExpr instanceof SQLIdentifierExpr) { //字段
String name = ((SQLIdentifierExpr) sqlExpr).getName().toUpperCase();
alias(sqlExpr);
if ("SYSTIMESTAMP".equalsIgnoreCase(name)) {
((SQLIdentifierExpr) sqlExpr).setName("CURRENT_TIMESTAMP");
} else {
((SQLIdentifierExpr) sqlExpr).setName(formatKeyField(name));
}
} else if (sqlExpr instanceof SQLPropertyExpr) { //参数
String name = ((SQLPropertyExpr) sqlExpr).getName();
alias(sqlExpr);
((SQLPropertyExpr) sqlExpr).setName(formatKeyField(name.toUpperCase()));
} else if (sqlExpr instanceof SQLCharExpr) { // 字符
alias(sqlExpr);
} else if (sqlExpr instanceof SQLBinaryOpExpr) {
SQLBinaryOperator operator = ((SQLBinaryOpExpr) sqlExpr).getOperator();
Optional.ofNullable(sqlExpr.getChildren()).orElse(new ArrayList<>()).forEach(e -> {
if (e instanceof SQLMethodInvokeExpr) { //函数
// forEachMethod((SQLMethodInvokeExpr)e);
methodInvoke((SQLMethodInvokeExpr) e);
}
});
if (SQLBinaryOperator.Concat == operator) {
String str = sqlExpr.toString();
SQLIdentifierExpr sqlIdentifierExpr = new SQLIdentifierExpr(String.format("concat(%s)", str.replaceAll("\\|\\|", ",")));
sqlIdentifierExpr.setParent(sqlExpr.getParent());
SQLObject parent = sqlExpr.getParent();
if (parent instanceof SQLSelectItem) {
((SQLSelectItem) parent).setExpr(sqlIdentifierExpr);
}
} else if (sqlExpr instanceof SQLAggregateExpr) {
methodInvoke((SQLMethodInvokeExpr) sqlExpr);
}
alias(sqlExpr);
} else if (sqlExpr instanceof SQLCastExpr) {
SQLDataType dataType = ((SQLCastExpr) sqlExpr).getDataType();
if (!ObjectUtils.isEmpty(dataType) && "timestamp".equalsIgnoreCase(dataType.getName())) {
dataType.setName("datetime");
}
}
}
@Override
public String concat(SQLObject sqlObject) {
StringBuilder sb = new StringBuilder();
if (sqlObject instanceof SQLBinaryOpExpr) {
SQLExpr left = ((SQLBinaryOpExpr) sqlObject).getLeft();
sb.append(concat(left));
SQLExpr right = ((SQLBinaryOpExpr) sqlObject).getRight();
sb.append(concat(right));
}
if (sqlObject instanceof SQLIdentifierExpr) {
String name = ((SQLIdentifierExpr) sqlObject).getName();
sb.append(name);
sb.append(" ");
} else if (sqlObject instanceof SQLCharExpr) {
String name = ((SQLCharExpr) sqlObject).getText();
sb.append(" '");
sb.append(name);
sb.append("' ");
}
return sb.toString();
}
@Override
public void listagg(SQLMethodInvokeExpr expr) {
if (expr instanceof SQLAggregateExpr) {
String methodName = expr.getMethodName();
if ("listagg".equalsIgnoreCase(methodName)) {
List children = expr.getChildren();
StringBuffer sb = new StringBuffer();
StringBuffer field = new StringBuffer();
StringBuffer fieldVal = new StringBuffer();
StringBuffer orderBy = new StringBuffer();
children.forEach(e -> {
if (e instanceof SQLPropertyExpr) {
field.append(((SQLPropertyExpr) e).getName());
} else if (e instanceof SQLCharExpr) {
fieldVal.append(" separator '" + ((SQLCharExpr) e).getText());
fieldVal.append("'");
} else if (e instanceof SQLOrderBy) {
((SQLOrderBy) e).getItems().forEach(c -> {
orderBy.append(c.getExpr().toString());
});
}
});
sb.append("group_concat(");
sb.append(field);
sb.append(" ");
if (orderBy.toString().length() > 0) {
sb.append(" order by ");
sb.append(orderBy);
}
sb.append(" ");
sb.append(fieldVal);
sb.append(")");
identifierExpr(sb.toString(), expr);
}
}
}
@Override
public void sys_guid(SQLMethodInvokeExpr expr) {
identifierExpr("md5(uuid())", expr);
}
@Override
public void to_char(SQLMethodInvokeExpr expr) {
expr.setMethodName("date_format");
SQLIdentifierExpr sqlCharExpr = null;
List<SQLObject> children = expr.getChildren();
for (int i = 0, listSize = children.size(); i < listSize; i++) {
SQLObject sqlObj = children.get(i);
if (sqlObj instanceof SQLCharExpr) {
String textStr = ((SQLCharExpr) sqlObj).getText();
if (textStr.indexOf("99") < 0) {
((SQLCharExpr) sqlObj).setText(formatDate(textStr));
} else {
sqlCharExpr = new SQLIdentifierExpr(String.valueOf(getRound(textStr)));
sqlCharExpr.setParent(sqlObj.getParent());
children.set(i, sqlCharExpr);
expr.setMethodName("ROUND");
}
} else {
String val = "";
int length = 0;
if (sqlObj instanceof SQLIntegerExpr) {
val = ((SQLIntegerExpr) sqlObj).getValue().toString();
length = val.length();
} else if (sqlObj instanceof SQLNumberExpr) {
val = ((SQLNumberExpr) sqlObj).getNumber().toString();
length = val.length();
if ((i + 1) <= listSize) {
SQLObject sqlObjNext = children.get(i + 1);
if (sqlObjNext instanceof SQLCharExpr) {
continue;
}
}
} else if (sqlObj instanceof SQLIdentifierExpr) {
if (sqlObj.getParent() instanceof SQLMethodInvokeExpr) {
if (((SQLMethodInvokeExpr) sqlObj.getParent()).getArguments().size() > 1) {
continue;
}
}
val = ((SQLIdentifierExpr) sqlObj).getName();
length = 11;
} else if (sqlObj instanceof SQLVariantRefExpr) {
if ((((SQLVariantRefExpr) sqlObj).getChildren().size()) > 1) {
continue;
}
val = ((SQLVariantRefExpr) sqlObj).getName();
length = 11;
}else if (sqlObj instanceof OracleSysdateExpr) {
children.set(i, new SQLIdentifierExpr("now()"));
continue;
} else {
continue;
}
sqlCharExpr = new SQLIdentifierExpr(String.format("%s AS CHAR(%d)", val, length));
sqlCharExpr.setParent(sqlObj.getParent());
children.set(i, sqlCharExpr);
expr.setMethodName("cast");
}
}
}
@Override
public void to_date(SQLMethodInvokeExpr expr) {
expr.setMethodName("str_to_date");
List<SQLObject> children = expr.getChildren();
for (int i = 0, listSize = children.size(); i < listSize; i++) {
SQLObject sqlObj = children.get(i);
if (sqlObj instanceof SQLCharExpr) {
String textStr = ((SQLCharExpr) sqlObj).getText();
((SQLCharExpr) sqlObj).setText(formatDate(textStr));
}
}
}
@Override
public void to_timestamp(SQLMethodInvokeExpr expr) {
expr.setMethodName("str_to_date");
List<SQLObject> children = expr.getChildren();
for (int i = 0, listSize = children.size(); i < listSize; i++) {
SQLObject sqlObj = children.get(i);
if (sqlObj instanceof SQLCharExpr) {
String textStr = ((SQLCharExpr) sqlObj).getText();
((SQLCharExpr) sqlObj).setText(formatDate(textStr));
}
}
}
@Override
public void to_number(SQLMethodInvokeExpr expr) {
expr.setMethodName("cast");
List<SQLObject> children = expr.getChildren();
SQLIdentifierExpr sqlCharExpr = null;
for (int i = 0, listSize = children.size(); i < listSize; i++) {
SQLObject sqlObj = children.get(i);
if (sqlObj instanceof SQLCharExpr) {
String textStr = ((SQLCharExpr) sqlObj).getText();
sqlCharExpr = new SQLIdentifierExpr(String.format("'%s' AS SIGNED", textStr));
sqlCharExpr.setParent(sqlObj.getParent());
children.set(i, sqlCharExpr);
} else if (sqlObj instanceof SQLIdentifierExpr) {
String name = ((SQLIdentifierExpr) sqlObj).getName();
((SQLIdentifierExpr) sqlObj).setName(String.format("%s AS SIGNED", name));
} else if (sqlObj instanceof SQLVariantRefExpr) {
String name = ((SQLVariantRefExpr) sqlObj).getName();
((SQLVariantRefExpr) sqlObj).setName(String.format("%s AS SIGNED", name));
}
}
}
@Override
public void trunc(SQLMethodInvokeExpr expr) {
List<SQLObject> children = expr.getChildren();
SQLIdentifierExpr sqlIdentifierExpr = null;
expr.setMethodName("truncate");
for (int i = 0, listSize = children.size(); i < listSize; i++) {
SQLObject sqlObj = children.get(i);
if (sqlObj instanceof OracleSysdateExpr) {
sqlIdentifierExpr = new SQLIdentifierExpr();
sqlIdentifierExpr.setName("now(), '%Y-%m-%d'");
sqlIdentifierExpr.setParent(sqlObj.getParent());
children.set(i, sqlIdentifierExpr);
expr.setMethodName("date_format");
} else if (sqlObj instanceof SQLIdentifierExpr) {
String name = ((SQLIdentifierExpr) sqlObj).getName();
if (name.toLowerCase().indexOf("time") > 0) { // 如果是一个字段 必须包含time
sqlIdentifierExpr = new SQLIdentifierExpr();
sqlIdentifierExpr.setName(name + ", '%Y-%m-%d'");
sqlIdentifierExpr.setParent(sqlObj.getParent());
children.set(i, sqlIdentifierExpr);
expr.setMethodName("date_format");
}
// 其他占卜做处理
} else if (sqlObj instanceof SQLNumberExpr) {
Number number = ((SQLNumberExpr) sqlObj).getNumber();
sqlIdentifierExpr = new SQLIdentifierExpr();
if (number.intValue() > 0) {
String num = "0";
List<SQLExpr> arguments = ((SQLMethodInvokeExpr) sqlObj.getParent()).getArguments();
if (arguments != null && arguments.size() == 2) {
if (arguments.get(1) instanceof SQLIntegerExpr) {
num = ((SQLIntegerExpr) arguments.get(1)).getNumber().toString();
}
}
sqlIdentifierExpr.setName(String.format("%s, %s", number.toString(), num));
expr.setMethodName("truncate");
} else {
sqlIdentifierExpr.setName(String.format("%s as SIGNED", number.toString()));
expr.setMethodName("cast");
}
sqlIdentifierExpr.setParent(sqlObj.getParent());
children.set(i, sqlIdentifierExpr);
} else if (sqlObj instanceof SQLCharExpr) {
String text = ((SQLCharExpr) sqlObj).getText();
((SQLCharExpr) sqlObj).setText(formatDate(text));
expr.setMethodName("date_format");
} else if (sqlObj instanceof SQLIntegerExpr) {
children.remove(i);
}
}
}
@Override
public void nvl(SQLMethodInvokeExpr expr) {
expr.setMethodName("ifnull");
}
@Override
public void nvl2(SQLMethodInvokeExpr expr) {
expr.setMethodName("if");
}
@Override
public void length(SQLMethodInvokeExpr expr) {
expr.setMethodName("char_length");
}
@Override
public void instr(SQLMethodInvokeExpr expr) {
List<SQLObject> children = expr.getChildren();
expr.setMethodName("locate");
if (children.size() >= 2) {
SQLObject sqlObject = children.get(0);
children.set(0, children.get(1));
children.set(1, sqlObject);
}
}
@Override
public void substr(SQLMethodInvokeExpr expr) {
List<SQLObject> children = expr.getChildren();
expr.setMethodName("substr");
if (children.size() >= 2) {
SQLObject sqlObject = children.get(1);
if (sqlObject instanceof SQLNumberExpr) {
int val = ((SQLNumberExpr) sqlObject).getNumber().intValue();
if (val <= 0) {
((SQLNumberExpr) sqlObject).setNumber(1);
}
} else if (sqlObject instanceof SQLIntegerExpr) {
int val = ((SQLIntegerExpr) sqlObject).getNumber().intValue();
if (val <= 0) {
((SQLIntegerExpr) sqlObject).setNumber(1);
}
}
}
}
@Override
public void add_months(SQLMethodInvokeExpr expr) {
List<SQLObject> children = expr.getChildren();
expr.setMethodName("date_add");
SQLIdentifierExpr sqlCharExpr = null;
for (int i = 0, listSize = children.size(); i < listSize; i++) {
SQLObject sqlObj = children.get(i);
if (sqlObj instanceof SQLIntegerExpr) {
String num = ((SQLIntegerExpr) sqlObj).getNumber().toString();
sqlCharExpr = new SQLIdentifierExpr();
sqlCharExpr.setName(String.format("interval %s month", num));
sqlCharExpr.setParent(sqlCharExpr);
children.set(i, sqlCharExpr);
}
}
}
@Override
public void hextoraw(SQLMethodInvokeExpr expr) {
expr.setMethodName("UNHEX");
}
@Override
public void decode(SQLMethodInvokeExpr expr) {
SQLExpr expr1 = OracleSQLDataTypeTransformUtil.transformDecode(expr);
if (expr.getParent() instanceof SQLSelectItem) {
((SQLSelectItem) expr.getParent()).setExpr(expr1);
} else if (expr.getParent() instanceof SQLBinaryOpExpr) {
((SQLBinaryOpExpr) expr.getParent()).setRight(expr1);
}
}
@Override
public String formatDate(String format) {
if(format.toUpperCase().startsWith("S")) {
format = format.substring(1);
}
return format.toUpperCase()
.replaceAll("YYYY", "%Y")
.replaceAll("MM", "%m")
.replaceAll("DD", "%d")
.replaceAll("HH24", "%H")
.replaceAll("MI", "%i")
.replaceAll("SS", "%s")
.replaceAll(".FF", ".%f")
.replaceAll(":FF", ".%f");
}
@Override
public String formatKeyField(String format) {
if (MySqlUtil.containsKeyWords(format)) {
return String.format("`%s`", format.toUpperCase());
}
return format;
}
@Override
public void alias(SQLExpr sqlExpr) {
if (sqlExpr.getParent() instanceof SQLSelectItem) {//取别名 as
String alias = ((SQLSelectItem) sqlExpr.getParent()).getAlias();
if (!StringUtils.isEmpty(alias)) {
if (alias.lastIndexOf("\"") <= 0) {
((SQLSelectItem) sqlExpr.getParent()).setAlias(formatKeyField(alias.toUpperCase()));
}
}
}
}
/**
* 获取四舍五入小数点多少位
* to_char(999995.6, '9999999999990.999999')
* @author rayson.fang
* @date 2021/02/05 13:36
* @param str
* @return java.lang.Integer
*/
private Integer getRound(String str) {
int round = 0;
if (str.indexOf(".") > 0) {
round = str.split("\\.")[1].length();
}
return round;
}
}
|
package net.gmx.onebyte.ttnmapper.widget;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RemoteViews;
public class ConfigurationActivity extends Activity {
private int mAppWidgetId;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setResult(RESULT_CANCELED);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras == null) {
finish();
return;
}
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
setContentView(R.layout.configuration);
this.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String device = ((EditText) findViewById(R.id.device)).getText().toString();
if (device.isEmpty()) {
return;
}
configured(device);
}
});
}
private void configured(String device) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(ConfigurationActivity.this);
RemoteViews views = new RemoteViews(ConfigurationActivity.this.getPackageName(),
R.layout.widget);
views.setCharSequence(R.id.device, "setText", device);
PendingIntent click = PendingIntent.getService(this, mAppWidgetId, UpdateService.getUpdateIntent(this, mAppWidgetId, device), PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.layout, click);
appWidgetManager.updateAppWidget(mAppWidgetId, views);
Bundle options = new Bundle();
options.putString("device", device);
appWidgetManager.updateAppWidgetOptions(mAppWidgetId, options);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
}
|
package frc.robot.subsystems;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj.DriverStation;
public class VisionSubsystem extends EntechSubsystem {
private NetworkTable table;
private static NetworkTableEntry tableEntryLowerBound;
private static NetworkTableEntry tableEntryUpperBound;
private int m_ballX = getBallX();
private int m_ballY = getBallY();
private int rpi_counter;
private int rpi_dead_counter;
private int rio_counter;
private int x_pos;
private int y_pos;
private Boolean isBallFound;
public VisionSubsystem() {
}
@Override
public void initialize(){
rio_counter = 0;
rpi_counter = -1;
rpi_dead_counter = 0;
table = NetworkTableInstance.getDefault().getTable("Vision");
tableEntryLowerBound = table.getEntry("HSVValuesLowerBound");
tableEntryUpperBound = table.getEntry("HSVValuesUpperBound");
}
public static void publishHSV() {
if (DriverStation.getAlliance() == DriverStation.Alliance.Red){
Number[] arrLowerBound = {160, 100, 0};
Number[] arrUpperBound = {180, 255, 255};
tableEntryLowerBound.forceSetNumberArray(arrLowerBound);
tableEntryUpperBound.forceSetNumberArray(arrUpperBound);
}
if (DriverStation.getAlliance() == DriverStation.Alliance.Blue){
Number[] arrLowerBound = {100, 100, 0};
Number[] arrUpperBound = {135, 255, 255};
tableEntryLowerBound.forceSetNumberArray(arrLowerBound);
tableEntryUpperBound.forceSetNumberArray(arrUpperBound);
}
if (DriverStation.getAlliance() == DriverStation.Alliance.Invalid){
Number[] arrLowerBound = {0, 0, 0};
Number[] arrUpperBound = {0, 0, 0};
tableEntryLowerBound.forceSetNumberArray(arrLowerBound);
tableEntryUpperBound.forceSetNumberArray(arrUpperBound);
}
}
@Override
public void periodic(){
// send rio information to the network tables
table.getEntry("rio_counter").setNumber(rio_counter);
rio_counter += 1;
publishHSV();
// get the counter and see if the rpi is alive
int counter = table.getEntry("rpi_counter").getNumber(0.0).intValue();
if (counter > rpi_counter) {
rpi_counter = counter;
rpi_dead_counter = 0;
} else {
rpi_dead_counter += 1;
}
x_pos = table.getEntry("x").getNumber(0).intValue();
y_pos = table.getEntry("y").getNumber(0).intValue();
isBallFound = table.getEntry("isBallFound").getBoolean(false);
logger.log("rpi counter", rpi_counter);
logger.log("rpi dead counter", rpi_dead_counter);
logger.log("Ball Lateral Offset", x_pos);
logger.log("Ball Vertical Offset", y_pos);
logger.log("Vision Ball Found?", isBallFound);
}
public Boolean isBallCenter() {
if ((m_ballX <= 2) && (m_ballX >= -2) && (m_ballY <= 2) && (m_ballY >= 2)) {
return true;
}
return false;
}
public Boolean isBallFound() {
return isBallFound;
}
public Boolean isRPiAlive() {
if (rpi_dead_counter > 50) {
return false;
}
return true;
}
public int getBallX() {
return x_pos;
}
public int getBallY() {
return y_pos;
}
}
|
package com.hm.cloud.common.exception;
/**
* @author Coder编程
* @Title: HMException
* @ProjectName hm-cloud-platform
* @Description: TODO
* @date 2020/12/414:38
*/
public class HMException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
public HMException(String msg) {
super(msg);
this.msg = msg;
}
public HMException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public HMException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public HMException(String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
|
/*
* GROOVE: GRaphs for Object Oriented VErification Copyright 2003--2007
* University of Twente
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* $Id: LTSJModel.java 5832 2017-01-31 15:55:37Z rensink $
*/
package groove.gui.jgraph;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import groove.graph.Edge;
import groove.graph.Node;
import groove.gui.look.Look;
import groove.gui.look.VisualKey;
import groove.lts.GTS;
import groove.lts.GTSListener;
import groove.lts.GraphState;
import groove.lts.GraphTransition;
import groove.lts.Status.Flag;
/**
* Graph model adding a concept of active state and transition, with special
* visual characteristics.
* @author Arend Rensink
* @version $Revision: 5832 $
*/
final public class LTSJModel extends JModel<GTS> implements GTSListener {
/** Creates a new model from a given LTS and set of display options. */
LTSJModel(LTSJGraph jGraph) {
super(jGraph);
}
/* Specialises the return type. */
@Override
public LTSJGraph getJGraph() {
return (LTSJGraph) super.getJGraph();
}
/**
* If the super call returns <code>null</code>, use
* {@link #DEFAULT_LTS_NAME}.
*/
@Override
public String getName() {
String result = super.getName();
if (result == null) {
result = DEFAULT_LTS_NAME;
}
return result;
}
@Override
public synchronized void addUpdate(GTS gts, GraphState state) {
if (isExploring()) {
this.addedNodes.add(state);
} else if (isAcceptState(state)) {
prepareInsert();
// add a corresponding GraphCell to the GraphModel
addNode(state);
doInsert(false);
}
}
@Override
public synchronized void addUpdate(GTS gts, GraphTransition transition) {
if (isExploring()) {
this.addedEdges.add(transition);
} else if (isAcceptTransition(transition)) {
prepareInsert();
// note that (as per GraphListener contract)
// source and target Nodes (if any) have already been added
JCell<GTS> edgeJCell = addEdge(transition);
doInsert(false);
JCell<GTS> stateJCell = getJCellForNode(transition.target());
stateJCell.setStale(VisualKey.VISIBLE);
edgeJCell.setStale(VisualKey.VISIBLE);
// layout should occur after the transition has been added
// otherwise the forest will not be computed correctly
getJGraph().doLayout(false);
getJGraph().scrollToActive();
}
}
@Override
public void statusUpdate(GTS lts, GraphState explored, int change) {
JCell<GTS> jCell = registerChange(explored, change);
if (jCell != null) {
if (isExploring()) {
this.changedCells.add(jCell);
} else {
getJGraph().refreshCells(Collections.singleton(jCell));
}
}
}
/**
* Registers a status change in a previously explored state.
* @return the cell that was changed as a consequence to the state change;
* {@code null} if there was no change.
*/
private JCell<GTS> registerChange(GraphState explored, int change) {
JVertex<GTS> jCell = getJCellForNode(explored);
if (jCell != null) {
if (Flag.CLOSED.test(change)) {
jCell.setLook(Look.OPEN, false);
}
if (Flag.DONE.test(change)) {
jCell.setLook(Look.RECIPE, explored.isInternalState());
jCell.setLook(Look.TRANSIENT, explored.isTransient());
jCell.setLook(Look.FINAL, explored.isFinal());
}
if (Flag.ABSENT.test(change)) {
Iterator<? extends JEdge<GTS>> iter = jCell.getContext();
while (iter.hasNext()) {
iter.next()
.setLook(Look.ABSENT, true);
}
jCell.setLook(Look.ABSENT, true);
}
jCell.setStale(VisualKey.refreshables());
}
return jCell;
}
@Override
public void loadGraph(GTS gts) {
GTS oldGTS = getGraph();
// temporarily remove the model as a graph listener
if (oldGTS != null && gts != oldGTS) {
oldGTS.removeLTSListener(this);
}
prepareLoad(gts);
addElements(gts.nodeSet(), null, true);
if (gts != oldGTS) {
gts.addLTSListener(this);
}
getJGraph().reactivate();
}
/**
* Possibly extends the jModel with additional states from the underlying GTS.
* This can be more efficient than reloading, e.g., if the state bound has increased.
*/
public boolean reloadGraph() {
boolean result = false;
if (getGraph() != null) {
int nodeCount = nodeCount();
int bound = getStateBound();
if (bound > nodeCount && nodeCount < getGraph().nodeCount()) {
result = addElements(getGraph().nodeSet(), getGraph().edgeSet(), false);
} else if (bound < nodeCount) {
loadGraph(getGraph());
result = true;
}
}
return result;
}
/* Overridden to ensure that the node rendering limit is used. */
@Override
protected boolean addNodes(Collection<? extends Node> nodeSet) {
boolean result = false;
int nodeCount = nodeCount();
for (Node node : nodeSet) {
GraphState state = (GraphState) node;
if (!isAcceptState(state)) {
continue;
}
LTSJVertex jVertex = (LTSJVertex) getJCellForNode(node);
if (jVertex != null) {
result |= jVertex.setVisibleFlag(true);
continue;
}
addNode(node);
result = true;
nodeCount++;
if (nodeCount > getStateBound()) {
break;
}
}
return result;
}
/** Tests if a given graph state is acceptable for addition to the LTS panel. */
private boolean isAcceptState(GraphState state) {
if (state.isInternalState() && !getJGraph().isShowRecipeSteps()) {
return false;
}
if (state.isAbsent() && !getJGraph().isShowAbsentStates()) {
return false;
}
return true;
}
/* Overridden to ensure that the node rendering limit is observed. */
@Override
protected boolean addEdges(Collection<? extends Edge> edgeSet) {
boolean result = false;
if (edgeSet == null) {
for (Node node : this.nodeJCellMap.keySet()) {
GraphState state = (GraphState) node;
for (GraphTransition trans : state
.getTransitions(getJGraph().getTransitionClass())) {
result |= addTransition(trans);
}
}
} else {
for (Edge edge : edgeSet) {
GraphTransition trans = (GraphTransition) edge;
if (getJGraph().getTransitionClass()
.admits(trans)) {
result |= addTransition((GraphTransition) edge);
}
}
}
return result;
}
/** Tests if a given graph transition is acceptable for addition to the LTS panel. */
private boolean isAcceptTransition(GraphTransition trans) {
return getJGraph().getTransitionClass()
.admits(trans);
}
/**
* Adds a given transition to the jModel, if its properties allow this,
* its source and target are in the model, and
* it is not in the model already.
* @return {@code true} if the transition was indeed added
*/
private boolean addTransition(GraphTransition trans) {
GraphState source = trans.source();
GraphState target = trans.target();
if (!isVisible(source)) {
return false;
}
// Only add the edges for which we know the target exists.
if (!trans.isLoop() && !isVisible(target)) {
return false;
}
// make visible if the transition is already there
LTSJCell jCell = (LTSJCell) getJCellForEdge(trans);
if (jCell != null) {
return jCell.setVisibleFlag(true);
}
addEdge(trans);
return true;
}
private boolean isVisible(GraphState state) {
LTSJVertex jVertex = (LTSJVertex) getJCellForNode(state);
return jVertex != null && jVertex.hasVisibleFlag();
}
/**
* Sets the maximum state number to be added.
* @return the previous bound
*/
public int setStateBound(int bound) {
int result = this.stateBound;
this.stateBound = bound;
return result;
}
/** Returns the maximum state number to be displayed. */
public int getStateBound() {
return this.stateBound;
}
/** The maximum state number to be added. */
private int stateBound;
/**
* Indicates if the model is set to exploring mode.
* In exploring mode, changes to the GTS are registered but not
* passed on to the GUI.
*/
public boolean isExploring() {
return this.exploring;
}
/**
* Sets or resets the exploring mode.
* When exploring is set to {@code false}, all registered changes
* are pushed to the GUI.
*/
public void setExploring(boolean exploring) {
boolean changed = (this.exploring != exploring);
if (changed) {
this.exploring = exploring;
if (exploring) {
this.addedNodes.clear();
this.addedEdges.clear();
this.changedCells.clear();
} else {
if (!this.addedNodes.isEmpty() || !this.addedEdges.isEmpty()) {
addElements(this.addedNodes, this.addedEdges, false);
}
if (!this.changedCells.isEmpty()) {
getJGraph().refreshCells(this.changedCells);
}
}
}
}
private boolean exploring;
/** Set of nodes added during the last exploration. */
private final List<Node> addedNodes = new ArrayList<>();
/** Set of edges added during the last exploration. */
private final List<Edge> addedEdges = new ArrayList<>();
/** Set of JCells with status changes during the last exploration. */
private final List<JCell<GTS>> changedCells = new ArrayList<>();
/** Default name of an LTS model. */
static public final String DEFAULT_LTS_NAME = "lts";
}
|
package chobo.springweb;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class KafkaObserverApplicationTests {
@Test
void contextLoads() {
}
}
|
package com.lovecyy.wallet.item.model.dto;
import com.lovecyy.wallet.item.model.pojo.TTransaction;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author shuoyu
*/
@Data
public class TransactionDTO implements Serializable {
/**下次使用页码*/
private Integer pageNum;
private Boolean isLastPage;
/**交易列表*/
private List<TTransaction> lists;
}
|
package org.srs.datacat.model.security;
import java.util.Set;
/**
* A CallContext object is used for verification of filesystem operations.
* It includes the user who initiated the call into the provider, and the user's groups.
* @author bvan
*/
public class CallContext {
private final DcUser subject;
private final Set<DcGroup> groups;
public CallContext(DcUser subject, Set<DcGroup> groups){
this.subject = subject;
this.groups = groups;
}
public DcUser getSubject(){
return subject;
}
public Set<DcGroup> getGroups(){
return groups;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.