text
stringlengths
7
1.01M
/* * Copyright (c) 2020 Bixbit s.c. All rights reserved. * See LICENSE file for licensing information. */ package io.imunity.furms.db.ssh_key_installation; import static java.util.stream.StreamSupport.stream; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import org.springframework.stereotype.Repository; import io.imunity.furms.domain.ssh_keys.InstalledSSHKey; import io.imunity.furms.spi.ssh_key_installation.InstalledSSHKeyRepository; @Repository class InstalledSSHKeyDatabaseRepository implements InstalledSSHKeyRepository { private final InstalledSSHKeyEntityRepository repository; InstalledSSHKeyDatabaseRepository(InstalledSSHKeyEntityRepository repository) { this.repository = repository; } @Override public List<InstalledSSHKey> findAll() { return stream(repository.findAll().spliterator(), false).map(entity -> InstalledSSHKey.builder() .id(entity.getId().toString()).siteId(entity.siteId.toString()) .sshkeyId(entity.sshkeyId.toString()).value(entity.value).build()) .collect(Collectors.toList()); } @Override public String create(InstalledSSHKey installedSSHKey) { InstalledSSHKeyEntity installedSSHKeyEntity = InstalledSSHKeyEntity.builder() .siteId(UUID.fromString(installedSSHKey.siteId)) .sshkeyId(UUID.fromString(installedSSHKey.sshkeyId)).value(installedSSHKey.value) .build(); InstalledSSHKeyEntity saved = repository.save(installedSSHKeyEntity); return saved.getId().toString(); } @Override public void update(String siteId, String keyId, String value) { repository.findBySshkeyIdAndSiteId(UUID.fromString(keyId), UUID.fromString(siteId)) .map(entity -> InstalledSSHKeyEntity.builder().id(entity.getId()).siteId(entity.siteId) .sshkeyId(entity.sshkeyId).value(value).build()) .ifPresent(repository::save); } @Override public void delete(String id) { repository.deleteById(UUID.fromString(id)); } @Override public void deleteAll() { repository.deleteAll(); } @Override public void deleteBySSHKeyIdAndSiteId(String sshkeyId, String siteId) { repository.deleteBySshkeyIdAndSiteId(UUID.fromString(sshkeyId), UUID.fromString(siteId)); } @Override public void deleteBySSHKey(String sshkeyId) { repository.deleteBySshkeyId(UUID.fromString(sshkeyId)); } @Override public List<InstalledSSHKey> findBySSHKeyId(String sshkeyId) { return stream(repository.findBySshkeyId(UUID.fromString(sshkeyId)).spliterator(), false) .map(entity -> InstalledSSHKey.builder().id(entity.getId().toString()) .siteId(entity.siteId.toString()).sshkeyId(entity.sshkeyId.toString()) .value(entity.value).build()) .collect(Collectors.toList()); } }
/* * Copyright 1999-2011 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.sql.ast.statement; import java.util.ArrayList; import java.util.List; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLObjectImpl; import com.alibaba.druid.sql.visitor.SQLASTVisitor; public class SQLSelectQueryBlock extends SQLObjectImpl implements SQLSelectQuery { protected int distionOption; protected final List<SQLSelectItem> selectList = new ArrayList<SQLSelectItem>(); protected SQLTableSource from; protected SQLExprTableSource into; protected SQLExpr where; protected SQLSelectGroupByClause groupBy; protected boolean parenthesized = false; public SQLSelectQueryBlock(){ } public SQLExprTableSource getInto() { return into; } public void setInto(SQLExpr into) { this.setInto(new SQLExprTableSource(into)); } public void setInto(SQLExprTableSource into) { if (into != null) { into.setParent(this); } this.into = into; } public SQLSelectGroupByClause getGroupBy() { return this.groupBy; } public void setGroupBy(SQLSelectGroupByClause groupBy) { this.groupBy = groupBy; } public SQLExpr getWhere() { return this.where; } public void setWhere(SQLExpr where) { if (where != null) { where.setParent(this); } this.where = where; } public int getDistionOption() { return this.distionOption; } public void setDistionOption(int distionOption) { this.distionOption = distionOption; } public List<SQLSelectItem> getSelectList() { return this.selectList; } public SQLTableSource getFrom() { return this.from; } public void setFrom(SQLTableSource from) { this.from = from; } public boolean isParenthesized() { return parenthesized; } public void setParenthesized(boolean parenthesized) { this.parenthesized = parenthesized; } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, this.selectList); acceptChild(visitor, this.from); acceptChild(visitor, this.where); acceptChild(visitor, this.groupBy); } visitor.endVisit(this); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (Boolean.valueOf(parenthesized).hashCode()); result = prime * result + distionOption; result = prime * result + ((from == null) ? 0 : from.hashCode()); result = prime * result + ((groupBy == null) ? 0 : groupBy.hashCode()); result = prime * result + ((into == null) ? 0 : into.hashCode()); result = prime * result + ((selectList == null) ? 0 : selectList.hashCode()); result = prime * result + ((where == null) ? 0 : where.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SQLSelectQueryBlock other = (SQLSelectQueryBlock) obj; if (parenthesized ^ other.parenthesized) return false; if (distionOption != other.distionOption) return false; if (from == null) { if (other.from != null) return false; } else if (!from.equals(other.from)) return false; if (groupBy == null) { if (other.groupBy != null) return false; } else if (!groupBy.equals(other.groupBy)) return false; if (into == null) { if (other.into != null) return false; } else if (!into.equals(other.into)) return false; if (selectList == null) { if (other.selectList != null) return false; } else if (!selectList.equals(other.selectList)) return false; if (where == null) { if (other.where != null) return false; } else if (!where.equals(other.where)) return false; return true; } }
package com.ruoyi.system.mapper; import java.util.List; import com.ruoyi.common.core.domain.entity.SysUser; import org.apache.ibatis.annotations.Param; /** * 用户表 数据层 * * @author ruoyi */ public interface SysUserMapper { /** * 根据条件分页查询用户列表 * * @param sysUser 用户信息 * @return 用户信息集合信息 */ public List<SysUser> selectUserList(SysUser sysUser); /** * 通过用户名查询用户 * * @param userName 用户名 * @return 用户对象信息 */ public SysUser selectUserByUserName(String userName); /** * 通过用户ID查询用户 * * @param userId 用户ID * @return 用户对象信息 */ public SysUser selectUserById(Long userId); /** * 新增用户信息 * * @param user 用户信息 * @return 结果 */ public int insertUser(SysUser user); /** * 修改用户信息 * * @param user 用户信息 * @return 结果 */ public int updateUser(SysUser user); /** * 修改用户头像 * * @param userName 用户名 * @param avatar 头像地址 * @return 结果 */ public int updateUserAvatar(@Param("userName") String userName, @Param("avatar") String avatar); /** * 重置用户密码 * * @param userName 用户名 * @param password 密码 * @return 结果 */ public int resetUserPwd(@Param("userName") String userName, @Param("password") String password); /** * 通过用户ID删除用户 * * @param userId 用户ID * @return 结果 */ public int deleteUserById(Long userId); /** * 批量删除用户信息 * * @param userIds 需要删除的用户ID * @return 结果 */ public int deleteUserByIds(Long[] userIds); /** * 校验用户名称是否唯一 * * @param userName 用户名称 * @return 结果 */ public int checkUserNameUnique(String userName); /** * 校验手机号码是否唯一 * * @param phonenumber 手机号码 * @return 结果 */ public SysUser checkPhoneUnique(String phonenumber); /** * 校验email是否唯一 * * @param email 用户邮箱 * @return 结果 */ public SysUser checkEmailUnique(String email); }
package parts.login.service; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import parts.login.domain.User; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @SpringBootTest public class UserServiceTest { @Autowired private UserService userService; @Test public void test_findByUsername(){ String username = "user"; User user = userService.findByUsername(username); assertEquals(username, user.getUsername()); } @Test public void test_save(){ //given final PasswordEncoder encoder = new BCryptPasswordEncoder(); User user = User.builder() .username("user") .password(encoder.encode("123123")) .build(); //when userService.save(user); //then User result = userService.findByUsername("user"); assertNotNull(result); } }
/* * Copyright (c) 2010-2014. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.messaging.metadata; import org.axonframework.messaging.Message; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * CorrelationDataProvider that combines the data of multiple other correlation providers. When multiple instance * provide the same keys, a delegate will override the entries provided by previously resolved delegates. * * @author Allard Buijze * @since 2.3 */ public class MultiCorrelationDataProvider<T extends Message> implements CorrelationDataProvider { private final List<? extends CorrelationDataProvider> delegates; /** * Initialize the correlation data provider, delegating to given <code>correlationDataProviders</code>. * * @param correlationDataProviders the providers to delegate to. */ public MultiCorrelationDataProvider(List<? extends CorrelationDataProvider> correlationDataProviders) { delegates = new ArrayList<>(correlationDataProviders); } @Override public Map<String, ?> correlationDataFor(Message<?> message) { Map<String, Object> correlationData = new HashMap<>(); for (CorrelationDataProvider delegate : delegates) { final Map<String, ?> extraData = delegate.correlationDataFor(message); if (extraData != null) { correlationData.putAll(extraData); } } return correlationData; } }
/* * 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.glaf.core.util; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.FormulaEvaluator; public class ExcelUtils { public static String getCellValue(CellValue cell, int precision) { String cellValue = null; if (cell.getCellTypeEnum() == CellType.NUMERIC) { double value = cell.getNumberValue(); if (precision > 0) { value = Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision); } cellValue = String.valueOf(value); if (cellValue != null && cellValue.trim().endsWith(".0")) { cellValue = cellValue.substring(0, cellValue.length() - 2); } } else if (cell.getCellTypeEnum() == CellType.FORMULA) { } else { cellValue = cell.getStringValue(); } return cellValue; } public static String getString(HSSFCell cell, int precision) { String strValue = null; if (cell.getCellTypeEnum() == CellType.NUMERIC) { double value = cell.getNumericCellValue(); DecimalFormat nf = new DecimalFormat("###"); return nf.format(value); } else if (cell.getCellTypeEnum() == CellType.STRING) { strValue = cell.getStringCellValue(); } else if (cell.getCellTypeEnum() == CellType.FORMULA) { } if (strValue != null) { return strValue; } return ""; } public static String getStringOrDateValue(HSSFCell cell, int precision) { String strValue = null; if (cell.getCellTypeEnum() == CellType.NUMERIC) { short format = cell.getCellStyle().getDataFormat(); SimpleDateFormat sdf = null; if (format == 14 || format == 31 || format == 57 || format == 58 || (176 <= format && format <= 178) || (182 <= format && format <= 196) || (210 <= format && format <= 213) || (208 == format)) { // 日期 sdf = new SimpleDateFormat("yyyy-MM-dd"); } else if (format == 20 || format == 32 || format == 183 || (200 <= format && format <= 209)) { // 时间 sdf = new SimpleDateFormat("HH:mm"); } else { // 不是日期格式 double value = cell.getNumericCellValue(); if (precision > 0) { value = Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision); } strValue = String.valueOf(value); if (strValue != null && strValue.trim().endsWith(".0")) { strValue = strValue.substring(0, strValue.length() - 2); } return strValue; } double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value); if (date == null) { return ""; } String result = ""; try { result = sdf.format(date); } catch (Exception e) { return ""; } // logger.debug(result); return result; } else if (cell.getCellTypeEnum() == CellType.STRING) { strValue = cell.getStringCellValue(); } else if (cell.getCellTypeEnum() == CellType.FORMULA) { } if (strValue != null) { return strValue; } return ""; } public static String getValue(FormulaEvaluator evaluator, HSSFCell cell, int precision) { String strValue = null; if (cell.getCellTypeEnum() == CellType.NUMERIC) { double value = cell.getNumericCellValue(); if (precision > 0) { value = Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision); } strValue = String.valueOf(value); if (strValue != null && strValue.trim().endsWith(".0")) { strValue = strValue.substring(0, strValue.length() - 2); } return strValue; } else if (cell.getCellTypeEnum() == CellType.STRING) { strValue = cell.getStringCellValue(); } else if (cell.getCellTypeEnum() == CellType.FORMULA) { CellValue cellValue = evaluator.evaluate(cell); strValue = getCellValue(cellValue, precision); } if (strValue != null) { return strValue; } return ""; } public static String getValue(HSSFCell cell, int precision) { String strValue = null; if (cell.getCellTypeEnum() == CellType.NUMERIC) { double value = cell.getNumericCellValue(); if (precision > 0) { value = Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision); } strValue = String.valueOf(value); if (strValue != null && strValue.trim().endsWith(".0")) { strValue = strValue.substring(0, strValue.length() - 2); } return strValue; } else if (cell.getCellTypeEnum() == CellType.STRING) { strValue = cell.getStringCellValue(); } else if (cell.getCellTypeEnum() == CellType.FORMULA) { } if (strValue != null) { return strValue; } return ""; } private ExcelUtils() { } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.util.webui; import alluxio.conf.AlluxioConfiguration; import alluxio.conf.PropertyKey; import alluxio.wire.BlockLocation; import alluxio.wire.FileBlockInfo; import com.google.common.base.Preconditions; import com.google.common.net.HostAndPort; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.concurrent.ThreadSafe; /** * Contains information for displaying a file block in the UI. */ @ThreadSafe public final class UIFileBlockInfo { private final List<String> mLocations = new ArrayList<>(); private final Set<String> mTierAliases = new HashSet<>(); private final long mId; private final long mBlockLength; private final long mLastAccessTimeMs; private final boolean mIsInHighestTier; /** * Creates a new instance of {@link alluxio.util.webui.UIFileBlockInfo}. * * @param fileBlockInfo underlying {@link FileBlockInfo} * @param alluxioConfiguration the alluxio configuration */ public UIFileBlockInfo(FileBlockInfo fileBlockInfo, AlluxioConfiguration alluxioConfiguration) { Preconditions.checkNotNull(fileBlockInfo, "fileBlockInfo"); mId = fileBlockInfo.getBlockInfo().getBlockId(); mBlockLength = fileBlockInfo.getBlockInfo().getLength(); mLastAccessTimeMs = -1; addLocations(fileBlockInfo); for (BlockLocation location : fileBlockInfo.getBlockInfo().getLocations()) { mTierAliases.add(location.getTierAlias()); } mIsInHighestTier = mTierAliases .contains(alluxioConfiguration.get(PropertyKey.MASTER_TIERED_STORE_GLOBAL_LEVEL0_ALIAS)); } /** * Creates a new instance of {@link alluxio.util.webui.UIFileBlockInfo}. * * @param blockId the block id * @param blockLength the block length * @param blockLastAccessTimeMs the block last access time in milliseconds * @param tierAlias the tier alias of the block * @param alluxioConfiguration the alluxio configuration */ public UIFileBlockInfo(long blockId, long blockLength, long blockLastAccessTimeMs, String tierAlias, AlluxioConfiguration alluxioConfiguration) { mId = blockId; mBlockLength = blockLength; mLastAccessTimeMs = blockLastAccessTimeMs; mTierAliases.add(tierAlias); mIsInHighestTier = mTierAliases .contains(alluxioConfiguration.get(PropertyKey.MASTER_TIERED_STORE_GLOBAL_LEVEL0_ALIAS)); } private void addLocations(FileBlockInfo fileBlockInfo) { Set<String> locations = new HashSet<>(); // add alluxio locations for (BlockLocation location : fileBlockInfo.getBlockInfo().getLocations()) { locations.add(location.getWorkerAddress().getHost()); } // add underFS locations for (String location : fileBlockInfo.getUfsLocations()) { locations.add(HostAndPort.fromString(location).getHost()); } mLocations.addAll(locations); } /** * Is in tier boolean. * * @param tierAlias the alias for the tier * @return true if the block is in the given tier alias in some worker, false otherwise */ public boolean isInTier(String tierAlias) { return mTierAliases.contains(tierAlias); } /** * Gets block length. * * @return the block length */ public long getBlockLength() { return mBlockLength; } /** * Gets id. * * @return the block id */ public long getID() { return mId; } /** * Gets last access time ms. * * @return the block last access time in milliseconds */ public long getLastAccessTimeMs() { return mLastAccessTimeMs; } /** * Gets locations. * * @return the block locations */ public List<String> getLocations() { return mLocations; } /** * Gets whether the block is in the highest tier alias. * * @return true if it's in the highest tier alias */ public boolean getIsInHighestTier() { return mIsInHighestTier; } }
/* * 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.openjpa.enhance; public interface UnenhancedSubtype extends UnenhancedType { UnenhancedType getRelated(); void setRelated(UnenhancedType related); void setIntField(int i); int getIntField(); }
package org.jbpm.executor.impl.jpa; import static org.kie.internal.query.QueryParameterIdentifiers.COMMAND_NAME_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.DEPLOYMENT_ID_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.EXECUTOR_EXECUTIONS_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.EXECUTOR_KEY_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.EXECUTOR_OWNER_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.EXECUTOR_RETRIES_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.EXECUTOR_STATUS_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.EXECUTOR_TIME_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.ID_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.MESSAGE_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.STACK_TRACE_LIST; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.metamodel.Attribute; import org.jbpm.executor.entities.ErrorInfo_; import org.jbpm.executor.entities.RequestInfo_; import org.jbpm.query.jpa.data.QueryCriteria; import org.jbpm.query.jpa.data.QueryWhere; import org.jbpm.query.jpa.impl.QueryCriteriaUtil; public class ExecutorQueryCriteriaUtil extends QueryCriteriaUtil { // Query Field Info ----------------------------------------------------------------------------------------------------------- public final static Map<Class, Map<String, Attribute>> criteriaAttributes = new ConcurrentHashMap<Class, Map<String, Attribute>>(); @Override protected synchronized boolean initializeCriteriaAttributes() { if( ErrorInfo_.id == null ) { // EMF/persistence has not been initialized: // When a persistence unit (EntityManagerFactory) is initialized, // the fields of classes annotated with @StaticMetamodel are filled using reflection return false; } // do not do initialization twice (slow performance, otherwise it doesn't matter) if( ! criteriaAttributes.isEmpty() ) { return true; } // ErrorInfoImpl addCriteria(criteriaAttributes, MESSAGE_LIST, ErrorInfo_.message); addCriteria(criteriaAttributes, ID_LIST, ErrorInfo_.id); addCriteria(criteriaAttributes, STACK_TRACE_LIST, ErrorInfo_.stacktrace); addCriteria(criteriaAttributes, EXECUTOR_TIME_LIST, ErrorInfo_.time); // RequestInfo addCriteria(criteriaAttributes, COMMAND_NAME_LIST, RequestInfo_.commandName); addCriteria(criteriaAttributes, DEPLOYMENT_ID_LIST, RequestInfo_.deploymentId); addCriteria(criteriaAttributes, EXECUTOR_EXECUTIONS_LIST, RequestInfo_.executions); addCriteria(criteriaAttributes, ID_LIST, RequestInfo_.id); addCriteria(criteriaAttributes, EXECUTOR_KEY_LIST, RequestInfo_.key); addCriteria(criteriaAttributes, MESSAGE_LIST, RequestInfo_.message); addCriteria(criteriaAttributes, EXECUTOR_OWNER_LIST, RequestInfo_.owner); addCriteria(criteriaAttributes, EXECUTOR_RETRIES_LIST, RequestInfo_.retries); addCriteria(criteriaAttributes, EXECUTOR_STATUS_LIST, RequestInfo_.status); addCriteria(criteriaAttributes, EXECUTOR_TIME_LIST, RequestInfo_.time); return true; } // Implementation specific logic ---------------------------------------------------------------------------------------------- private ExecutorJPAAuditService executorAuditService; public ExecutorQueryCriteriaUtil(ExecutorJPAAuditService service) { super(criteriaAttributes); this.executorAuditService = service; } private EntityManager getEntityManager() { return this.executorAuditService.getEntityManager(); } private Object joinTransaction(EntityManager em) { return this.executorAuditService.joinTransaction(em); } private void closeEntityManager(EntityManager em, Object transaction) { this.executorAuditService.closeEntityManager(em, transaction); } // Implementation specific methods -------------------------------------------------------------------------------------------- protected CriteriaBuilder getCriteriaBuilder() { return getEntityManager().getCriteriaBuilder(); } @Override protected <T> List<T> createQueryAndCallApplyMetaCriteriaAndGetResult(QueryWhere queryWhere, CriteriaQuery<T> criteriaQuery, CriteriaBuilder builder) { EntityManager em = getEntityManager(); Object newTx = joinTransaction(em); Query query = em.createQuery(criteriaQuery); applyMetaCriteriaToQuery(query, queryWhere); // execute query List<T> result = query.getResultList(); closeEntityManager(em, newTx); return result; } @Override protected <R,T> Predicate implSpecificCreatePredicateFromSingleCriteria( CriteriaQuery<R> query, CriteriaBuilder builder, Class queryType, QueryCriteria criteria, QueryWhere queryWhere) { throw new IllegalStateException("List id " + criteria.getListId() + " is not supported for queries on " + queryType.getSimpleName() + "."); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.biojava.bio.structure; /** * Describes author attributes for author information in a PDB file. * @author Jules Jacobsen */ public class Author { private String surname = ""; private String initials = ""; public String getInitials() { return initials; } public void setInitials(String initials) { this.initials = initials; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Author other = (Author) obj; if ((this.surname == null) ? (other.surname != null) : !this.surname.equals(other.surname)) { return false; } if ((this.initials == null) ? (other.initials != null) : !this.initials.equals(other.initials)) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 19 * hash + (this.surname != null ? this.surname.hashCode() : 0); hash = 19 * hash + (this.initials != null ? this.initials.hashCode() : 0); return hash; } @Override public String toString() { return initials + surname; } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|// Copyright (C) 2013 The Android Open Source Project end_comment begin_comment comment|// end_comment begin_comment comment|// Licensed under the Apache License, Version 2.0 (the "License"); end_comment begin_comment comment|// you may not use this file except in compliance with the License. end_comment begin_comment comment|// You may obtain a copy of the License at end_comment begin_comment comment|// end_comment begin_comment comment|// http://www.apache.org/licenses/LICENSE-2.0 end_comment begin_comment comment|// end_comment begin_comment comment|// Unless required by applicable law or agreed to in writing, software end_comment begin_comment comment|// distributed under the License is distributed on an "AS IS" BASIS, end_comment begin_comment comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. end_comment begin_comment comment|// See the License for the specific language governing permissions and end_comment begin_comment comment|// limitations under the License. end_comment begin_package DECL|package|com.google.gerrit.server.restapi.group package|package name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|restapi operator|. name|group package|; end_package begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|ImmutableList import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|Sets import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|common operator|. name|data operator|. name|GroupDescription import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|entities operator|. name|AccountGroup import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|exceptions operator|. name|NoSuchGroupException import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|restapi operator|. name|AuthException import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|restapi operator|. name|MethodNotAllowedException import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|restapi operator|. name|ResourceNotFoundException import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|restapi operator|. name|Response import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|restapi operator|. name|RestModifyView import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|restapi operator|. name|UnprocessableEntityException import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|UserInitiated import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|account operator|. name|GroupControl import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|group operator|. name|GroupResolver import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|group operator|. name|GroupResource import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|group operator|. name|SubgroupResource import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|group operator|. name|db operator|. name|GroupsUpdate import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|group operator|. name|db operator|. name|InternalGroupUpdate import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|server operator|. name|restapi operator|. name|group operator|. name|AddSubgroups operator|. name|Input import|; end_import begin_import import|import name|com operator|. name|google operator|. name|inject operator|. name|Inject import|; end_import begin_import import|import name|com operator|. name|google operator|. name|inject operator|. name|Provider import|; end_import begin_import import|import name|com operator|. name|google operator|. name|inject operator|. name|Singleton import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashSet import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|errors operator|. name|ConfigInvalidException import|; end_import begin_class annotation|@ name|Singleton DECL|class|DeleteSubgroups specifier|public class|class name|DeleteSubgroups implements|implements name|RestModifyView argument_list|< name|GroupResource argument_list|, name|Input argument_list|> block|{ DECL|field|groupResolver specifier|private specifier|final name|GroupResolver name|groupResolver decl_stmt|; DECL|field|groupsUpdateProvider specifier|private specifier|final name|Provider argument_list|< name|GroupsUpdate argument_list|> name|groupsUpdateProvider decl_stmt|; annotation|@ name|Inject DECL|method|DeleteSubgroups ( GroupResolver groupResolver, @UserInitiated Provider<GroupsUpdate> groupsUpdateProvider) name|DeleteSubgroups parameter_list|( name|GroupResolver name|groupResolver parameter_list|, annotation|@ name|UserInitiated name|Provider argument_list|< name|GroupsUpdate argument_list|> name|groupsUpdateProvider parameter_list|) block|{ name|this operator|. name|groupResolver operator|= name|groupResolver expr_stmt|; name|this operator|. name|groupsUpdateProvider operator|= name|groupsUpdateProvider expr_stmt|; block|} annotation|@ name|Override DECL|method|apply (GroupResource resource, Input input) specifier|public name|Response argument_list|< name|? argument_list|> name|apply parameter_list|( name|GroupResource name|resource parameter_list|, name|Input name|input parameter_list|) throws|throws name|AuthException throws|, name|NotInternalGroupException throws|, name|UnprocessableEntityException throws|, name|ResourceNotFoundException throws|, name|IOException throws|, name|ConfigInvalidException block|{ name|GroupDescription operator|. name|Internal name|internalGroup init|= name|resource operator|. name|asInternalGroup argument_list|() operator|. name|orElseThrow argument_list|( name|NotInternalGroupException operator|:: operator|new argument_list|) decl_stmt|; name|input operator|= name|Input operator|. name|init argument_list|( name|input argument_list|) expr_stmt|; specifier|final name|GroupControl name|control init|= name|resource operator|. name|getControl argument_list|() decl_stmt|; if|if condition|( operator|! name|control operator|. name|canRemoveGroup argument_list|() condition|) block|{ throw|throw operator|new name|AuthException argument_list|( name|String operator|. name|format argument_list|( literal|"Cannot delete groups from group %s" argument_list|, name|internalGroup operator|. name|getName argument_list|() argument_list|) argument_list|) throw|; block|} name|Set argument_list|< name|AccountGroup operator|. name|UUID argument_list|> name|subgroupsToRemove init|= operator|new name|HashSet argument_list|<> argument_list|() decl_stmt|; for|for control|( name|String name|subgroupIdentifier range|: name|input operator|. name|groups control|) block|{ name|GroupDescription operator|. name|Basic name|subgroup init|= name|groupResolver operator|. name|parse argument_list|( name|subgroupIdentifier argument_list|) decl_stmt|; name|subgroupsToRemove operator|. name|add argument_list|( name|subgroup operator|. name|getGroupUUID argument_list|() argument_list|) expr_stmt|; block|} name|AccountGroup operator|. name|UUID name|groupUuid init|= name|internalGroup operator|. name|getGroupUUID argument_list|() decl_stmt|; try|try block|{ name|removeSubgroups argument_list|( name|groupUuid argument_list|, name|subgroupsToRemove argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|NoSuchGroupException name|e parameter_list|) block|{ throw|throw operator|new name|ResourceNotFoundException argument_list|( name|String operator|. name|format argument_list|( literal|"Group %s not found" argument_list|, name|groupUuid argument_list|) argument_list|) throw|; block|} return|return name|Response operator|. name|none argument_list|() return|; block|} DECL|method|removeSubgroups ( AccountGroup.UUID parentGroupUuid, Set<AccountGroup.UUID> removedSubgroupUuids) specifier|private name|void name|removeSubgroups parameter_list|( name|AccountGroup operator|. name|UUID name|parentGroupUuid parameter_list|, name|Set argument_list|< name|AccountGroup operator|. name|UUID argument_list|> name|removedSubgroupUuids parameter_list|) throws|throws name|NoSuchGroupException throws|, name|IOException throws|, name|ConfigInvalidException block|{ name|InternalGroupUpdate name|groupUpdate init|= name|InternalGroupUpdate operator|. name|builder argument_list|() operator|. name|setSubgroupModification argument_list|( name|subgroupUuids lambda|-> name|Sets operator|. name|difference argument_list|( name|subgroupUuids argument_list|, name|removedSubgroupUuids argument_list|) argument_list|) operator|. name|build argument_list|() decl_stmt|; name|groupsUpdateProvider operator|. name|get argument_list|() operator|. name|updateGroup argument_list|( name|parentGroupUuid argument_list|, name|groupUpdate argument_list|) expr_stmt|; block|} annotation|@ name|Singleton DECL|class|DeleteSubgroup specifier|public specifier|static class|class name|DeleteSubgroup implements|implements name|RestModifyView argument_list|< name|SubgroupResource argument_list|, name|Input argument_list|> block|{ DECL|field|delete specifier|private specifier|final name|Provider argument_list|< name|DeleteSubgroups argument_list|> name|delete decl_stmt|; annotation|@ name|Inject DECL|method|DeleteSubgroup (Provider<DeleteSubgroups> delete) specifier|public name|DeleteSubgroup parameter_list|( name|Provider argument_list|< name|DeleteSubgroups argument_list|> name|delete parameter_list|) block|{ name|this operator|. name|delete operator|= name|delete expr_stmt|; block|} annotation|@ name|Override DECL|method|apply (SubgroupResource resource, Input input) specifier|public name|Response argument_list|< name|? argument_list|> name|apply parameter_list|( name|SubgroupResource name|resource parameter_list|, name|Input name|input parameter_list|) throws|throws name|AuthException throws|, name|MethodNotAllowedException throws|, name|UnprocessableEntityException throws|, name|ResourceNotFoundException throws|, name|IOException throws|, name|ConfigInvalidException block|{ name|AddSubgroups operator|. name|Input name|in init|= operator|new name|AddSubgroups operator|. name|Input argument_list|() decl_stmt|; name|in operator|. name|groups operator|= name|ImmutableList operator|. name|of argument_list|( name|resource operator|. name|getMember argument_list|() operator|. name|get argument_list|() argument_list|) expr_stmt|; return|return name|delete operator|. name|get argument_list|() operator|. name|apply argument_list|( name|resource argument_list|, name|in argument_list|) return|; block|} block|} block|} end_class end_unit
/* * 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.flink.hdfstests; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.io.FileInputFormat; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.io.TextInputFormat; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.typeutils.TypeExtractor; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.fs.FileInputSplit; import org.apache.flink.core.fs.Path; import org.apache.flink.api.common.io.FilePathFilter; import org.apache.flink.core.testutils.OneShotLatch; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.functions.source.ContinuousFileMonitoringFunction; import org.apache.flink.streaming.api.functions.source.ContinuousFileReaderOperator; import org.apache.flink.streaming.api.functions.source.TimestampedFileInputSplit; import org.apache.flink.streaming.api.functions.source.FileProcessingMode; import org.apache.flink.streaming.api.functions.source.SourceFunction; import org.apache.flink.streaming.api.operators.StreamSource; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.streaming.runtime.tasks.OperatorStateHandles; import org.apache.flink.streaming.util.AbstractStreamOperatorTestHarness; import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness; import org.apache.flink.util.Preconditions; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.ConcurrentLinkedQueue; public class ContinuousFileProcessingTest { private static final int NO_OF_FILES = 5; private static final int LINES_PER_FILE = 10; private static final long INTERVAL = 100; private static File baseDir; private static FileSystem hdfs; private static String hdfsURI; private static MiniDFSCluster hdfsCluster; // PREPARING FOR THE TESTS @BeforeClass public static void createHDFS() { try { baseDir = new File("./target/hdfs/hdfsTesting").getAbsoluteFile(); FileUtil.fullyDelete(baseDir); org.apache.hadoop.conf.Configuration hdConf = new org.apache.hadoop.conf.Configuration(); hdConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath()); hdConf.set("dfs.block.size", String.valueOf(1048576)); // this is the minimum we can set. MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(hdConf); hdfsCluster = builder.build(); hdfsURI = "hdfs://" + hdfsCluster.getURI().getHost() + ":" + hdfsCluster.getNameNodePort() +"/"; hdfs = new org.apache.hadoop.fs.Path(hdfsURI).getFileSystem(hdConf); } catch(Throwable e) { e.printStackTrace(); Assert.fail("Test failed " + e.getMessage()); } } @AfterClass public static void destroyHDFS() { try { FileUtil.fullyDelete(baseDir); hdfsCluster.shutdown(); } catch (Throwable t) { throw new RuntimeException(t); } } // END OF PREPARATIONS // TESTS @Test public void testInvalidPathSpecification() throws Exception { String invalidPath = "hdfs://" + hdfsCluster.getURI().getHost() + ":" + hdfsCluster.getNameNodePort() +"/invalid/"; TextInputFormat format = new TextInputFormat(new Path(invalidPath)); ContinuousFileMonitoringFunction<String> monitoringFunction = new ContinuousFileMonitoringFunction<>(format, FileProcessingMode.PROCESS_ONCE, 1, INTERVAL); try { monitoringFunction.run(new DummySourceContext() { @Override public void collect(TimestampedFileInputSplit element) { // we should never arrive here with an invalid path Assert.fail("Test passes with an invalid path."); } }); // we should never arrive here with an invalid path Assert.fail("Test passed with an invalid path."); } catch (FileNotFoundException e) { Assert.assertEquals("The provided file path " + format.getFilePath() + " does not exist.", e.getMessage()); } } @Test public void testFileReadingOperatorWithIngestionTime() throws Exception { Set<org.apache.hadoop.fs.Path> filesCreated = new HashSet<>(); Map<Integer, String> expectedFileContents = new HashMap<>(); Map<String, Long> modTimes = new HashMap<>(); for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(hdfsURI, "file", i, "This is test line."); filesCreated.add(file.f0); modTimes.put(file.f0.getName(), hdfs.getFileStatus(file.f0).getModificationTime()); expectedFileContents.put(i, file.f1); } TextInputFormat format = new TextInputFormat(new Path(hdfsURI)); TypeInformation<String> typeInfo = TypeExtractor.getInputFormatTypes(format); final long watermarkInterval = 10; ContinuousFileReaderOperator<String> reader = new ContinuousFileReaderOperator<>(format); final OneInputStreamOperatorTestHarness<TimestampedFileInputSplit, String> tester = new OneInputStreamOperatorTestHarness<>(reader); tester.getExecutionConfig().setAutoWatermarkInterval(watermarkInterval); tester.setTimeCharacteristic(TimeCharacteristic.IngestionTime); reader.setOutputType(typeInfo, tester.getExecutionConfig()); tester.open(); Assert.assertEquals(TimeCharacteristic.IngestionTime, tester.getTimeCharacteristic()); // test that watermarks are correctly emitted ConcurrentLinkedQueue<Object> output = tester.getOutput(); tester.setProcessingTime(201); Assert.assertTrue(output.peek() instanceof Watermark); Assert.assertEquals(200, ((Watermark) output.poll()).getTimestamp()); tester.setProcessingTime(301); Assert.assertTrue(output.peek() instanceof Watermark); Assert.assertEquals(300, ((Watermark) output.poll()).getTimestamp()); tester.setProcessingTime(401); Assert.assertTrue(output.peek() instanceof Watermark); Assert.assertEquals(400, ((Watermark) output.poll()).getTimestamp()); tester.setProcessingTime(501); Assert.assertTrue(output.peek() instanceof Watermark); Assert.assertEquals(500, ((Watermark) output.poll()).getTimestamp()); Assert.assertTrue(output.isEmpty()); // create the necessary splits for the test FileInputSplit[] splits = format.createInputSplits( reader.getRuntimeContext().getNumberOfParallelSubtasks()); // and feed them to the operator Map<Integer, List<String>> actualFileContents = new HashMap<>(); long lastSeenWatermark = Long.MIN_VALUE; int lineCounter = 0; // counter for the lines read from the splits int watermarkCounter = 0; for (FileInputSplit split: splits) { // set the next "current processing time". long nextTimestamp = tester.getProcessingTime() + watermarkInterval; tester.setProcessingTime(nextTimestamp); // send the next split to be read and wait until it is fully read, the +1 is for the watermark. tester.processElement(new StreamRecord<>( new TimestampedFileInputSplit(modTimes.get(split.getPath().getName()), split.getSplitNumber(), split.getPath(), split.getStart(), split.getLength(), split.getHostnames()))); // NOTE: the following check works because each file fits in one split. // In other case it would fail and wait forever. // BUT THIS IS JUST FOR THIS TEST while (tester.getOutput().isEmpty() || tester.getOutput().size() != (LINES_PER_FILE + 1)) { Thread.sleep(10); } // verify that the results are the expected for (Object line: tester.getOutput()) { if (line instanceof StreamRecord) { @SuppressWarnings("unchecked") StreamRecord<String> element = (StreamRecord<String>) line; lineCounter++; Assert.assertEquals(nextTimestamp, element.getTimestamp()); int fileIdx = Character.getNumericValue(element.getValue().charAt(0)); List<String> content = actualFileContents.get(fileIdx); if (content == null) { content = new ArrayList<>(); actualFileContents.put(fileIdx, content); } content.add(element.getValue() + "\n"); } else if (line instanceof Watermark) { long watermark = ((Watermark) line).getTimestamp(); Assert.assertEquals(nextTimestamp - (nextTimestamp % watermarkInterval), watermark); Assert.assertTrue(watermark > lastSeenWatermark); watermarkCounter++; lastSeenWatermark = watermark; } else { Assert.fail("Unknown element in the list."); } } // clean the output to be ready for the next split tester.getOutput().clear(); } // now we are processing one split after the other, // so all the elements must be here by now. Assert.assertEquals(NO_OF_FILES * LINES_PER_FILE, lineCounter); // because we expect one watermark per split. Assert.assertEquals(splits.length, watermarkCounter); // then close the reader gracefully so that the Long.MAX watermark is emitted synchronized (tester.getCheckpointLock()) { tester.close(); } for (org.apache.hadoop.fs.Path file: filesCreated) { hdfs.delete(file, false); } // check if the last element is the LongMax watermark (by now this must be the only element) Assert.assertEquals(1, tester.getOutput().size()); Assert.assertTrue(tester.getOutput().peek() instanceof Watermark); Assert.assertEquals(Long.MAX_VALUE, ((Watermark) tester.getOutput().poll()).getTimestamp()); // check if the elements are the expected ones. Assert.assertEquals(expectedFileContents.size(), actualFileContents.size()); for (Integer fileIdx: expectedFileContents.keySet()) { Assert.assertTrue("file" + fileIdx + " not found", actualFileContents.keySet().contains(fileIdx)); List<String> cntnt = actualFileContents.get(fileIdx); Collections.sort(cntnt, new Comparator<String>() { @Override public int compare(String o1, String o2) { return getLineNo(o1) - getLineNo(o2); } }); StringBuilder cntntStr = new StringBuilder(); for (String line: cntnt) { cntntStr.append(line); } Assert.assertEquals(expectedFileContents.get(fileIdx), cntntStr.toString()); } } @Test public void testFileReadingOperatorWithEventTime() throws Exception { Set<org.apache.hadoop.fs.Path> filesCreated = new HashSet<>(); Map<String, Long> modTimes = new HashMap<>(); Map<Integer, String> expectedFileContents = new HashMap<>(); for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(hdfsURI, "file", i, "This is test line."); modTimes.put(file.f0.getName(), hdfs.getFileStatus(file.f0).getModificationTime()); filesCreated.add(file.f0); expectedFileContents.put(i, file.f1); } TextInputFormat format = new TextInputFormat(new Path(hdfsURI)); TypeInformation<String> typeInfo = TypeExtractor.getInputFormatTypes(format); ContinuousFileReaderOperator<String> reader = new ContinuousFileReaderOperator<>(format); reader.setOutputType(typeInfo, new ExecutionConfig()); OneInputStreamOperatorTestHarness<TimestampedFileInputSplit, String> tester = new OneInputStreamOperatorTestHarness<>(reader); tester.setTimeCharacteristic(TimeCharacteristic.EventTime); tester.open(); // create the necessary splits for the test FileInputSplit[] splits = format.createInputSplits( reader.getRuntimeContext().getNumberOfParallelSubtasks()); // and feed them to the operator for (FileInputSplit split: splits) { tester.processElement(new StreamRecord<>(new TimestampedFileInputSplit( modTimes.get(split.getPath().getName()), split.getSplitNumber(), split.getPath(), split.getStart(), split.getLength(), split.getHostnames()))); } // then close the reader gracefully (and wait to finish reading) synchronized (tester.getCheckpointLock()) { tester.close(); } // the lines received must be the elements in the files +1 for for the longMax watermark // we are in event time, which emits no watermarks, so the last watermark will mark the // of the input stream. Assert.assertEquals(NO_OF_FILES * LINES_PER_FILE + 1, tester.getOutput().size()); Map<Integer, List<String>> actualFileContents = new HashMap<>(); Object lastElement = null; for (Object line: tester.getOutput()) { lastElement = line; if (line instanceof StreamRecord) { @SuppressWarnings("unchecked") StreamRecord<String> element = (StreamRecord<String>) line; int fileIdx = Character.getNumericValue(element.getValue().charAt(0)); List<String> content = actualFileContents.get(fileIdx); if (content == null) { content = new ArrayList<>(); actualFileContents.put(fileIdx, content); } content.add(element.getValue() + "\n"); } } // check if the last element is the LongMax watermark Assert.assertTrue(lastElement instanceof Watermark); Assert.assertEquals(Long.MAX_VALUE, ((Watermark) lastElement).getTimestamp()); Assert.assertEquals(expectedFileContents.size(), actualFileContents.size()); for (Integer fileIdx: expectedFileContents.keySet()) { Assert.assertTrue("file" + fileIdx + " not found", actualFileContents.keySet().contains(fileIdx)); List<String> cntnt = actualFileContents.get(fileIdx); Collections.sort(cntnt, new Comparator<String>() { @Override public int compare(String o1, String o2) { return getLineNo(o1) - getLineNo(o2); } }); StringBuilder cntntStr = new StringBuilder(); for (String line: cntnt) { cntntStr.append(line); } Assert.assertEquals(expectedFileContents.get(fileIdx), cntntStr.toString()); } for (org.apache.hadoop.fs.Path file: filesCreated) { hdfs.delete(file, false); } } @Test public void testReaderSnapshotRestore() throws Exception { TimestampedFileInputSplit split1 = new TimestampedFileInputSplit(0, 3, new Path("test/test1"), 0, 100, null); TimestampedFileInputSplit split2 = new TimestampedFileInputSplit(10, 2, new Path("test/test2"), 101, 200, null); TimestampedFileInputSplit split3 = new TimestampedFileInputSplit(10, 1, new Path("test/test2"), 0, 100, null); TimestampedFileInputSplit split4 = new TimestampedFileInputSplit(11, 0, new Path("test/test3"), 0, 100, null); final OneShotLatch latch = new OneShotLatch(); BlockingFileInputFormat format = new BlockingFileInputFormat(latch, new Path(hdfsURI)); TypeInformation<FileInputSplit> typeInfo = TypeExtractor.getInputFormatTypes(format); ContinuousFileReaderOperator<FileInputSplit> initReader = new ContinuousFileReaderOperator<>(format); initReader.setOutputType(typeInfo, new ExecutionConfig()); OneInputStreamOperatorTestHarness<TimestampedFileInputSplit, FileInputSplit> initTestInstance = new OneInputStreamOperatorTestHarness<>(initReader); initTestInstance.setTimeCharacteristic(TimeCharacteristic.EventTime); initTestInstance.open(); // create some state in the reader initTestInstance.processElement(new StreamRecord<>(split1)); initTestInstance.processElement(new StreamRecord<>(split2)); initTestInstance.processElement(new StreamRecord<>(split3)); initTestInstance.processElement(new StreamRecord<>(split4)); // take a snapshot of the operator's state. This will be used // to initialize another reader and compare the results of the // two operators. final OperatorStateHandles snapshot; synchronized (initTestInstance.getCheckpointLock()) { snapshot = initTestInstance.snapshot(0L, 0L); } ContinuousFileReaderOperator<FileInputSplit> restoredReader = new ContinuousFileReaderOperator<>( new BlockingFileInputFormat(latch, new Path(hdfsURI))); restoredReader.setOutputType(typeInfo, new ExecutionConfig()); OneInputStreamOperatorTestHarness<TimestampedFileInputSplit, FileInputSplit> restoredTestInstance = new OneInputStreamOperatorTestHarness<>(restoredReader); restoredTestInstance.setTimeCharacteristic(TimeCharacteristic.EventTime); restoredTestInstance.initializeState(snapshot); restoredTestInstance.open(); // now let computation start latch.trigger(); // ... and wait for the operators to close gracefully synchronized (initTestInstance.getCheckpointLock()) { initTestInstance.close(); } synchronized (restoredTestInstance.getCheckpointLock()) { restoredTestInstance.close(); } FileInputSplit fsSplit1 = createSplitFromTimestampedSplit(split1); FileInputSplit fsSplit2 = createSplitFromTimestampedSplit(split2); FileInputSplit fsSplit3 = createSplitFromTimestampedSplit(split3); FileInputSplit fsSplit4 = createSplitFromTimestampedSplit(split4); // compare if the results contain what they should contain and also if // they are the same, as they should. Assert.assertTrue(initTestInstance.getOutput().contains(new StreamRecord<>(fsSplit1))); Assert.assertTrue(initTestInstance.getOutput().contains(new StreamRecord<>(fsSplit2))); Assert.assertTrue(initTestInstance.getOutput().contains(new StreamRecord<>(fsSplit3))); Assert.assertTrue(initTestInstance.getOutput().contains(new StreamRecord<>(fsSplit4))); Assert.assertArrayEquals( initTestInstance.getOutput().toArray(), restoredTestInstance.getOutput().toArray() ); } private FileInputSplit createSplitFromTimestampedSplit(TimestampedFileInputSplit split) { Preconditions.checkNotNull(split); return new FileInputSplit( split.getSplitNumber(), split.getPath(), split.getStart(), split.getLength(), split.getHostnames() ); } private static class BlockingFileInputFormat extends FileInputFormat<FileInputSplit> { private static final long serialVersionUID = -6727603565381560267L; private final OneShotLatch latch; private FileInputSplit split; private boolean reachedEnd; BlockingFileInputFormat(OneShotLatch latch, Path filePath) { super(filePath); this.latch = latch; this.reachedEnd = false; } @Override public void open(FileInputSplit fileSplit) throws IOException { this.split = fileSplit; this.reachedEnd = false; } @Override public boolean reachedEnd() throws IOException { if (!latch.isTriggered()) { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } return reachedEnd; } @Override public FileInputSplit nextRecord(FileInputSplit reuse) throws IOException { this.reachedEnd = true; return split; } @Override public void close() { } } //// Monitoring Function Tests ////// @Test public void testFilePathFiltering() throws Exception { Set<org.apache.hadoop.fs.Path> filesCreated = new HashSet<>(); Set<String> filesKept = new TreeSet<>(); // create the files to be discarded for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(hdfsURI, "**file", i, "This is test line."); filesCreated.add(file.f0); } // create the files to be kept for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(hdfsURI, "file", i, "This is test line."); filesCreated.add(file.f0); filesKept.add(file.f0.getName()); } TextInputFormat format = new TextInputFormat(new Path(hdfsURI)); format.setFilesFilter(new FilePathFilter() { private static final long serialVersionUID = 2611449927338589804L; @Override public boolean filterPath(Path filePath) { return filePath.getName().startsWith("**"); } }); ContinuousFileMonitoringFunction<String> monitoringFunction = new ContinuousFileMonitoringFunction<>(format, FileProcessingMode.PROCESS_ONCE, 1, INTERVAL); final FileVerifyingSourceContext context = new FileVerifyingSourceContext(new OneShotLatch(), monitoringFunction); monitoringFunction.open(new Configuration()); monitoringFunction.run(context); Assert.assertArrayEquals(filesKept.toArray(), context.getSeenFiles().toArray()); // finally delete the files created for the test. for (org.apache.hadoop.fs.Path file: filesCreated) { hdfs.delete(file, false); } } @Test public void testNestedFilesProcessing() throws Exception { final Set<org.apache.hadoop.fs.Path> filesCreated = new HashSet<>(); final Set<String> filesToBeRead = new TreeSet<>(); // create two nested directories org.apache.hadoop.fs.Path firstLevelDir = new org.apache.hadoop.fs.Path(hdfsURI + "/" + "firstLevelDir"); org.apache.hadoop.fs.Path secondLevelDir = new org.apache.hadoop.fs.Path(hdfsURI + "/" + "firstLevelDir" + "/" + "secondLevelDir"); Assert.assertFalse(hdfs.exists(firstLevelDir)); hdfs.mkdirs(firstLevelDir); hdfs.mkdirs(secondLevelDir); // create files in the base dir, the first level dir and the second level dir for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(hdfsURI, "firstLevelFile", i, "This is test line."); filesCreated.add(file.f0); filesToBeRead.add(file.f0.getName()); } for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(firstLevelDir.toString(), "secondLevelFile", i, "This is test line."); filesCreated.add(file.f0); filesToBeRead.add(file.f0.getName()); } for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(secondLevelDir.toString(), "thirdLevelFile", i, "This is test line."); filesCreated.add(file.f0); filesToBeRead.add(file.f0.getName()); } TextInputFormat format = new TextInputFormat(new Path(hdfsURI)); format.setFilesFilter(FilePathFilter.createDefaultFilter()); format.setNestedFileEnumeration(true); ContinuousFileMonitoringFunction<String> monitoringFunction = new ContinuousFileMonitoringFunction<>(format, FileProcessingMode.PROCESS_ONCE, 1, INTERVAL); final FileVerifyingSourceContext context = new FileVerifyingSourceContext(new OneShotLatch(), monitoringFunction); monitoringFunction.open(new Configuration()); monitoringFunction.run(context); Assert.assertArrayEquals(filesToBeRead.toArray(), context.getSeenFiles().toArray()); // finally delete the dirs and the files created for the test. for (org.apache.hadoop.fs.Path file: filesCreated) { hdfs.delete(file, false); } hdfs.delete(secondLevelDir, false); hdfs.delete(firstLevelDir, false); } @Test public void testSortingOnModTime() throws Exception { final long[] modTimes = new long[NO_OF_FILES]; final org.apache.hadoop.fs.Path[] filesCreated = new org.apache.hadoop.fs.Path[NO_OF_FILES]; for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(hdfsURI, "file", i, "This is test line."); Thread.sleep(400); filesCreated[i] = file.f0; modTimes[i] = hdfs.getFileStatus(file.f0).getModificationTime(); } TextInputFormat format = new TextInputFormat(new Path(hdfsURI)); format.setFilesFilter(FilePathFilter.createDefaultFilter()); // this is just to verify that all splits have been forwarded later. FileInputSplit[] splits = format.createInputSplits(1); ContinuousFileMonitoringFunction<String> monitoringFunction = new ContinuousFileMonitoringFunction<>(format, FileProcessingMode.PROCESS_ONCE, 1, INTERVAL); ModTimeVerifyingSourceContext context = new ModTimeVerifyingSourceContext(modTimes); monitoringFunction.open(new Configuration()); monitoringFunction.run(context); Assert.assertEquals(splits.length, context.getCounter()); // delete the created files. for (int i = 0; i < NO_OF_FILES; i++) { hdfs.delete(filesCreated[i], false); } } @Test public void testProcessOnce() throws Exception { final OneShotLatch latch = new OneShotLatch(); // create a single file in the directory Tuple2<org.apache.hadoop.fs.Path, String> bootstrap = createFileAndFillWithData(hdfsURI, "file", NO_OF_FILES + 1, "This is test line."); Assert.assertTrue(hdfs.exists(bootstrap.f0)); // the source is supposed to read only this file. final Set<String> filesToBeRead = new TreeSet<>(); filesToBeRead.add(bootstrap.f0.getName()); TextInputFormat format = new TextInputFormat(new Path(hdfsURI)); format.setFilesFilter(FilePathFilter.createDefaultFilter()); final ContinuousFileMonitoringFunction<String> monitoringFunction = new ContinuousFileMonitoringFunction<>(format, FileProcessingMode.PROCESS_ONCE, 1, INTERVAL); final FileVerifyingSourceContext context = new FileVerifyingSourceContext(latch, monitoringFunction); final Thread t = new Thread() { @Override public void run() { try { monitoringFunction.open(new Configuration()); monitoringFunction.run(context); // we would never arrive here if we were in // PROCESS_CONTINUOUSLY mode. // this will trigger the latch context.close(); } catch (Exception e) { Assert.fail(e.getMessage()); } } }; t.start(); if (!latch.isTriggered()) { latch.await(); } // create some additional files that should be processed in the case of PROCESS_CONTINUOUSLY final org.apache.hadoop.fs.Path[] filesCreated = new org.apache.hadoop.fs.Path[NO_OF_FILES]; for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> ignoredFile = createFileAndFillWithData(hdfsURI, "file", i, "This is test line."); filesCreated[i] = ignoredFile.f0; } // wait until the monitoring thread exits t.join(); Assert.assertArrayEquals(filesToBeRead.toArray(), context.getSeenFiles().toArray()); // finally delete the files created for the test. hdfs.delete(bootstrap.f0, false); for (org.apache.hadoop.fs.Path path: filesCreated) { hdfs.delete(path, false); } } @Test public void testFunctionRestore() throws Exception { org.apache.hadoop.fs.Path path = null; long fileModTime = Long.MIN_VALUE; for (int i = 0; i < 1; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(hdfsURI, "file", i, "This is test line."); path = file.f0; fileModTime = hdfs.getFileStatus(file.f0).getModificationTime(); } TextInputFormat format = new TextInputFormat(new Path(hdfsURI)); final ContinuousFileMonitoringFunction<String> monitoringFunction = new ContinuousFileMonitoringFunction<>(format, FileProcessingMode.PROCESS_CONTINUOUSLY, 1, INTERVAL); StreamSource<TimestampedFileInputSplit, ContinuousFileMonitoringFunction<String>> src = new StreamSource<>(monitoringFunction); final AbstractStreamOperatorTestHarness<TimestampedFileInputSplit> testHarness = new AbstractStreamOperatorTestHarness<>(src, 1, 1, 0); testHarness.open(); final Throwable[] error = new Throwable[1]; final OneShotLatch latch = new OneShotLatch(); // run the source asynchronously Thread runner = new Thread() { @Override public void run() { try { monitoringFunction.run(new DummySourceContext() { @Override public void collect(TimestampedFileInputSplit element) { latch.trigger(); } }); } catch (Throwable t) { t.printStackTrace(); error[0] = t; } } }; runner.start(); if (!latch.isTriggered()) { latch.await(); } OperatorStateHandles snapshot = testHarness.snapshot(0, 0); monitoringFunction.cancel(); runner.join(); testHarness.close(); final ContinuousFileMonitoringFunction<String> monitoringFunctionCopy = new ContinuousFileMonitoringFunction<>(format, FileProcessingMode.PROCESS_CONTINUOUSLY, 1, INTERVAL); StreamSource<TimestampedFileInputSplit, ContinuousFileMonitoringFunction<String>> srcCopy = new StreamSource<>(monitoringFunctionCopy); AbstractStreamOperatorTestHarness<TimestampedFileInputSplit> testHarnessCopy = new AbstractStreamOperatorTestHarness<>(srcCopy, 1, 1, 0); testHarnessCopy.initializeState(snapshot); testHarnessCopy.open(); Assert.assertNull(error[0]); Assert.assertEquals(fileModTime, monitoringFunctionCopy.getGlobalModificationTime()); hdfs.delete(path, false); } @Test public void testProcessContinuously() throws Exception { final OneShotLatch latch = new OneShotLatch(); // create a single file in the directory Tuple2<org.apache.hadoop.fs.Path, String> bootstrap = createFileAndFillWithData(hdfsURI, "file", NO_OF_FILES + 1, "This is test line."); Assert.assertTrue(hdfs.exists(bootstrap.f0)); final Set<String> filesToBeRead = new TreeSet<>(); filesToBeRead.add(bootstrap.f0.getName()); TextInputFormat format = new TextInputFormat(new Path(hdfsURI)); format.setFilesFilter(FilePathFilter.createDefaultFilter()); final ContinuousFileMonitoringFunction<String> monitoringFunction = new ContinuousFileMonitoringFunction<>(format, FileProcessingMode.PROCESS_CONTINUOUSLY, 1, INTERVAL); final int totalNoOfFilesToBeRead = NO_OF_FILES + 1; // 1 for the bootstrap + NO_OF_FILES final FileVerifyingSourceContext context = new FileVerifyingSourceContext(latch, monitoringFunction, 1, totalNoOfFilesToBeRead); final Thread t = new Thread() { @Override public void run() { try { monitoringFunction.open(new Configuration()); monitoringFunction.run(context); } catch (Exception e) { Assert.fail(e.getMessage()); } } }; t.start(); if (!latch.isTriggered()) { latch.await(); } // create some additional files that will be processed in the case of PROCESS_CONTINUOUSLY final org.apache.hadoop.fs.Path[] filesCreated = new org.apache.hadoop.fs.Path[NO_OF_FILES]; for (int i = 0; i < NO_OF_FILES; i++) { Tuple2<org.apache.hadoop.fs.Path, String> file = createFileAndFillWithData(hdfsURI, "file", i, "This is test line."); filesCreated[i] = file.f0; filesToBeRead.add(file.f0.getName()); } // wait until the monitoring thread exits t.join(); Assert.assertArrayEquals(filesToBeRead.toArray(), context.getSeenFiles().toArray()); // finally delete the files created for the test. hdfs.delete(bootstrap.f0, false); for (org.apache.hadoop.fs.Path path: filesCreated) { hdfs.delete(path, false); } } /////////// Source Contexts Used by the tests ///////////////// private static class FileVerifyingSourceContext extends DummySourceContext { private final ContinuousFileMonitoringFunction src; private final OneShotLatch latch; private final Set<String> seenFiles; private int elementsBeforeNotifying = -1; private int elementsBeforeCanceling = -1; FileVerifyingSourceContext(OneShotLatch latch, ContinuousFileMonitoringFunction src) { this(latch, src, -1, -1); } FileVerifyingSourceContext(OneShotLatch latch, ContinuousFileMonitoringFunction src, int elementsBeforeNotifying, int elementsBeforeCanceling) { this.latch = latch; this.seenFiles = new TreeSet<>(); this.src = src; this.elementsBeforeNotifying = elementsBeforeNotifying; this.elementsBeforeCanceling = elementsBeforeCanceling; } Set<String> getSeenFiles() { return this.seenFiles; } @Override public void collect(TimestampedFileInputSplit element) { String seenFileName = element.getPath().getName(); this.seenFiles.add(seenFileName); if (seenFiles.size() == elementsBeforeNotifying && !latch.isTriggered()) { latch.trigger(); } if (seenFiles.size() == elementsBeforeCanceling) { src.cancel(); } } @Override public void close() { // the context was terminated so trigger so // that all threads that were waiting for this // are un-blocked. if (!latch.isTriggered()) { latch.trigger(); } src.cancel(); } } private static class ModTimeVerifyingSourceContext extends DummySourceContext { final long[] expectedModificationTimes; int splitCounter; long lastSeenModTime; ModTimeVerifyingSourceContext(long[] modTimes) { this.expectedModificationTimes = modTimes; this.splitCounter = 0; this.lastSeenModTime = Long.MIN_VALUE; } int getCounter() { return splitCounter; } @Override public void collect(TimestampedFileInputSplit element) { try { long modTime = hdfs.getFileStatus(new org.apache.hadoop.fs.Path(element.getPath().getPath())).getModificationTime(); Assert.assertTrue(modTime >= lastSeenModTime); Assert.assertEquals(expectedModificationTimes[splitCounter], modTime); lastSeenModTime = modTime; splitCounter++; } catch (IOException e) { Assert.fail(e.getMessage()); } } } private abstract static class DummySourceContext implements SourceFunction.SourceContext<TimestampedFileInputSplit> { private final Object lock = new Object(); @Override public void collectWithTimestamp(TimestampedFileInputSplit element, long timestamp) { } @Override public void emitWatermark(Watermark mark) { } @Override public Object getCheckpointLock() { return lock; } @Override public void close() { } } ///////// Auxiliary Methods ///////////// private static int getLineNo(String line) { String[] tkns = line.split("\\s"); Assert.assertEquals(6, tkns.length); return Integer.parseInt(tkns[tkns.length - 1]); } /** * Create a file with pre-determined String format of the form: * {@code fileIdx +": "+ sampleLine +" "+ lineNo}. * */ private static Tuple2<org.apache.hadoop.fs.Path, String> createFileAndFillWithData( String base, String fileName, int fileIdx, String sampleLine) throws IOException { assert (hdfs != null); final String fileRandSuffix = UUID.randomUUID().toString(); org.apache.hadoop.fs.Path file = new org.apache.hadoop.fs.Path(base + "/" + fileName + fileRandSuffix); Assert.assertFalse(hdfs.exists(file)); org.apache.hadoop.fs.Path tmp = new org.apache.hadoop.fs.Path(base + "/." + fileName + fileRandSuffix); FSDataOutputStream stream = hdfs.create(tmp); StringBuilder str = new StringBuilder(); for (int i = 0; i < LINES_PER_FILE; i++) { String line = fileIdx +": "+ sampleLine + " " + i +"\n"; str.append(line); stream.write(line.getBytes()); } stream.close(); hdfs.rename(tmp, file); Assert.assertTrue("No result file present", hdfs.exists(file)); return new Tuple2<>(file, str.toString()); } }
package cn.featherfly.hammer.sqldb.tpl.freemarker; import cn.featherfly.hammer.sqldb.tpl.SqlDbTemplateProcessEnv; import cn.featherfly.hammer.sqldb.tpl.freemarker.directive.AndTemplateDirectiveModel; import cn.featherfly.hammer.sqldb.tpl.freemarker.directive.IncludeDirectiveModel; import cn.featherfly.hammer.sqldb.tpl.freemarker.directive.OrTemplateDirectiveModel; import cn.featherfly.hammer.sqldb.tpl.freemarker.directive.PropertiesMappingDirectiveModel; import cn.featherfly.hammer.sqldb.tpl.freemarker.directive.WhereTemplateDirectiveModel; import cn.featherfly.hammer.sqldb.tpl.freemarker.directive.WrapTemplateDirectiveModel; import cn.featherfly.hammer.sqldb.tpl.freemarker.method.WrapMethodModel; import cn.featherfly.hammer.tpl.freemarker.FreemarkerDirective; import cn.featherfly.hammer.tpl.freemarker.FreemarkerMethod; /** * <p> * JdbcFreemarkerTemplateEnv * </p> * * @author zhongj */ public class SqldbFreemarkerTemplateProcessEnv extends SqlDbTemplateProcessEnv<FreemarkerDirective, FreemarkerMethod> { /** */ public SqldbFreemarkerTemplateProcessEnv() { } /** * {@inheritDoc} */ @Override protected FreemarkerDirective createWhereDirective() { return new WhereTemplateDirectiveModel(); } /** * {@inheritDoc} */ @Override protected FreemarkerDirective createAndDirective() { return new AndTemplateDirectiveModel(manager); } /** * {@inheritDoc} */ @Override protected FreemarkerDirective createOrDirective() { return new OrTemplateDirectiveModel(manager); } /** * {@inheritDoc} */ @Override protected FreemarkerDirective createPropertiesDirective() { return new PropertiesMappingDirectiveModel(mappingFactory, resultType); } /** * {@inheritDoc} */ @Override protected FreemarkerDirective createIncludeDirective() { return new IncludeDirectiveModel(configFactory); } /** * {@inheritDoc} */ @Override protected FreemarkerDirective createWrapDirective() { return new WrapTemplateDirectiveModel(dialect); } /** * {@inheritDoc} */ @Override protected FreemarkerMethod createWrapMethode() { return new WrapMethodModel(dialect); } }
/* * #%L * ImgLib2: a general-purpose, multidimensional image processing library. * %% * Copyright (C) 2009 - 2022 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld, * John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke, * Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner, * Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert, * Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin, * Jean-Yves Tinevez and Michael Zinsmaier. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * 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 HOLDERS 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. * #L% */ package net.imglib2.img; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import net.imglib2.Cursor; import net.imglib2.Interval; import net.imglib2.RandomAccess; import net.imglib2.img.array.ArrayImgFactory; import net.imglib2.type.logic.BitType; import net.imglib2.type.numeric.integer.IntType; import net.imglib2.util.IntervalIndexer; import net.imglib2.view.Views; import net.imglib2.view.iteration.SubIntervalIterable; import org.junit.Test; public abstract class AbstractSubIntervalIterableCursorTest< T extends Img< IntType > & SubIntervalIterable< IntType > > { /** * dimensions of the tested Image. dimension 0 of all should be at least 18 */ protected long[] dimensions; protected int[] intData; /** Img to test on */ protected T img; /** Interval which is optimizable with a special SubIntervalCursor */ protected Interval intervalFast; /** Interval which is not optimizable */ protected Interval intervalShifted; /* * Cursor */ @Test public void testIterationFast() { Cursor< IntType > cursor = Views.interval( img, intervalFast ).cursor(); testCursorIteration( cursor, intervalFast ); } @Test public void testIterationShifted() { Cursor< IntType > cursor = Views.interval( img, intervalShifted ).cursor(); testCursorIteration( cursor, intervalShifted ); } @Test public void testJumpFwdFast() { Cursor< IntType > cursor = Views.interval( img, intervalFast ).cursor(); testCursorJumpFwd( cursor, intervalFast ); } @Test public void testJumpFwdShifted() { Cursor< IntType > cursor = Views.interval( img, intervalShifted ).cursor(); testCursorJumpFwd( cursor, intervalShifted ); } /* * Localizing Cursor */ @Test public void testLocalizingIterationFast() { Cursor< IntType > cursor = Views.interval( img, intervalFast ).localizingCursor(); testCursorIteration( cursor, intervalFast ); } @Test public void testLocalizingIterationShifted() { Cursor< IntType > cursor = Views.interval( img, intervalShifted ).localizingCursor(); testCursorIteration( cursor, intervalShifted ); } @Test public void testLocalizingJumpFwdFast() { Cursor< IntType > cursor = Views.interval( img, intervalFast ).localizingCursor(); testCursorJumpFwd( cursor, intervalFast ); } @Test public void testLocalizingJumpFwdShifted() { Cursor< IntType > cursor = Views.interval( img, intervalShifted ).localizingCursor(); testCursorJumpFwd( cursor, intervalShifted ); } protected void testCursorIteration( Cursor< IntType > cursor, Interval i ) { long[] position = new long[ cursor.numDimensions() ]; long[] min = new long[ cursor.numDimensions() ]; i.min( min ); cursor.fwd(); cursor.localize( position ); cursor.reset(); int ctr = 0; long sum = 0; final RandomAccess< BitType > check = Views.translate( new ArrayImgFactory<>( new BitType() ).create( i ), min ).randomAccess(); while ( cursor.hasNext() ) { cursor.fwd(); cursor.localize( position ); check.setPosition( position ); assertFalse( check.get().get() ); check.get().set( true ); sum += cursor.get().get(); ctr++; } assertEquals( "wrong number of elements accessed.", getIntervalSize( i ), ctr ); assertEquals( "sum of elements incorrect.", sum, getSum( i ) ); } protected void testCursorJumpFwd( Cursor< IntType > cursor, Interval i ) { long[] position = new long[ cursor.numDimensions() ]; long[] ref = new long[ cursor.numDimensions() ]; i.min( ref ); ref[ 0 ] += 17; cursor.jumpFwd( 18 ); cursor.localize( position ); assertArrayEquals( "jumpFwd position incorrect.", ref, position ); } // HELPER protected final long getSum( Interval interval ) { long[] pos = new long[ interval.numDimensions() ]; long sum = 0; for ( int i = 0; i < intData.length; ++i ) { IntervalIndexer.indexToPosition( i, dimensions, pos ); boolean in = true; for ( int j = 0; j < pos.length; j++ ) { if ( pos[ j ] < interval.min( j ) || pos[ j ] > interval.max( j ) ) { in = false; break; } } if ( in ) { sum += intData[ i ]; } } return sum; } protected final long getIntervalSize( Interval interval ) { long size = interval.dimension( 0 ); for ( int i = 1; i < interval.numDimensions(); ++i ) { size *= interval.dimension( i ); } return size; } }
package org.owller.CubeWorld.Server.Threads; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.owller.CubeWorld.Entity.CubePlayer; import org.owller.CubeWorld.Logging.CubeLogger; import org.owller.CubeWorld.Owller; import org.owller.CubeWorld.Server.Network.Packet.CubePacket; import org.owller.CubeWorld.Server.Network.Packet.CubePacketType; import org.owller.CubeWorld.Server.Network.CubeSocketCloseReason; import org.owller.CubeWorld.Server.Network.CubeSocketManager; import org.owller.CubeWorld.Server.Network.Packet.Exceptions.InvalidPacketException; import org.owller.CubeWorld.Server.Network.Packet.Exceptions.InvalidPacketTypeException; public class CubeSocketThread extends CubeThread { private CubeSocketManager manager; public CubeSocketThread(CubeSocketManager manager) { this.manager = manager; } public CubeSocketManager getManager() {return this.manager;} public CubeLogger getLogger() {return this.manager.getServer().getServer().getLogger();} @Override public void run() { while(this.getManager() != null && this.getManager().getSocket() != null && this.getManager().getSocket().isConnected() && !this.getManager().getSocket().isInputShutdown()) { try { DataInputStream is = new DataInputStream(this.manager.getSocket().getInputStream()); getLogger().debug("Checking for Packets..."); byte id = is.readByte(); getLogger().debug("Client Sent byte: " + id); CubePacketType packetType = CubePacketType.getByID(id); CubePacket packet = packetType.decode(is); this.recievePacket(packet); } catch(IOException e) { getLogger().debug("Caught Exception: " + e.getMessage()); break; } catch (InvalidPacketTypeException e) { getLogger().debug("Caught Exception: " + e.getMessage()); break; } catch(InvalidPacketException e) { getLogger().debug("Caught Exception: " + e.getMessage()); break; } } if(this.manager != null) this.manager.closeSocket(CubeSocketCloseReason.LOST_CONNECTION); } public void recievePacket(CubePacket packet) throws InvalidPacketTypeException, InvalidPacketException { if(packet == null) return; getLogger().debug("Got: " + packet.toString()); //Start Packet Logic if(packet.getType().equals(CubePacketType.VERSION_EXCHANGE)) { //Client has Sent the version of their game this.getManager().setVersion(packet.getData().getByteArray()); //Check for Update Issues if(this.getManager().getClientVersion() == null || !this.getManager().getClientVersion().equals(Owller.SERVER_VERSION)) { this.sendPacket(CubePacket.getServerVersionPacket()); this.manager.closeSocket(CubeSocketCloseReason.OUTDATED); return; } //Check if Server is Full (MIGHT FIX LATER WITH OVERRIDE FOR ADMINS) if(this.getManager().getServer().getServer().isServerFull() && !this.getManager().isConnnected()) { this.sendPacket(CubePacket.makeServerFullPacket()); this.manager.closeSocket(CubeSocketCloseReason.SERVER_FULL); return; } if(this.getManager().isConnnected()) return; //Player is Trying to Join, let's get started. CubePlayer player = new CubePlayer(this.manager, this.getManager().getServer().getServer().getDefaultWorld()); CubePacket playerJoin = CubePacket.makePacket(CubePacketType.PLAYER_JOIN, player); this.sendPacket(playerJoin); this.sendPacket(CubePacket.makePacket(CubePacketType.MAP_SEED, player)); //TODO: Add Login messages, etc } } public boolean sendPacket(CubePacket packet) { try { this.trySendPacket(packet); return true; } catch (IOException e) {return false;} } public void trySendPacket(CubePacket packet) throws IOException { getLogger().debug("Sending: " + packet.toString()); DataOutputStream os = new DataOutputStream(this.manager.getSocket().getOutputStream()); getLogger().debug("Writing Packet... " + packet.getType().getName()); os.write(packet.getData().getByteArray()); getLogger().debug("Flushing Packet..."); os.flush(); getLogger().debug("Flushed!"); } }
/*- * Copyright (C) 2011, 2018 Oracle and/or its affiliates. All rights reserved. * * This file was distributed by Oracle as part of a version of Oracle NoSQL * Database made available at: * * http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html * * Please see the LICENSE file included in the top-level directory of the * appropriate version of Oracle NoSQL Database for a copy of the license and * additional information. */ package oracle.kv.impl.admin.client; import static java.util.concurrent.TimeUnit.SECONDS; import java.rmi.RemoteException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import oracle.kv.impl.admin.CommandServiceAPI; import oracle.kv.impl.rep.MasterRepNodeStats; import oracle.kv.impl.rep.RepNodeStatus; import oracle.kv.impl.topo.Datacenter; import oracle.kv.impl.topo.DatacenterId; import oracle.kv.impl.topo.RepGroupId; import oracle.kv.impl.topo.RepNodeId; import oracle.kv.impl.topo.Topology; import oracle.kv.impl.util.CommandParser; import oracle.kv.impl.util.JsonUtils; import oracle.kv.util.ErrorMessage; import oracle.kv.util.PingCollector; import oracle.kv.util.shell.Shell; import oracle.kv.util.shell.ShellCommand; import oracle.kv.util.shell.ShellCommandResult; import oracle.kv.util.shell.ShellException; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; /* * await-consistent command */ class AwaitCommand extends ShellCommand { /* Time to wait between pings */ private static final long WAIT_MS = 5000; /* Default is 5 seconds */ private static final long DEFAULT_REPLICA_DELAY_THRESHOLD_MILLIS = 5000; AwaitCommand() { super("await-consistent", 3); } @Override public String execute(String[] args, Shell shell) throws ShellException { return new AwaitCommandExecutor<String>() { @Override public String failureResult(String message) { return message; } @Override public String successResult(String message) { return message; } @Override public String timeoutResult(Map<String, ReplicaDelayInfo> waiting, Set<DatacenterId> zones, long thresholdMillis) { final StringBuilder sb = new StringBuilder(); sb.append("The ").append(zonesOrStore(zones.size())); sb.append(" did not become consistent " + "within the timeout period\n"); for (Entry<String, ReplicaDelayInfo> e : waiting.entrySet()) { sb.append(" ").append(e.getKey()); if (e.getValue() == null) { sb.append(" state is not known\n"); } else { final ReplicaDelayInfo ri = e.getValue(); ri.report(sb, thresholdMillis); } } return sb.toString(); } }.commonExecute(args, shell); } private abstract class AwaitCommandExecutor<T> implements Executor<T> { @Override public T commonExecute(String[] args, Shell shell) throws ShellException { final CommandShell cmd = (CommandShell) shell; final CommandServiceAPI cs = cmd.getAdmin(); int timeoutSec = -1; long thresholdMillis = DEFAULT_REPLICA_DELAY_THRESHOLD_MILLIS; final Set<DatacenterId> zones = new HashSet<>(); try { for (int i = 1; i < args.length; i++) { final String arg = args[i]; if ("-timeout".equals(arg)) { timeoutSec = parseUnsignedInt( Shell.nextArg(args, i++, AwaitCommand.this)); } else if ("-zn".equals(arg)) { zones.add( DatacenterId.parse( Shell.nextArg(args, i++, AwaitCommand.this))); } else if ("-znname".equals(arg)) { final String zoneName = Shell.nextArg(args, i++, AwaitCommand.this); zones.add( CommandUtils.getDatacenterId(zoneName, cs, AwaitCommand.this)); } else if ("-replica-delay-threshold".equals(arg)) { thresholdMillis = parseUnsignedInt(Shell.nextArg(args, i++, AwaitCommand.this)); } else { shell.unknownArgument(arg, AwaitCommand.this); } } if (timeoutSec < 0) { shell.requiredArg("-timeout", AwaitCommand.this); } final Map<String, ReplicaDelayInfo> waiting; try { waiting = waitForZones(cs.getTopology(), zones, timeoutSec, thresholdMillis); } catch (IllegalArgumentException iae) { return failureResult(iae.getMessage()); } catch (InterruptedException ex) { return failureResult("Unexpected interupt"); } if (waiting == null) { return successResult( "The " + zonesOrStore(zones.size()) + ((zones.size() > 1) ? " are" : " is") + " consistent"); } return timeoutResult(waiting, zones, thresholdMillis); } catch (RemoteException re) { cmd.noAdmin(re); } return null; /* Not reached */ } public abstract T timeoutResult(Map<String, ReplicaDelayInfo> waiting, Set<DatacenterId> zones, long thresholdMillis); public abstract T failureResult(String message); public abstract T successResult(String message); } @Override public ShellCommandResult executeJsonOutput(String[] args, Shell shell) throws ShellException { final ShellCommandResult scr = ShellCommandResult.getDefault("await consistency"); return new AwaitCommandExecutor<ShellCommandResult>() { @Override public ShellCommandResult failureResult(String message) { scr.setReturnCode(ErrorMessage.NOSQL_5100.getValue()); scr.setDescription(message); return scr; } @Override public ShellCommandResult successResult(String message) { scr.setDescription(message); return scr; } @Override public ShellCommandResult timeoutResult(Map<String, ReplicaDelayInfo> waiting, Set<DatacenterId> zones, long thresholdMillis) { scr.setReturnCode(ErrorMessage.NOSQL_5300.getValue()); scr.setDescription( "The " + zonesOrStore(zones.size()) + " did not become consistent within the timeout period"); final ObjectNode top = JsonUtils.createObjectNode(); final ArrayNode delayArray = top.putArray("replicaDelayInfos"); for (Entry<String, ReplicaDelayInfo> e : waiting.entrySet()) { final ObjectNode on = JsonUtils.createObjectNode(); on.put("replicaName", e.getKey()); if (e.getValue() != null) { final ReplicaDelayInfo ri = e.getValue(); on.put("replicaDelayMillis", ri.replicaDelayMillis); on.put("replicaCatchupSecs", ri.replicaCatchupTimeSecs); on.put("thresholdMillis", thresholdMillis); } delayArray.add(on); } scr.setReturnValue(top); return scr; } }.commonExecute(args, shell); } /** * Waits up to the timeout number of seconds for the RNs in the * specified zones to become consistent. If all of the RNs are consistent * null is returned. Otherwise, returns a map of RNs which are behind * when the timeout is reached. The map key is the name of the RN and the * value is a ReplicaDelayInfo instance containing replica delay * information for the node. If no information about a target node is * found, the value will be null; * * If the set of zones is empty, all of the zones in the store * are waited on. * * @param topo a topology * @param zones the set of zones to wait for * @param timeoutSec how long to wait * @param thresholdMillis replica delay threshold * @return the map of lagging nodes or null * @throws InterruptedException if the call is interrupted * @throws IllegalArgumentException if a specified zone is not found or * the store or specified zone(s) contained no nodes */ static Map<String, ReplicaDelayInfo> waitForZones(Topology topo, Set<DatacenterId> zones, int timeoutSec, long thresholdMillis) throws InterruptedException { /* If no zone is specified, then check all zones */ final Set<DatacenterId> zonesToCheck = zones.isEmpty() ? topo.getDatacenterMap().getAllIds() : zones; final Set<String> targetRNs = new HashSet<>(); /* Gather the RNs from each zone */ for (DatacenterId zoneId : zonesToCheck) { final Datacenter dc = topo.get(zoneId); if (dc == null) { throw new IllegalArgumentException("Unknown zone: " + zoneId); } for (RepNodeId rnId : topo.getRepNodeIds(zoneId)) { targetRNs.add(rnId.getFullName()); } } if (targetRNs.isEmpty()) { throw new IllegalArgumentException( "The " + zonesOrStore(zones.size()) + " does not contain any nodes"); } final long limitMs = System.currentTimeMillis() + SECONDS.toMillis(timeoutSec); while (true) { final Map<String, ReplicaDelayInfo> waiting = checkRNs(targetRNs, topo, thresholdMillis); if (waiting.isEmpty()) { return null; } /* * If waiting would put us over the timeout, return with the * failed nodes. */ if (System.currentTimeMillis() + WAIT_MS > limitMs) { return waiting; } Thread.sleep(WAIT_MS); } } /** * Checks whether the target replicas delays are under the threshold. * If a target replica is behind, its name and the number of milliseconds * it is behind is added to the waiting map. If all nodes are caught-up * the map will be empty. If no information about a target node is found, * its name will have a null value. * * @param targetRNs the set of RNs to check * @param topo a topology * @param thresholdMillis the threshold value to use in checking RN delay * @return a map of lagging replicas */ private static Map<String, ReplicaDelayInfo> checkRNs(Set<String> targetRNs, Topology topo, long thresholdMillis){ /* * Create a map with all of the target RNs, setting the value to * null. Entries are removed if the RN is found to be a master, * or its delay is under the threshold. If the delay is * over the threshold, the value is replaced by a ReplicaDelayInfo * containing the delay information for that node. */ final Map<String, ReplicaDelayInfo> waiting = new HashMap<>(targetRNs.size()); for (String rnId : targetRNs) { waiting.put(rnId, null); } /* * For each group, find the master's stats for its nodes. */ PingCollector collector = new PingCollector(topo); for (RepGroupId rgId : topo.getRepGroupIds()) { /* * Get the RN status for each node in the group. Find the master * and remove it from waiting and use its stats to check for delays. */ MasterRepNodeStats masterStats = null; final Map<RepNodeId, RepNodeStatus> statusMap = collector.getRepNodeStatus(rgId); for (Entry<RepNodeId, RepNodeStatus> e : statusMap.entrySet()) { final RepNodeStatus rns = e.getValue(); if ((rns != null) && rns.getReplicationState().isMaster()) { waiting.remove(e.getKey().getFullName()); masterStats = rns.getMasterRepNodeStats(); break; } } /* The master's stats for this group was not found */ if (masterStats == null) { continue; } final Map<String, Long> delayMap = masterStats.getReplicaDelayMillisMap(); for (Entry<String, Long> e : delayMap.entrySet()) { final String replicaName = e.getKey(); final Long delayMillis = e.getValue(); /* Null, we dont know */ if (delayMillis == null) { continue; } if (delayMillis > thresholdMillis) { /* Catchup can be null */ final Long catchupTimeSecs = masterStats.getReplicaCatchupTimeSecs(replicaName); waiting.put(replicaName, new ReplicaDelayInfo(delayMillis, catchupTimeSecs)); } else { waiting.remove(replicaName); } } } return waiting; } private static String zonesOrStore(int n) { return (n == 0) ? "store" : "specified " + ((n == 1) ? "zone" : "zones"); } @Override protected String getCommandSyntax() { return "await-consistent -timeout <timeout-secs> " + "[-zn <id> | -znname <name>]... " + "[-replica-delay-threshold <time-millis>] " + CommandParser.getJsonUsage(); } @Override public String getCommandDescription() { return "Waits for up to the specified number of seconds for" + eolt + "the replicas in one or more zones, or in the entire" + eolt + "store, to catch up with the masters in their associated" + eolt + "shards. Prints information about whether consistency" + eolt + "was achieved or, if not, details about which nodes" + eolt + "failed to become consistent."; } static class ReplicaDelayInfo { final Long replicaDelayMillis; final Long replicaCatchupTimeSecs; private ReplicaDelayInfo(Long replicaDelayMillis, Long replicaCatchupTimeSecs) { assert replicaDelayMillis != null && replicaDelayMillis > 0; this.replicaDelayMillis = replicaDelayMillis; this.replicaCatchupTimeSecs = replicaCatchupTimeSecs; } @Override public String toString() { return "ReplicaDelayInfo[" + "replicaDelayMillis=" + replicaDelayMillis + " replicaCatchupTimeSecs=" + replicaCatchupTimeSecs + "]"; } private StringBuilder report(StringBuilder sb, long thresholdMillis) { sb.append(" is ").append(replicaDelayMillis); sb.append(" milliseconds behind"); if (replicaCatchupTimeSecs == null) { sb.append(", time to catchup is unknown"); } else if (replicaCatchupTimeSecs == Long.MAX_VALUE) { sb.append(" and is not catching up"); } else if (replicaCatchupTimeSecs < 0) { sb.append(" and is falling further behind"); } else { /* * If catching up, adjust the time to reflect the fact that * we are waiting to get under the threshold, not completely * caught up. */ final long adjustedCatchup = replicaDelayMillis > thresholdMillis ? (long)(replicaCatchupTimeSecs * (float)(replicaDelayMillis - thresholdMillis) / replicaDelayMillis) : 1; sb.append(", expected to catchup in "); sb.append(adjustedCatchup).append(" second"); if (adjustedCatchup > 1) { sb.append("s"); } } sb.append("\n"); return sb; } } }
/* * Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.apigateway.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.apigateway.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetStagesResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetStagesResultJsonUnmarshaller implements Unmarshaller<GetStagesResult, JsonUnmarshallerContext> { public GetStagesResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetStagesResult getStagesResult = new GetStagesResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return getStagesResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("item", targetDepth)) { context.nextToken(); getStagesResult.setItem(new ListUnmarshaller<Stage>(StageJsonUnmarshaller.getInstance()).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return getStagesResult; } private static GetStagesResultJsonUnmarshaller instance; public static GetStagesResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetStagesResultJsonUnmarshaller(); return instance; } }
package com.ctl.as.domain.geo.types; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import com.ctl.as.domain.geo.v2.types.GeoPointSource; /** * <p>Java class for GeoPoint complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="GeoPoint"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Source" type="{http://geo.domain.as.ctl.com/v2/Types}GeoPointSource" minOccurs="0"/> * &lt;element name="Latitude" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/> * &lt;element name="Longitude" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/> * &lt;element name="CoordinateLevel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Accuracy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Elevation" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/> * &lt;element name="Horizontal" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/> * &lt;element name="Vertical" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GeoPoint", propOrder = { "source", "latitude", "longitude", "coordinateLevel", "accuracy", "elevation", "horizontal", "vertical" }) public class GeoPoint { @XmlElement(name = "Source") @XmlSchemaType(name = "string") protected GeoPointSource source; @XmlElement(name = "Latitude") protected Double latitude; @XmlElement(name = "Longitude") protected Double longitude; @XmlElementRef(name = "CoordinateLevel", namespace = "http://geo.domain.as.ctl.com/Types", type = JAXBElement.class, required = false) protected JAXBElement<String> coordinateLevel; @XmlElementRef(name = "Accuracy", namespace = "http://geo.domain.as.ctl.com/Types", type = JAXBElement.class, required = false) protected JAXBElement<String> accuracy; @XmlElement(name = "Elevation") protected Double elevation; @XmlElement(name = "Horizontal") protected Double horizontal; @XmlElement(name = "Vertical") protected Double vertical; /** * Gets the value of the source property. * * @return * possible object is * {@link GeoPointSource } * */ public GeoPointSource getSource() { return source; } /** * Sets the value of the source property. * * @param value * allowed object is * {@link GeoPointSource } * */ public void setSource(GeoPointSource value) { this.source = value; } /** * Gets the value of the latitude property. * * @return * possible object is * {@link Double } * */ public Double getLatitude() { return latitude; } /** * Sets the value of the latitude property. * * @param value * allowed object is * {@link Double } * */ public void setLatitude(Double value) { this.latitude = value; } /** * Gets the value of the longitude property. * * @return * possible object is * {@link Double } * */ public Double getLongitude() { return longitude; } /** * Sets the value of the longitude property. * * @param value * allowed object is * {@link Double } * */ public void setLongitude(Double value) { this.longitude = value; } /** * Gets the value of the coordinateLevel property. * * @return * possible object is * {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getCoordinateLevel() { return coordinateLevel; } /** * Sets the value of the coordinateLevel property. * * @param value * allowed object is * {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >} * */ public void setCoordinateLevel(JAXBElement<String> value) { this.coordinateLevel = value; } /** * Gets the value of the accuracy property. * * @return * possible object is * {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getAccuracy() { return accuracy; } /** * Sets the value of the accuracy property. * * @param value * allowed object is * {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >} * */ public void setAccuracy(JAXBElement<String> value) { this.accuracy = value; } /** * Gets the value of the elevation property. * * @return * possible object is * {@link Double } * */ public Double getElevation() { return elevation; } /** * Sets the value of the elevation property. * * @param value * allowed object is * {@link Double } * */ public void setElevation(Double value) { this.elevation = value; } /** * Gets the value of the horizontal property. * * @return * possible object is * {@link Double } * */ public Double getHorizontal() { return horizontal; } /** * Sets the value of the horizontal property. * * @param value * allowed object is * {@link Double } * */ public void setHorizontal(Double value) { this.horizontal = value; } /** * Gets the value of the vertical property. * * @return * possible object is * {@link Double } * */ public Double getVertical() { return vertical; } /** * Sets the value of the vertical property. * * @param value * allowed object is * {@link Double } * */ public void setVertical(Double value) { this.vertical = value; } }
/******************************************************************************* * Copyright 2017 Capital One Services, LLC and Bitwise, 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. *******************************************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.05.17 at 01:02:05 PM IST // package hydrograph.ui.common.component.config; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the hydrograph.ui.common.component.config package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: hydrograph.ui.common.component.config * */ public ObjectFactory() { } /** * Create an instance of {@link Config } * */ public Config createConfig() { return new Config(); } /** * Create an instance of {@link Component } * */ public Component createComponent() { return new Component(); } /** * Create an instance of {@link TypeInfo } * */ public TypeInfo createTypeInfo() { return new TypeInfo(); } /** * Create an instance of {@link PortInfo } * */ public PortInfo createPortInfo() { return new PortInfo(); } /** * Create an instance of {@link PortSpecification } * */ public PortSpecification createPortSpecification() { return new PortSpecification(); } /** * Create an instance of {@link Operations } * */ public Operations createOperations() { return new Operations(); } /** * Create an instance of {@link Policy } * */ public Policy createPolicy() { return new Policy(); } /** * Create an instance of {@link Property } * */ public Property createProperty() { return new Property(); } /** * Create an instance of {@link IOPort } * */ public IOPort createIOPort() { return new IOPort(); } }
/* * 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.el.parser; import javax.el.ELException; import org.apache.el.lang.EvaluationContext; /** * @author Jacob Hookom [jacob@hookom.net] * @version $Id$ */ public class BooleanNode extends SimpleNode { /** * @param i */ public BooleanNode(int i) { super(i); } @Override public Class<?> getType(EvaluationContext ctx) throws ELException { return Boolean.class; } }
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.customtabs.content; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.stubbing.Answer; import org.robolectric.annotation.Config; import org.chromium.base.task.TaskTraits; import org.chromium.base.task.test.ShadowPostTask; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController.FinishHandler; import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController.FinishReason; import org.chromium.chrome.browser.customtabs.shadows.ShadowExternalNavigationDelegateImpl; import org.chromium.chrome.browser.flags.ActivityType; import org.chromium.chrome.browser.tab.Tab; import org.chromium.testing.local.LocalRobolectricTestRunner; import org.chromium.url.GURL; /** * Unit tests for {@link CustomTabActivityNavigationController}. * * {@link CustomTabActivityNavigationController#navigate} is tested in integration with other * classes in {@link CustomTabActivityUrlLoadingTest}. */ @RunWith(LocalRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = { ShadowExternalNavigationDelegateImpl.class, ShadowPostTask.class}) public class CustomTabActivityNavigationControllerTest { @Rule public final CustomTabActivityContentTestEnvironment env = new CustomTabActivityContentTestEnvironment(); private CustomTabActivityNavigationController mNavigationController; @Mock CustomTabActivityTabController mTabController; @Mock FinishHandler mFinishHandler; @Before public void setUp() { ShadowPostTask.setTestImpl(new ShadowPostTask.TestImpl() { @Override public void postDelayedTask(TaskTraits taskTraits, Runnable task, long delay) {} }); MockitoAnnotations.initMocks(this); mNavigationController = env.createNavigationController(mTabController); mNavigationController.setFinishHandler(mFinishHandler); Tab tab = env.prepareTab(); when(tab.getUrl()).thenReturn(new GURL("")); // avoid DomDistillerUrlUtils going to native. env.tabProvider.setInitialTab(tab, TabCreationMode.DEFAULT); } @Test public void finishes_IfBackNavigationClosesTheOnlyTab() { when(mTabController.onlyOneTabRemaining()).thenReturn(true); mNavigationController.navigateOnBack(); verify(mFinishHandler).onFinish(eq(FinishReason.USER_NAVIGATION)); } @Test public void doesntFinish_IfBackNavigationReplacesTabWithPreviousOne() { doAnswer((Answer<Void>) invocation -> { env.tabProvider.swapTab(env.prepareTab()); return null; }).when(mTabController).closeTab(); mNavigationController.navigateOnBack(); verify(mFinishHandler, never()).onFinish(anyInt()); } @Test public void startsReparenting_WhenOpenInBrowserCalled_AndChromeCanHandleIntent() { ShadowExternalNavigationDelegateImpl.setWillChromeHandleIntent(true); mNavigationController.openCurrentUrlInBrowser(false); verify(env.activity, never()).startActivity(any()); verify(mTabController).detachAndStartReparenting(any(), any(), any()); } @Test public void finishes_whenDoneReparenting() { ShadowExternalNavigationDelegateImpl.setWillChromeHandleIntent(true); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); doNothing().when(mTabController).detachAndStartReparenting(any(), any(), captor.capture()); mNavigationController.openCurrentUrlInBrowser(false); verify(mFinishHandler, never()).onFinish(anyInt()); captor.getValue().run(); verify(mFinishHandler).onFinish(FinishReason.REPARENTING); } @Test public void startsNewActivity_WhenOpenInBrowserCalled_AndChromeCanNotHandleIntent() { ShadowExternalNavigationDelegateImpl.setWillChromeHandleIntent(false); mNavigationController.openCurrentUrlInBrowser(false); verify(mTabController, never()).detachAndStartReparenting(any(), any(), any()); verify(env.activity).startActivity(any(), any()); } @Test public void startsNewActivity_WhenOpenInBrowserCalled_AndChromeCanHandleIntent_AndIsTwa() { ShadowExternalNavigationDelegateImpl.setWillChromeHandleIntent(true); when(env.intentDataProvider.getActivityType()) .thenReturn(ActivityType.TRUSTED_WEB_ACTIVITY); mNavigationController.openCurrentUrlInBrowser(false); verify(mTabController, never()).detachAndStartReparenting(any(), any(), any()); verify(env.activity).startActivity(any(), any()); } @After public void tearDown() { ShadowPostTask.reset(); } }
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.internal.verification; import org.mockito.internal.verification.api.VerificationData; import org.mockito.verification.VerificationMode; public class DummyVerificationMode implements VerificationMode { public void verify(VerificationData data) { } }
package com.xc.luckysheet; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.PlatformTransactionManager; /** * @author cr */ @Slf4j @EnableScheduling @Configuration @SpringBootApplication(scanBasePackages = "com.xc",exclude={MongoAutoConfiguration.class}) public class WebApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); log.info("webtest server is started"); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(WebApplication.class); } @Bean public Object testBean(@Qualifier("postgreTxManager") PlatformTransactionManager platformTransactionManager){ //启动类中添加如下方法,Debug测试,能知道自动注入的是 PlatformTransactionManager 接口的哪个实现类 System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName()); return new Object(); } }
package com.example.springmvc.model; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.GenericGenerators; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Registry { @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid2") private String id; private String name; private String address; public Registry() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
/* * Copyright 2016-2019 Fraunhofer AISEC * * 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. * * $$\ $$\ $$\ $$\ * $$ | $$ |\__| $$ | * $$$$$$$\ $$ | $$$$$$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$\ $$$$$$\ * $$ _____|$$ |$$ __$$\ $$ | $$ |$$ __$$ |$$ |\_$$ _| $$ __$$\ $$ __$$\ * $$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ | $$ | $$ / $$ |$$ | \__| * $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ | * \$$$$$$\ $$ |\$$$$$ |\$$$$$ |\$$$$$$ |$$ | \$$$ |\$$$$$ |$$ | * \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__| * * This file is part of Clouditor Community Edition. */ package io.clouditor.discovery; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.ObjectMapper; import io.clouditor.assurance.Rule; import io.clouditor.rest.ObjectMapperResolver; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class represents a Scanner, which discovers a certain asset type. The properties of the * asset will then later queried by a {@link Rule}. * * @param <C> The API type. * @param <T> The discovered object type. */ public abstract class Scanner<C, T> { protected static final Logger LOGGER = LoggerFactory.getLogger(Scanner.class); protected static final ObjectMapper MAPPER = new ObjectMapper(); static { ObjectMapperResolver.configureObjectMapper(MAPPER); } protected ScannerPostProcessor<?, T> postProcessor; private final Supplier<C> supplier; private final Function<T, String> idGenerator; private final Function<T, String> nameGenerator; protected C api; private boolean initialized = false; public Scanner( Supplier<C> supplier, Function<T, String> idGenerator, Function<T, String> nameGenerator) { this.supplier = supplier; this.idGenerator = idGenerator; this.nameGenerator = nameGenerator; } public void init() throws IOException { if (this.supplier != null) { this.api = supplier.get(); } } protected abstract List<T> list() throws ScanException; @JsonIgnore public DiscoveryResult scan(String scanId) { var result = new DiscoveryResult(scanId); try { // initialize the scanner, if not done already if (!this.initialized) { this.init(); // we need to set that here and not within init() because a lot of scanners overwrite // init() this.initialized = true; } var assets = new HashMap<String, Asset>(); LOGGER.info("Scanner {} is now scanning", this.getId()); for (var object : list()) { var asset = transform(object); assets.put(asset.getId(), asset); } result.setDiscoveredAssets(assets); } catch (Exception e) { // it is important to catch all exceptions here, since that means a scan interval is failed // however, we might be able to recover in the next interval, so we do NOT want our future to // get cancelled LOGGER.info("Exception during scan", e); // mark the scan result as a failure result.setFailed(true); result.setError(e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName()); } return result; } protected String getIdForObject(T object) { return this.idGenerator.apply(object); } protected String getNameForObject(T object) { return this.nameGenerator.apply(object); } public String getId() { return this.getClass().getName(); } /** * Transforms an object to an {@link Asset}. * * @param object the object to transform * @return the asset. */ protected Asset transform(T object) throws ScanException { Asset asset = new Asset(); if (postProcessor != null) { asset.setProperties(MAPPER.convertValue(postProcessor.handle(object), AssetProperties.class)); } else { asset.setProperties(MAPPER.convertValue(object, AssetProperties.class)); } // TODO: not really the most efficient way to do this. better would be if the Scanner would have // access to the Scan object var info = this.getClass().getAnnotation(ScannerInfo.class); if (info != null) { asset.setType(info.assetType()); } else { asset.setType(object.getClass().getSimpleName()); } asset.setId(this.idGenerator.apply(object)); asset.setName(this.nameGenerator.apply(object)); return asset; } // TODO: just for mocking debug public void setApi(C api) { this.api = api; } public void setInitialized(boolean initialized) { this.initialized = initialized; } public boolean getInitialized() { return initialized; } public ScannerInfo getInfo() { return this.getClass().getAnnotation(ScannerInfo.class); } }
/* * Copyright 2018 Jean-Francois Arcand * * 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.atmosphere.cpr; import org.atmosphere.container.BlockingIOCometSupport; import org.atmosphere.handler.AbstractReflectorAtmosphereHandler; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import static org.mockito.Mockito.mock; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; public class AtmosphereRequestTest { private AtmosphereFramework framework; @BeforeMethod public void create() throws Throwable { framework = new AtmosphereFramework(); framework.setAsyncSupport(new BlockingIOCometSupport(framework.getAtmosphereConfig())); framework.init(new ServletConfig() { @Override public String getServletName() { return "void"; } @Override public ServletContext getServletContext() { return mock(ServletContext.class); } @Override public String getInitParameter(String name) { return null; } @Override public Enumeration<String> getInitParameterNames() { return null; } }); } @AfterMethod public void stop() { framework.destroy(); } @Test public void testQueryStringAsRequest() throws IOException, ServletException { framework.addAtmosphereHandler("/a", new AbstractReflectorAtmosphereHandler() { @Override public void onRequest(AtmosphereResource resource) throws IOException { } @Override public void destroy() { } }); Map<String, String[]> qs = new HashMap<String, String[]>(); qs.put("Content-Type", new String[]{"application/xml"}); qs.put("X-Atmosphere-Transport", new String[]{"long-polling"}); AtmosphereRequest request = new AtmosphereRequestImpl.Builder().queryStrings(qs).pathInfo("/a").build(); final AtomicReference<String> e = new AtomicReference<String>(); final AtomicReference<String> e2 = new AtomicReference<String>(); framework.interceptor(new AtmosphereInterceptor() { @Override public void configure(AtmosphereConfig config) { } @Override public Action inspect(AtmosphereResource r) { e.set(r.getRequest().getContentType()); e2.set(r.transport().name()); return Action.CANCELLED; } @Override public void postInspect(AtmosphereResource r) { } @Override public void destroy() { } }); framework.doCometSupport(request, AtmosphereResponseImpl.newInstance()); assertEquals(e.get(), "application/xml"); assertEquals(e2.get().toLowerCase(), "long_polling"); } @Test public void testQueryStringBuilder() throws IOException, ServletException { framework.addAtmosphereHandler("/a", new AbstractReflectorAtmosphereHandler() { @Override public void onRequest(AtmosphereResource resource) throws IOException { } @Override public void destroy() { } }); AtmosphereRequest request = new AtmosphereRequestImpl.Builder().queryString("a=b").pathInfo("/a").build(); final AtomicReference<String> e = new AtomicReference<String>(); framework.interceptor(new AtmosphereInterceptor() { @Override public void configure(AtmosphereConfig config) { } @Override public Action inspect(AtmosphereResource r) { e.set(r.getRequest().getQueryString()); return Action.CANCELLED; } @Override public void postInspect(AtmosphereResource r) { } @Override public void destroy() { } }); framework.doCometSupport(request, AtmosphereResponseImpl.newInstance()); assertEquals(e.get(), "a=b"); } @Test public void testNormalQueryStringBuilder() throws IOException, ServletException { framework.addAtmosphereHandler("/a", new AbstractReflectorAtmosphereHandler() { @Override public void onRequest(AtmosphereResource resource) throws IOException { } @Override public void destroy() { } }); AtmosphereRequest request = new AtmosphereRequestImpl.Builder().pathInfo("/a").build(); request.queryString("a=b"); final AtomicReference<String> e = new AtomicReference<String>(); framework.interceptor(new AtmosphereInterceptor() { @Override public void configure(AtmosphereConfig config) { } @Override public Action inspect(AtmosphereResource r) { e.set(r.getRequest().getQueryString()); return Action.CANCELLED; } @Override public void postInspect(AtmosphereResource r) { } @Override public void destroy() { } }); framework.doCometSupport(request, AtmosphereResponseImpl.newInstance()); assertEquals(e.get(), "a=b"); } @Test public void testStrinpQueryStringBuilder() throws IOException, ServletException { framework.addAtmosphereHandler("/a", new AbstractReflectorAtmosphereHandler() { @Override public void onRequest(AtmosphereResource resource) throws IOException { } @Override public void destroy() { } }); AtmosphereRequest request = new AtmosphereRequestImpl.Builder().pathInfo("/a").build(); request.queryString("a=b&X-Atmosphere-Transport=websocket"); final AtomicReference<String> e = new AtomicReference<String>(); framework.interceptor(new AtmosphereInterceptor() { @Override public void configure(AtmosphereConfig config) { } @Override public Action inspect(AtmosphereResource r) { e.set(r.getRequest().getQueryString()); return Action.CANCELLED; } @Override public void postInspect(AtmosphereResource r) { } @Override public void destroy() { } }); framework.doCometSupport(request, AtmosphereResponseImpl.newInstance()); assertEquals(e.get(), "a=b"); } @Test public void testEncodingOnPreSuspend() throws IOException, ServletException { final AtomicReference<AtmosphereResponse> e = new AtomicReference<AtmosphereResponse>(); framework.addAtmosphereHandler("/a", new AbstractReflectorAtmosphereHandler() { @Override public void onRequest(AtmosphereResource resource) throws IOException { resource.addEventListener(new AtmosphereResourceEventListenerAdapter() { @Override public void onPreSuspend(AtmosphereResourceEvent event) { AtmosphereResponse response = event.getResource().getResponse(); response.setCharacterEncoding("utf-8"); e.set(response); } }).suspend(10); } @Override public void destroy() { } }); AtmosphereRequest request = new AtmosphereRequestImpl.Builder().pathInfo("/a").build(); framework.doCometSupport(request, AtmosphereResponseImpl.newInstance().delegateToNativeResponse(false)); assertEquals(e.get().getCharacterEncoding(), "utf-8"); } @Test public void testRequestBodyString() throws IOException, ServletException { final AtomicReference<AtmosphereRequestImpl.Body> e = new AtomicReference<AtmosphereRequestImpl.Body>(); framework.addAtmosphereHandler("/a", new AbstractReflectorAtmosphereHandler() { @Override public void onRequest(AtmosphereResource resource) throws IOException { e.set(resource.getRequest().body()); } @Override public void destroy() { } }); AtmosphereRequest request = new AtmosphereRequestImpl.Builder().pathInfo("/a").body("test").build(); framework.doCometSupport(request, AtmosphereResponseImpl.newInstance().delegateToNativeResponse(false)); assertNotNull(e.get()); assertTrue(e.get().hasString()); assertFalse(e.get().hasBytes()); assertEquals(e.get().asString(), "test"); } @Test public void testRequestBodyBytes() throws IOException, ServletException { final AtomicReference<AtmosphereRequestImpl.Body> e = new AtomicReference<AtmosphereRequestImpl.Body>(); framework.addAtmosphereHandler("/a", new AbstractReflectorAtmosphereHandler() { @Override public void onRequest(AtmosphereResource resource) throws IOException { e.set(resource.getRequest().body()); } @Override public void destroy() { } }); AtmosphereRequest request = new AtmosphereRequestImpl.Builder().pathInfo("/a").body("test".getBytes()).build(); framework.doCometSupport(request, AtmosphereResponseImpl.newInstance().delegateToNativeResponse(false)); assertNotNull(e.get()); assertTrue(e.get().hasBytes()); assertFalse(e.get().hasString()); assertEquals(new String(e.get().asBytes()), "test"); } @Test public void testForceContentType() throws Exception { // a non-empty body AtmosphereRequest request = new AtmosphereRequestImpl.Builder().pathInfo("/a").body("test".getBytes()).build(); // default type for a non-empty body assertEquals(request.getContentType(), "text/plain"); // no body request = new AtmosphereRequestImpl.Builder().pathInfo("/a").build(); // default type for a non-empty type assertEquals(request.getContentType(), "text/plain"); // no content-type explicitly set request = new AtmosphereRequestImpl.Builder().pathInfo("/a").contentType(null).build(); // no content type assertNull(request.getContentType()); } }
import java.util.Scanner; /** * * @author swaroopksahu * @category Introduction * @since June 2020 * @version 1.0 * @see <a href="https://github.com/swaroopksahu">GitHub - swaroopksahu</a> * */ public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i = scan.nextInt(); Double d = scan.nextDouble(); String s = ""; while (scan.hasNext()) { s = s + scan.nextLine(); } System.out.println("String: " + s); System.out.println("Double: " + d); System.out.println("Int: " + i); } }
package com.hha.heinhtetaung.simplehabits.adapters; import android.content.Context; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewGroup; import com.hha.heinhtetaung.simplehabits.R; import com.hha.heinhtetaung.simplehabits.data.vo.CategoriesProgramVO; import com.hha.heinhtetaung.simplehabits.data.vo.ProgramVO; import com.hha.heinhtetaung.simplehabits.delegate.CategoriesProgramDelegate; import com.hha.heinhtetaung.simplehabits.viewholders.ItemCategoriesProgramViewHolder; /** * Created by E5 on 5/22/2018. */ public class CategoriesProgramAdapter extends BaseRecyclerAdapter<ItemCategoriesProgramViewHolder, ProgramVO> { private CategoriesProgramDelegate mDelegate; private CategoriesProgramVO mRootCategory; public CategoriesProgramAdapter(Context context, CategoriesProgramDelegate delegate) { super(context); mDelegate = delegate; } @NonNull @Override public ItemCategoriesProgramViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = mLayoutInflator.inflate(R.layout.item_healthy_mind, parent, false); return new ItemCategoriesProgramViewHolder(view, mDelegate); } @Override public void onBindViewHolder(ItemCategoriesProgramViewHolder holder, int position) { holder.setData(mData.get(position)); holder.setCategory(mRootCategory); } public void setCategory(CategoriesProgramVO category) { mRootCategory = category; } }
package org.openstreetmap.atlas.generator; import java.util.List; import org.apache.hadoop.mapred.lib.MultipleOutputFormat; import org.openstreetmap.atlas.generator.persistence.MultipleAtlasCountryStatisticsOutputFormat; import org.openstreetmap.atlas.generator.persistence.MultipleAtlasFeatureChangeOutput; import org.openstreetmap.atlas.generator.persistence.MultipleAtlasProtoOutputFormat; import org.openstreetmap.atlas.generator.persistence.MultipleAtlasStatisticsOutputFormat; import org.openstreetmap.atlas.geography.atlas.Atlas; import org.openstreetmap.atlas.geography.atlas.statistics.AtlasStatistics; /** * @author samgass */ public enum AtlasGeneratorJobGroup { RAW(0, "Raw Atlas Creation", "rawAtlas", Atlas.class, MultipleAtlasProtoOutputFormat.class), SLICED( 1, "Sliced Atlas Creation", "slicedAtlas", Atlas.class, MultipleAtlasProtoOutputFormat.class), SLICED_SUB( 2, "Multipolygon Relation Sub Atlas Creation", "multipolygonRelationSubAtlas", Atlas.class, MultipleAtlasProtoOutputFormat.class), EDGE_SUB( 4, "Edge-only Sub Atlas Creation", "edgeOnlySubAtlas", Atlas.class, MultipleAtlasProtoOutputFormat.class), WAY_SECTIONED_PBF( 5, "Way Sectioned Atlas Creation", "atlas", Atlas.class, MultipleAtlasProtoOutputFormat.class), SHARD_STATISTICS( 6, "Shard Statistics Creation", "shardStats", AtlasStatistics.class, MultipleAtlasStatisticsOutputFormat.class), COUNTRY_STATISTICS( 7, "Country Statistics Creation", "countryStats", AtlasStatistics.class, MultipleAtlasCountryStatisticsOutputFormat.class), DIFFS(8, "Atlas Diff Creation", "diffs", List.class, MultipleAtlasFeatureChangeOutput.class), TAGGABLE_FILTERED_OUTPUT( 9, "Taggable Filtered SubAtlas Creation", "filteredOutput", Atlas.class, MultipleAtlasProtoOutputFormat.class), CONFIGURED_FILTERED_OUTPUT( 10, "Configured Filtered SubAtlas Creation", "configuredOutput", Atlas.class, MultipleAtlasProtoOutputFormat.class); private final String description; private final Integer identifier; private final String cacheFolder; private final Class<?> keyClass; private final Class<? extends MultipleOutputFormat<?, ?>> outputClass; AtlasGeneratorJobGroup(final Integer identifier, final String description, final String cacheFolder, final Class<?> keyClass, final Class<? extends MultipleOutputFormat<?, ?>> outputClass) { this.identifier = identifier; this.description = description; this.cacheFolder = cacheFolder; this.outputClass = outputClass; this.keyClass = keyClass; } public String getCacheFolder() { return this.cacheFolder; } public String getDescription() { return this.description; } public Integer getId() { return this.identifier; } public Class<?> getKeyClass() { return this.keyClass; } public Class<? extends MultipleOutputFormat<?, ?>> getOutputClass() { return this.outputClass; } }
/** * 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.cxf.security.claims.authorization; public enum ClaimMode { STRICT, LAX }
/** Generated by english-annotation-buster, Powered by Google Translate.**/ /* * Copyright 2002-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 * * 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. */ /** * 版权所有2002-2019的原始作者或作者。 * 根据Apache许可证2.0版("许可证")获得许可; * 除非遵守许可,否则不得使用此文件。 * 您可以在https://www.apache.org/licenses/LICENSE-2.0上获得许可的副本。 * 除非适用法律要求或以书面形式同意,否则根据"许可"分发的软件将按"现状"分发,没有任何明示或暗示的保证或条件。 * 有关许可下特定的语言管理权限和限制,请参阅许可。 * */ package org.springframework.expression.spel.ast; import org.springframework.asm.Label; import org.springframework.asm.MethodVisitor; import org.springframework.expression.EvaluationException; import org.springframework.expression.TypedValue; import org.springframework.expression.spel.CodeFlow; import org.springframework.expression.spel.ExpressionState; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.support.BooleanTypedValue; import org.springframework.lang.Nullable; /** * Represents the boolean AND operation. * * @author Andy Clement * @author Mark Fisher * @author Oliver Becker * @since 3.0 */ /** * 表示布尔值AND运算。 * <@作者>安迪·克莱门特<@作者>马克·费舍尔<@作者>奥利弗·贝克尔@since 3.0 */ public class OpAnd extends Operator { public OpAnd(int startPos, int endPos, SpelNodeImpl... operands) { super("and", startPos, endPos, operands); this.exitTypeDescriptor = "Z"; } @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { if (!getBooleanValue(state, getLeftOperand())) { // no need to evaluate right operand return BooleanTypedValue.FALSE; } return BooleanTypedValue.forValue(getBooleanValue(state, getRightOperand())); } private boolean getBooleanValue(ExpressionState state, SpelNodeImpl operand) { try { Boolean value = operand.getValue(state, Boolean.class); assertValueNotNull(value); return value; } catch (SpelEvaluationException ex) { ex.setPosition(operand.getStartPosition()); throw ex; } } private void assertValueNotNull(@Nullable Boolean value) { if (value == null) { throw new SpelEvaluationException(SpelMessage.TYPE_CONVERSION_ERROR, "null", "boolean"); } } @Override public boolean isCompilable() { SpelNodeImpl left = getLeftOperand(); SpelNodeImpl right = getRightOperand(); return (left.isCompilable() && right.isCompilable() && CodeFlow.isBooleanCompatible(left.exitTypeDescriptor) && CodeFlow.isBooleanCompatible(right.exitTypeDescriptor)); } @Override public void generateCode(MethodVisitor mv, CodeFlow cf) { // Pseudo: if (!leftOperandValue) { result=false; } else { result=rightOperandValue; } Label elseTarget = new Label(); Label endOfIf = new Label(); cf.enterCompilationScope(); getLeftOperand().generateCode(mv, cf); cf.unboxBooleanIfNecessary(mv); cf.exitCompilationScope(); mv.visitJumpInsn(IFNE, elseTarget); mv.visitLdcInsn(0); // FALSE mv.visitJumpInsn(GOTO,endOfIf); mv.visitLabel(elseTarget); cf.enterCompilationScope(); getRightOperand().generateCode(mv, cf); cf.unboxBooleanIfNecessary(mv); cf.exitCompilationScope(); mv.visitLabel(endOfIf); cf.pushDescriptor(this.exitTypeDescriptor); } }
package net.glowstone.net; import net.glowstone.entity.meta.MetadataIndex; import net.glowstone.entity.meta.MetadataMap; import net.glowstone.util.TextMessage; import net.glowstone.util.nbt.CompoundTag; import net.glowstone.util.nbt.TagType; import org.json.simple.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Utilities for helping with the protocol test. */ public final class ProtocolTestUtils { private ProtocolTestUtils() { } @SuppressWarnings("unchecked") public static JSONObject getJson() { JSONObject obj = new JSONObject(); obj.put("key", "value"); return obj; } public static TextMessage getTextMessage() { return new TextMessage("text"); } public static List<MetadataMap.Entry> getMetadataEntry() { List<MetadataMap.Entry> list = new ArrayList<>(); list.add(new MetadataMap.Entry(MetadataIndex.AGE, 1)); return list; } public static CompoundTag getTag() { CompoundTag tag = new CompoundTag(); tag.putInt("int", 5); tag.putString("string", "text"); tag.putList("list", TagType.FLOAT, Arrays.asList(1.f, 2.f, 3.f)); tag.putCompound("compound", new CompoundTag()); return tag; } }
package com.example.datastore.query; import static org.junit.Assert.fail; import org.junit.Test; import com.example.datastore.exception.InvalidPredicateException; import com.example.datastore.exception.QueryParsingException; public class QueryParserTest { @Test public void testValidQueries() { try { Query query = Query.createQuery("select $person1,$person2 where $person1 {isFriendOf} $person2"); QueryParser parser = new QueryParser(query); parser.parse(); Query query2 = Query.createQuery("select $person Where {Anish} {isFriendOf} $person,$person {studiedAt} {IITB} "); QueryParser parser2 = new QueryParser(query2); parser2.parse(); Query query3 = Query.createQuery(" select $city WHERE $person {belongsTo} $city"); QueryParser parser3 = new QueryParser(query3); parser3.parse(); Query query4 = Query.createQuery("SELECT $person1,$person2 where {Neha} {isFriendOf} $person1,$person1 " + "{isFriendOf} $person2,$person2 {staysIn} {Mumbai}"); QueryParser parser4 = new QueryParser(query4); parser4.parse(); } catch (QueryParsingException | InvalidPredicateException e) { fail("Not expecting to throw exception"); } } @Test(expected = QueryParsingException.class) public void testInvalidQuery_1() throws QueryParsingException, InvalidPredicateException { Query query = Query.createQuery("select $person1 $person1 {isFriendOf} $person2"); } @Test(expected = QueryParsingException.class) public void testInvalidQuery_2() throws QueryParsingException, InvalidPredicateException { Query query = Query.createQuery("$person1 where $person1 {isFriendOf} $person2"); } @Test(expected = QueryParsingException.class) public void testInvalidQuery_3() throws QueryParsingException, InvalidPredicateException { Query query = Query.createQuery("select $person1 $person2 where $person1 {isFriendOf} $person2"); } }
package com.atomsk.vhr.config; import com.atomsk.vhr.service.MenuService; import com.atomsk.vhr.model.Menu; import com.atomsk.vhr.model.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import java.util.Collection; import java.util.List; /** * @author Atomsk * @github https://github.com/AtomskGit * @blog https://atomskgit.github.io/blog/ * @date 2020/6/4 * <p> * 根据用户传来的请求地址,分析用户 */ @Component public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { @Autowired MenuService menuService; AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException { String requestUrl = ((FilterInvocation) obj).getRequestUrl(); List<Menu> menus = menuService.getAllMenusWithRole(); for (Menu menu : menus) { List<Role> roles = menu.getRoles(); String[] strings = new String[roles.size()]; if (antPathMatcher.match(menu.getUrl(), requestUrl)) { for (int i = 0; i < roles.size(); i++) { strings[i] = roles.get(i).getName(); } return SecurityConfig.createList(strings); } } return SecurityConfig.createList("ROLE_LOGIN"); } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } @Override public boolean supports(Class<?> aClass) { return true; } }
package cn.fxbin.bubble.fireworks.plugin.logging.aspect; import org.slf4j.MDC; /** * AbstractLogging * * @author fxbin * @version v1.0 * @since 2020/5/19 16:18 */ public abstract class AbstractLogging { public String getTraceId() { return MDC.get("traceId"); } public String getSpanId() { return MDC.get("spanId"); } }
package database.biomodels; import org.apache.commons.compress.harmony.unpack200.bytecode.forms.ThisFieldRefForm; import org.apache.http.client.methods.HttpGet; import java.util.Objects; /** * @author Mihai Glon\u021b mglont@ebi.ac.uk */ @SuppressWarnings("WeakerAccess") public final class Requests { // can also use the Caltech instance: http://biomodels.caltech.edu/ public static final String BIOMODELS_EBI_BASE = "https://www.ebi.ac.uk/biomodels/"; public static final String SEARCH_CMD = "search?query=modelformat%3A%22SBML%22%20AND%20curationstatus%3AManually%20curated%20AND%20levelversion%3AL2V4%20OR%20levelversion%3AL3V1&sort=id-desc"; public static final String GET_FILES_CMD = "model/files/"; public static final String DLD_MODEL_CMD = "model/download/"; public static final int SEARCH_RESULTS_PER_PAGE = 100; public static final String APPLICATION_NAME = "SBMLWebApp"; public static final String VERSION = "1.0.0"; public static HttpGet newGetModelRequest(String model) { final String url = getModelRequestUrl(BIOMODELS_EBI_BASE, model); return constructJsonGetRequest(url); } public static HttpGet newCuratedModelSearchRequest() { return newCuratedModelSearchRequest(0); } public static HttpGet newCuratedModelSearchRequest(int offset) { String url = String.format("%s%s&offset=%d&numResults=%d", BIOMODELS_EBI_BASE, SEARCH_CMD, offset, SEARCH_RESULTS_PER_PAGE); return constructJsonGetRequest(url); } public static HttpGet newGetModelFileRequest(String modelId, String fileName) { String url = String.format("%s%s%s?filename=%s", BIOMODELS_EBI_BASE, DLD_MODEL_CMD, Objects.requireNonNull(modelId, "The model identifier is required"), Objects.requireNonNull(fileName, "Model file name is required")); return constructJsonGetRequest(url); } public static HttpGet newGetFilesRequest(String modelId) { String getFilesUrl = String.format("%s%s%s", BIOMODELS_EBI_BASE, GET_FILES_CMD, Objects.requireNonNull(modelId, "The model identifier is required")); return constructJsonGetRequest(getFilesUrl); } private static String getModelRequestUrl(String base, String model) { return String.format("%s%s", Objects.requireNonNull(base, "Cannot build a model retrieval request without a base URI"), Objects.requireNonNull(model, "Model identifier (e.g. BIOMD0000000001) required")); } private static HttpGet constructJsonGetRequest(String uri) { final HttpGet request = new HttpGet(uri); String agentName = APPLICATION_NAME + "/" + VERSION; // please include a point of contact, such as a website or support email address String contact = "http://celldesigner.org"; String userAgent = String.format("%s <%s>", agentName, contact); // System.out.printf("Performing request %s with user agent %s.%n", uri, userAgent); request.setHeader("User-Agent", userAgent); request.setHeader("Accept", "application/json"); return request; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.cluster.settings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentParseException; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.XContentTestUtils; import java.io.IOException; import java.util.Collections; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; public class ClusterUpdateSettingsRequestTests extends ESTestCase { public void testFromXContent() throws IOException { doFromXContentTestWithRandomFields(false); } public void testFromXContentWithRandomFields() throws IOException { doFromXContentTestWithRandomFields(true); } private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws IOException { final ClusterUpdateSettingsRequest request = createTestItem(); boolean humanReadable = randomBoolean(); final XContentType xContentType = XContentType.JSON; BytesReference originalBytes = toShuffledXContent(request, xContentType, ToXContent.EMPTY_PARAMS, humanReadable); if (addRandomFields) { String unsupportedField = "unsupported_field"; BytesReference mutated = BytesReference.bytes(XContentTestUtils.insertIntoXContent(xContentType.xContent(), originalBytes, Collections.singletonList(""), () -> unsupportedField, () -> randomAlphaOfLengthBetween(3, 10))); XContentParseException iae = expectThrows(XContentParseException.class, () -> ClusterUpdateSettingsRequest.fromXContent(createParser(xContentType.xContent(), mutated))); assertThat(iae.getMessage(), containsString("[cluster_update_settings_request] unknown field [" + unsupportedField + "], parser not found")); } else { XContentParser parser = createParser(xContentType.xContent(), originalBytes); ClusterUpdateSettingsRequest parsedRequest = ClusterUpdateSettingsRequest.fromXContent(parser); assertNull(parser.nextToken()); assertThat(parsedRequest.transientSettings(), equalTo(request.transientSettings())); assertThat(parsedRequest.persistentSettings(), equalTo(request.persistentSettings())); } } private static ClusterUpdateSettingsRequest createTestItem() { ClusterUpdateSettingsRequest request = new ClusterUpdateSettingsRequest(); request.persistentSettings(ClusterUpdateSettingsResponseTests.randomClusterSettings(0, 2)); request.transientSettings(ClusterUpdateSettingsResponseTests.randomClusterSettings(0, 2)); return request; } }
/* * Copyright 2021-2021 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.alfresco.core.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; import org.alfresco.core.model.ContentInfo; import org.alfresco.core.model.Definition; import org.alfresco.core.model.Node; import org.alfresco.core.model.PathInfo; import org.alfresco.core.model.PermissionsInfo; import org.alfresco.core.model.UserInfo; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * DeletedNode */ @Validated public class DeletedNode { @JsonProperty("id") private String id = null; @JsonProperty("name") private String name = null; @JsonProperty("nodeType") private String nodeType = null; @JsonProperty("isFolder") private Boolean isFolder = null; @JsonProperty("isFile") private Boolean isFile = null; @JsonProperty("isLocked") private Boolean isLocked = false; @JsonProperty("modifiedAt") private OffsetDateTime modifiedAt = null; @JsonProperty("modifiedByUser") private UserInfo modifiedByUser = null; @JsonProperty("createdAt") private OffsetDateTime createdAt = null; @JsonProperty("createdByUser") private UserInfo createdByUser = null; @JsonProperty("parentId") private String parentId = null; @JsonProperty("isLink") private Boolean isLink = null; @JsonProperty("isFavorite") private Boolean isFavorite = null; @JsonProperty("content") private ContentInfo content = null; @JsonProperty("aspectNames") @Valid private List<String> aspectNames = null; @JsonProperty("properties") private Object properties = null; @JsonProperty("allowableOperations") @Valid private List<String> allowableOperations = null; @JsonProperty("path") private PathInfo path = null; @JsonProperty("permissions") private PermissionsInfo permissions = null; @JsonProperty("definition") private Definition definition = null; @JsonProperty("archivedByUser") private UserInfo archivedByUser = null; @JsonProperty("archivedAt") private OffsetDateTime archivedAt = null; public DeletedNode id(String id) { this.id = id; return this; } /** * Get id * @return id **/ @ApiModelProperty(required = true, value = "") @NotNull public String getId() { return id; } public void setId(String id) { this.id = id; } public DeletedNode name(String name) { this.name = name; return this; } /** * The name must not contain spaces or the following special characters: * \" < > \\ / ? : and |. The character . must not be used at the end of the name. * @return name **/ @ApiModelProperty(required = true, value = "The name must not contain spaces or the following special characters: * \" < > \\ / ? : and |. The character . must not be used at the end of the name. ") @NotNull @Pattern(regexp="^(?!(.*[\\\"\\*\\\\\\>\\<\\?/\\:\\|]+.*)|(.*[\\.]?.*[\\.]+$)|(.*[ ]+$))") public String getName() { return name; } public void setName(String name) { this.name = name; } public DeletedNode nodeType(String nodeType) { this.nodeType = nodeType; return this; } /** * Get nodeType * @return nodeType **/ @ApiModelProperty(required = true, value = "") @NotNull public String getNodeType() { return nodeType; } public void setNodeType(String nodeType) { this.nodeType = nodeType; } public DeletedNode isFolder(Boolean isFolder) { this.isFolder = isFolder; return this; } /** * Get isFolder * @return isFolder **/ @ApiModelProperty(required = true, value = "") @NotNull public Boolean isIsFolder() { return isFolder; } public void setIsFolder(Boolean isFolder) { this.isFolder = isFolder; } public DeletedNode isFile(Boolean isFile) { this.isFile = isFile; return this; } /** * Get isFile * @return isFile **/ @ApiModelProperty(required = true, value = "") @NotNull public Boolean isIsFile() { return isFile; } public void setIsFile(Boolean isFile) { this.isFile = isFile; } public DeletedNode isLocked(Boolean isLocked) { this.isLocked = isLocked; return this; } /** * Get isLocked * @return isLocked **/ @ApiModelProperty(value = "") public Boolean isIsLocked() { return isLocked; } public void setIsLocked(Boolean isLocked) { this.isLocked = isLocked; } public DeletedNode modifiedAt(OffsetDateTime modifiedAt) { this.modifiedAt = modifiedAt; return this; } /** * Get modifiedAt * @return modifiedAt **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public OffsetDateTime getModifiedAt() { return modifiedAt; } public void setModifiedAt(OffsetDateTime modifiedAt) { this.modifiedAt = modifiedAt; } public DeletedNode modifiedByUser(UserInfo modifiedByUser) { this.modifiedByUser = modifiedByUser; return this; } /** * Get modifiedByUser * @return modifiedByUser **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public UserInfo getModifiedByUser() { return modifiedByUser; } public void setModifiedByUser(UserInfo modifiedByUser) { this.modifiedByUser = modifiedByUser; } public DeletedNode createdAt(OffsetDateTime createdAt) { this.createdAt = createdAt; return this; } /** * Get createdAt * @return createdAt **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public OffsetDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; } public DeletedNode createdByUser(UserInfo createdByUser) { this.createdByUser = createdByUser; return this; } /** * Get createdByUser * @return createdByUser **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public UserInfo getCreatedByUser() { return createdByUser; } public void setCreatedByUser(UserInfo createdByUser) { this.createdByUser = createdByUser; } public DeletedNode parentId(String parentId) { this.parentId = parentId; return this; } /** * Get parentId * @return parentId **/ @ApiModelProperty(value = "") public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public DeletedNode isLink(Boolean isLink) { this.isLink = isLink; return this; } /** * Get isLink * @return isLink **/ @ApiModelProperty(value = "") public Boolean isIsLink() { return isLink; } public void setIsLink(Boolean isLink) { this.isLink = isLink; } public DeletedNode isFavorite(Boolean isFavorite) { this.isFavorite = isFavorite; return this; } /** * Get isFavorite * @return isFavorite **/ @ApiModelProperty(value = "") public Boolean isIsFavorite() { return isFavorite; } public void setIsFavorite(Boolean isFavorite) { this.isFavorite = isFavorite; } public DeletedNode content(ContentInfo content) { this.content = content; return this; } /** * Get content * @return content **/ @ApiModelProperty(value = "") @Valid public ContentInfo getContent() { return content; } public void setContent(ContentInfo content) { this.content = content; } public DeletedNode aspectNames(List<String> aspectNames) { this.aspectNames = aspectNames; return this; } public DeletedNode addAspectNamesItem(String aspectNamesItem) { if (this.aspectNames == null) { this.aspectNames = new ArrayList<>(); } this.aspectNames.add(aspectNamesItem); return this; } /** * Get aspectNames * @return aspectNames **/ @ApiModelProperty(value = "") public List<String> getAspectNames() { return aspectNames; } public void setAspectNames(List<String> aspectNames) { this.aspectNames = aspectNames; } public DeletedNode properties(Object properties) { this.properties = properties; return this; } /** * Get properties * @return properties **/ @ApiModelProperty(value = "") public Object getProperties() { return properties; } public void setProperties(Object properties) { this.properties = properties; } public DeletedNode allowableOperations(List<String> allowableOperations) { this.allowableOperations = allowableOperations; return this; } public DeletedNode addAllowableOperationsItem(String allowableOperationsItem) { if (this.allowableOperations == null) { this.allowableOperations = new ArrayList<>(); } this.allowableOperations.add(allowableOperationsItem); return this; } /** * Get allowableOperations * @return allowableOperations **/ @ApiModelProperty(value = "") public List<String> getAllowableOperations() { return allowableOperations; } public void setAllowableOperations(List<String> allowableOperations) { this.allowableOperations = allowableOperations; } public DeletedNode path(PathInfo path) { this.path = path; return this; } /** * Get path * @return path **/ @ApiModelProperty(value = "") @Valid public PathInfo getPath() { return path; } public void setPath(PathInfo path) { this.path = path; } public DeletedNode permissions(PermissionsInfo permissions) { this.permissions = permissions; return this; } /** * Get permissions * @return permissions **/ @ApiModelProperty(value = "") @Valid public PermissionsInfo getPermissions() { return permissions; } public void setPermissions(PermissionsInfo permissions) { this.permissions = permissions; } public DeletedNode definition(Definition definition) { this.definition = definition; return this; } /** * Get definition * @return definition **/ @ApiModelProperty(value = "") @Valid public Definition getDefinition() { return definition; } public void setDefinition(Definition definition) { this.definition = definition; } public DeletedNode archivedByUser(UserInfo archivedByUser) { this.archivedByUser = archivedByUser; return this; } /** * Get archivedByUser * @return archivedByUser **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public UserInfo getArchivedByUser() { return archivedByUser; } public void setArchivedByUser(UserInfo archivedByUser) { this.archivedByUser = archivedByUser; } public DeletedNode archivedAt(OffsetDateTime archivedAt) { this.archivedAt = archivedAt; return this; } /** * Get archivedAt * @return archivedAt **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public OffsetDateTime getArchivedAt() { return archivedAt; } public void setArchivedAt(OffsetDateTime archivedAt) { this.archivedAt = archivedAt; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeletedNode deletedNode = (DeletedNode) o; return Objects.equals(this.id, deletedNode.id) && Objects.equals(this.name, deletedNode.name) && Objects.equals(this.nodeType, deletedNode.nodeType) && Objects.equals(this.isFolder, deletedNode.isFolder) && Objects.equals(this.isFile, deletedNode.isFile) && Objects.equals(this.isLocked, deletedNode.isLocked) && Objects.equals(this.modifiedAt, deletedNode.modifiedAt) && Objects.equals(this.modifiedByUser, deletedNode.modifiedByUser) && Objects.equals(this.createdAt, deletedNode.createdAt) && Objects.equals(this.createdByUser, deletedNode.createdByUser) && Objects.equals(this.parentId, deletedNode.parentId) && Objects.equals(this.isLink, deletedNode.isLink) && Objects.equals(this.isFavorite, deletedNode.isFavorite) && Objects.equals(this.content, deletedNode.content) && Objects.equals(this.aspectNames, deletedNode.aspectNames) && Objects.equals(this.properties, deletedNode.properties) && Objects.equals(this.allowableOperations, deletedNode.allowableOperations) && Objects.equals(this.path, deletedNode.path) && Objects.equals(this.permissions, deletedNode.permissions) && Objects.equals(this.definition, deletedNode.definition) && Objects.equals(this.archivedByUser, deletedNode.archivedByUser) && Objects.equals(this.archivedAt, deletedNode.archivedAt); } @Override public int hashCode() { return Objects.hash(id, name, nodeType, isFolder, isFile, isLocked, modifiedAt, modifiedByUser, createdAt, createdByUser, parentId, isLink, isFavorite, content, aspectNames, properties, allowableOperations, path, permissions, definition, archivedByUser, archivedAt); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeletedNode {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" nodeType: ").append(toIndentedString(nodeType)).append("\n"); sb.append(" isFolder: ").append(toIndentedString(isFolder)).append("\n"); sb.append(" isFile: ").append(toIndentedString(isFile)).append("\n"); sb.append(" isLocked: ").append(toIndentedString(isLocked)).append("\n"); sb.append(" modifiedAt: ").append(toIndentedString(modifiedAt)).append("\n"); sb.append(" modifiedByUser: ").append(toIndentedString(modifiedByUser)).append("\n"); sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); sb.append(" createdByUser: ").append(toIndentedString(createdByUser)).append("\n"); sb.append(" parentId: ").append(toIndentedString(parentId)).append("\n"); sb.append(" isLink: ").append(toIndentedString(isLink)).append("\n"); sb.append(" isFavorite: ").append(toIndentedString(isFavorite)).append("\n"); sb.append(" content: ").append(toIndentedString(content)).append("\n"); sb.append(" aspectNames: ").append(toIndentedString(aspectNames)).append("\n"); sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); sb.append(" allowableOperations: ").append(toIndentedString(allowableOperations)).append("\n"); sb.append(" path: ").append(toIndentedString(path)).append("\n"); sb.append(" permissions: ").append(toIndentedString(permissions)).append("\n"); sb.append(" definition: ").append(toIndentedString(definition)).append("\n"); sb.append(" archivedByUser: ").append(toIndentedString(archivedByUser)).append("\n"); sb.append(" archivedAt: ").append(toIndentedString(archivedAt)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.junit.jupiter.api.Test; public class ToDynamicLanguageSimpleAndXPathAndHeaderTest extends ContextTestSupport { @Test public void testToDynamic() throws Exception { getMockEndpoint("mock:foo-123").expectedBodiesReceived("<order uri=\"foo\"/>"); getMockEndpoint("mock:bar-456").expectedBodiesReceived("<order uri=\"bar\"/>"); template.sendBodyAndHeader("direct:start", "<order uri=\"foo\"/>", "sub", "-123"); template.sendBodyAndHeader("direct:start", "<order uri=\"bar\"/>", "sub", "-456"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").toD("mock:+language:xpath:/order/@uri+language:header:sub"); } }; } }
package cz.metacentrum.perun.wui.registrar.widgets.items; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.user.client.ui.Widget; import cz.metacentrum.perun.wui.json.Events; import cz.metacentrum.perun.wui.model.PerunException; import cz.metacentrum.perun.wui.model.beans.ApplicationFormItemData; import cz.metacentrum.perun.wui.registrar.widgets.PerunForm; import cz.metacentrum.perun.wui.registrar.widgets.items.validators.EinfraUsernameValidator; import cz.metacentrum.perun.wui.registrar.widgets.items.validators.PerunFormItemValidator; import cz.metacentrum.perun.wui.registrar.widgets.items.validators.UsernameValidator; import cz.metacentrum.perun.wui.widgets.boxes.ExtendedTextBox; import org.gwtbootstrap3.client.ui.InputGroup; import org.gwtbootstrap3.client.ui.InputGroupAddon; import org.gwtbootstrap3.client.ui.constants.IconType; import org.gwtbootstrap3.client.ui.html.Paragraph; import java.util.Objects; /** * Represents text field for username/login. * * @author Ondrej Velisek <ondrejvelisek@gmail.com> */ public class Username extends PerunFormItemEditable { public final static int MAX_LENGTH = 1024; private final UsernameValidator validator; private InputGroup widget; public Username(PerunForm form, ApplicationFormItemData item, String lang) { super(form, item, lang); if (item.getFormItem() != null && Objects.equals("urn:perun:user:attribute-def:def:login-namespace:einfra", item.getFormItem().getPerunDestinationAttribute())) { this.validator = new EinfraUsernameValidator(); } else { this.validator = new UsernameValidator(); } } protected Widget initWidget() { InputGroupAddon addon = new InputGroupAddon(); addon.setIcon(IconType.USER); ExtendedTextBox box = new ExtendedTextBox(); box.setMaxLength(MAX_LENGTH); if (getItemData().getFormItem().getRegex() != null) { box.setRegex(getItemData().getFormItem().getRegex()); } widget = new InputGroup(); widget.add(addon); widget.add(box); return widget; } @Override public Widget initWidgetOnlyPreview() { InputGroupAddon addon = new InputGroupAddon(); addon.setIcon(IconType.USER); Paragraph box = new Paragraph(); box.addStyleName("form-control"); widget = new InputGroup(); widget.add(addon); widget.add(box); return widget; } @Override public void validate(Events<Boolean> events) { if (!isOnlyPreview() && getTextBox().isEnabled()) { validator.validate(this, events); } else { events.onLoadingStart(); events.onFinished(true); } } @Override public boolean validateLocal() { if (!isOnlyPreview() && getTextBox().isEnabled()) { return validator.validateLocal(this); } return true; } @Override public PerunFormItemValidator.Result getLastValidationResult() { if (getTextBox().isEnabled()) { return validator.getLastResult(); } return PerunFormItemValidator.Result.OK; } @Override public boolean focus() { if (isOnlyPreview()) { return false; } if (getTextBox().isEnabled()) { getTextBox().setFocus(true); return true; } return false; } @Override public void setValidationTriggers() { if (isOnlyPreview()) { return; } final Events<Boolean> nothingEvents = new Events<Boolean>() { @Override public void onFinished(Boolean result) { } @Override public void onError(PerunException error) { } @Override public void onLoadingStart() { } }; getTextBox().addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { validate(nothingEvents); } }); } @Override public String getValue() { if (isOnlyPreview()) { return getPreview().getText(); } return getTextBox().getValue(); } @Override public InputGroup getWidget() { return widget; } @Override protected void setValueImpl(String value) { if (isOnlyPreview()) { getPreview().setText(value); return; } getTextBox().setValue(value); } public ExtendedTextBox getTextBox() { for (Widget box : getWidget()) { if (box instanceof ExtendedTextBox) { return (ExtendedTextBox) box; } } return null; } public Paragraph getPreview() { for (Widget box : getWidget()) { if (box instanceof Paragraph) { return (Paragraph) box; } } return null; } public void setEnable(boolean enable) { getTextBox().setEnabled(enable); } @Override public boolean isOnlyPreview() { return super.isOnlyPreview() || PerunForm.FormState.EDIT.equals(getForm().getFormState()); } @Override public boolean isUpdatable() { // username can't' be updated once submitted return false; } }
/*- * #%L * OpenAPI Generator for Spring Boot :: Common * %% * Copyright (C) 2020 QAware 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% */ package de.qaware.openapigeneratorforspring.common.mapper; import de.qaware.openapigeneratorforspring.model.ExternalDocumentation; import lombok.RequiredArgsConstructor; import static de.qaware.openapigeneratorforspring.common.util.OpenApiMapUtils.setMapIfNotEmpty; import static de.qaware.openapigeneratorforspring.common.util.OpenApiStringUtils.setStringIfNotBlank; @RequiredArgsConstructor public class DefaultExternalDocumentationAnnotationMapper implements ExternalDocumentationAnnotationMapper { private final ExtensionAnnotationMapper extensionAnnotationMapper; @Override public ExternalDocumentation map(io.swagger.v3.oas.annotations.ExternalDocumentation annotation) { ExternalDocumentation externalDocumentation = new ExternalDocumentation(); setStringIfNotBlank(annotation.description(), externalDocumentation::setDescription); setStringIfNotBlank(annotation.url(), externalDocumentation::setUrl); setMapIfNotEmpty(extensionAnnotationMapper.mapArray(annotation.extensions()), externalDocumentation::setExtensions); return externalDocumentation; } }
package org.linlinjava.litemall.db.domain; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class LitemallCouponExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_coupon * * @mbg.generated */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_coupon * * @mbg.generated */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_coupon * * @mbg.generated */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public LitemallCouponExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public LitemallCouponExample orderBy(String orderByClause) { this.setOrderByClause(orderByClause); return this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public LitemallCouponExample orderBy(String ... orderByClauses) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < orderByClauses.length; i++) { sb.append(orderByClauses[i]); if (i < orderByClauses.length - 1) { sb.append(" , "); } } this.setOrderByClause(sb.toString()); return this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(this); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public static Criteria newAndCreateCriteria() { LitemallCouponExample example = new LitemallCouponExample(); return example.createCriteria(); } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table litemall_coupon * * @mbg.generated */ protected abstract static class GeneratedCriteria { protected List<Criterion> goodsValueCriteria; protected List<Criterion> allCriteria; protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); goodsValueCriteria = new ArrayList<Criterion>(); } public List<Criterion> getGoodsValueCriteria() { return goodsValueCriteria; } protected void addGoodsValueCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } goodsValueCriteria.add(new Criterion(condition, value, "org.linlinjava.litemall.db.mybatis.JsonIntegerArrayTypeHandler")); allCriteria = null; } protected void addGoodsValueCriterion(String condition, Integer[] value1, Integer[] value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } goodsValueCriteria.add(new Criterion(condition, value1, value2, "org.linlinjava.litemall.db.mybatis.JsonIntegerArrayTypeHandler")); allCriteria = null; } public boolean isValid() { return criteria.size() > 0 || goodsValueCriteria.size() > 0; } public List<Criterion> getAllCriteria() { if (allCriteria == null) { allCriteria = new ArrayList<Criterion>(); allCriteria.addAll(criteria); allCriteria.addAll(goodsValueCriteria); } return allCriteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); allCriteria = null; } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); allCriteria = null; } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); allCriteria = null; } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andIdEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("id = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andIdNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("id <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andIdGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("id > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andIdGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("id >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andIdLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("id < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andIdLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("id <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("`name` is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("`name` is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("`name` =", value, "name"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andNameEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`name` = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("`name` <>", value, "name"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andNameNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`name` <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("`name` >", value, "name"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andNameGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`name` > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("`name` >=", value, "name"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andNameGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`name` >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("`name` <", value, "name"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andNameLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`name` < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("`name` <=", value, "name"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andNameLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`name` <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("`name` like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("`name` not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("`name` in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("`name` not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("`name` between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("`name` not between", value1, value2, "name"); return (Criteria) this; } public Criteria andDescIsNull() { addCriterion("`desc` is null"); return (Criteria) this; } public Criteria andDescIsNotNull() { addCriterion("`desc` is not null"); return (Criteria) this; } public Criteria andDescEqualTo(String value) { addCriterion("`desc` =", value, "desc"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDescEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`desc` = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDescNotEqualTo(String value) { addCriterion("`desc` <>", value, "desc"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDescNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`desc` <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDescGreaterThan(String value) { addCriterion("`desc` >", value, "desc"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDescGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`desc` > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDescGreaterThanOrEqualTo(String value) { addCriterion("`desc` >=", value, "desc"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDescGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`desc` >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDescLessThan(String value) { addCriterion("`desc` <", value, "desc"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDescLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`desc` < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDescLessThanOrEqualTo(String value) { addCriterion("`desc` <=", value, "desc"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDescLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`desc` <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDescLike(String value) { addCriterion("`desc` like", value, "desc"); return (Criteria) this; } public Criteria andDescNotLike(String value) { addCriterion("`desc` not like", value, "desc"); return (Criteria) this; } public Criteria andDescIn(List<String> values) { addCriterion("`desc` in", values, "desc"); return (Criteria) this; } public Criteria andDescNotIn(List<String> values) { addCriterion("`desc` not in", values, "desc"); return (Criteria) this; } public Criteria andDescBetween(String value1, String value2) { addCriterion("`desc` between", value1, value2, "desc"); return (Criteria) this; } public Criteria andDescNotBetween(String value1, String value2) { addCriterion("`desc` not between", value1, value2, "desc"); return (Criteria) this; } public Criteria andTagIsNull() { addCriterion("tag is null"); return (Criteria) this; } public Criteria andTagIsNotNull() { addCriterion("tag is not null"); return (Criteria) this; } public Criteria andTagEqualTo(String value) { addCriterion("tag =", value, "tag"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTagEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("tag = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTagNotEqualTo(String value) { addCriterion("tag <>", value, "tag"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTagNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("tag <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTagGreaterThan(String value) { addCriterion("tag >", value, "tag"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTagGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("tag > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTagGreaterThanOrEqualTo(String value) { addCriterion("tag >=", value, "tag"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTagGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("tag >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTagLessThan(String value) { addCriterion("tag <", value, "tag"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTagLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("tag < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTagLessThanOrEqualTo(String value) { addCriterion("tag <=", value, "tag"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTagLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("tag <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTagLike(String value) { addCriterion("tag like", value, "tag"); return (Criteria) this; } public Criteria andTagNotLike(String value) { addCriterion("tag not like", value, "tag"); return (Criteria) this; } public Criteria andTagIn(List<String> values) { addCriterion("tag in", values, "tag"); return (Criteria) this; } public Criteria andTagNotIn(List<String> values) { addCriterion("tag not in", values, "tag"); return (Criteria) this; } public Criteria andTagBetween(String value1, String value2) { addCriterion("tag between", value1, value2, "tag"); return (Criteria) this; } public Criteria andTagNotBetween(String value1, String value2) { addCriterion("tag not between", value1, value2, "tag"); return (Criteria) this; } public Criteria andTotalIsNull() { addCriterion("total is null"); return (Criteria) this; } public Criteria andTotalIsNotNull() { addCriterion("total is not null"); return (Criteria) this; } public Criteria andTotalEqualTo(Integer value) { addCriterion("total =", value, "total"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTotalEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("total = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTotalNotEqualTo(Integer value) { addCriterion("total <>", value, "total"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTotalNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("total <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTotalGreaterThan(Integer value) { addCriterion("total >", value, "total"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTotalGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("total > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTotalGreaterThanOrEqualTo(Integer value) { addCriterion("total >=", value, "total"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTotalGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("total >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTotalLessThan(Integer value) { addCriterion("total <", value, "total"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTotalLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("total < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTotalLessThanOrEqualTo(Integer value) { addCriterion("total <=", value, "total"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTotalLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("total <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTotalIn(List<Integer> values) { addCriterion("total in", values, "total"); return (Criteria) this; } public Criteria andTotalNotIn(List<Integer> values) { addCriterion("total not in", values, "total"); return (Criteria) this; } public Criteria andTotalBetween(Integer value1, Integer value2) { addCriterion("total between", value1, value2, "total"); return (Criteria) this; } public Criteria andTotalNotBetween(Integer value1, Integer value2) { addCriterion("total not between", value1, value2, "total"); return (Criteria) this; } public Criteria andDiscountIsNull() { addCriterion("discount is null"); return (Criteria) this; } public Criteria andDiscountIsNotNull() { addCriterion("discount is not null"); return (Criteria) this; } public Criteria andDiscountEqualTo(BigDecimal value) { addCriterion("discount =", value, "discount"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDiscountEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("discount = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDiscountNotEqualTo(BigDecimal value) { addCriterion("discount <>", value, "discount"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDiscountNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("discount <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDiscountGreaterThan(BigDecimal value) { addCriterion("discount >", value, "discount"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDiscountGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("discount > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDiscountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("discount >=", value, "discount"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDiscountGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("discount >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDiscountLessThan(BigDecimal value) { addCriterion("discount <", value, "discount"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDiscountLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("discount < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDiscountLessThanOrEqualTo(BigDecimal value) { addCriterion("discount <=", value, "discount"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDiscountLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("discount <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDiscountIn(List<BigDecimal> values) { addCriterion("discount in", values, "discount"); return (Criteria) this; } public Criteria andDiscountNotIn(List<BigDecimal> values) { addCriterion("discount not in", values, "discount"); return (Criteria) this; } public Criteria andDiscountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("discount between", value1, value2, "discount"); return (Criteria) this; } public Criteria andDiscountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("discount not between", value1, value2, "discount"); return (Criteria) this; } public Criteria andMinIsNull() { addCriterion("`min` is null"); return (Criteria) this; } public Criteria andMinIsNotNull() { addCriterion("`min` is not null"); return (Criteria) this; } public Criteria andMinEqualTo(BigDecimal value) { addCriterion("`min` =", value, "min"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andMinEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`min` = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andMinNotEqualTo(BigDecimal value) { addCriterion("`min` <>", value, "min"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andMinNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`min` <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andMinGreaterThan(BigDecimal value) { addCriterion("`min` >", value, "min"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andMinGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`min` > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andMinGreaterThanOrEqualTo(BigDecimal value) { addCriterion("`min` >=", value, "min"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andMinGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`min` >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andMinLessThan(BigDecimal value) { addCriterion("`min` <", value, "min"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andMinLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`min` < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andMinLessThanOrEqualTo(BigDecimal value) { addCriterion("`min` <=", value, "min"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andMinLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`min` <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andMinIn(List<BigDecimal> values) { addCriterion("`min` in", values, "min"); return (Criteria) this; } public Criteria andMinNotIn(List<BigDecimal> values) { addCriterion("`min` not in", values, "min"); return (Criteria) this; } public Criteria andMinBetween(BigDecimal value1, BigDecimal value2) { addCriterion("`min` between", value1, value2, "min"); return (Criteria) this; } public Criteria andMinNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("`min` not between", value1, value2, "min"); return (Criteria) this; } public Criteria andLimitIsNull() { addCriterion("`limit` is null"); return (Criteria) this; } public Criteria andLimitIsNotNull() { addCriterion("`limit` is not null"); return (Criteria) this; } public Criteria andLimitEqualTo(Short value) { addCriterion("`limit` =", value, "limit"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andLimitEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`limit` = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andLimitNotEqualTo(Short value) { addCriterion("`limit` <>", value, "limit"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andLimitNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`limit` <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andLimitGreaterThan(Short value) { addCriterion("`limit` >", value, "limit"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andLimitGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`limit` > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andLimitGreaterThanOrEqualTo(Short value) { addCriterion("`limit` >=", value, "limit"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andLimitGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`limit` >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andLimitLessThan(Short value) { addCriterion("`limit` <", value, "limit"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andLimitLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`limit` < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andLimitLessThanOrEqualTo(Short value) { addCriterion("`limit` <=", value, "limit"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andLimitLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`limit` <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andLimitIn(List<Short> values) { addCriterion("`limit` in", values, "limit"); return (Criteria) this; } public Criteria andLimitNotIn(List<Short> values) { addCriterion("`limit` not in", values, "limit"); return (Criteria) this; } public Criteria andLimitBetween(Short value1, Short value2) { addCriterion("`limit` between", value1, value2, "limit"); return (Criteria) this; } public Criteria andLimitNotBetween(Short value1, Short value2) { addCriterion("`limit` not between", value1, value2, "limit"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("`type` is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("`type` is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Short value) { addCriterion("`type` =", value, "type"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTypeEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`type` = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTypeNotEqualTo(Short value) { addCriterion("`type` <>", value, "type"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTypeNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`type` <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTypeGreaterThan(Short value) { addCriterion("`type` >", value, "type"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTypeGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`type` > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Short value) { addCriterion("`type` >=", value, "type"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTypeGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`type` >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTypeLessThan(Short value) { addCriterion("`type` <", value, "type"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTypeLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`type` < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Short value) { addCriterion("`type` <=", value, "type"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTypeLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`type` <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTypeIn(List<Short> values) { addCriterion("`type` in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Short> values) { addCriterion("`type` not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Short value1, Short value2) { addCriterion("`type` between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Short value1, Short value2) { addCriterion("`type` not between", value1, value2, "type"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("`status` is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("`status` is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Short value) { addCriterion("`status` =", value, "status"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStatusEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`status` = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStatusNotEqualTo(Short value) { addCriterion("`status` <>", value, "status"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStatusNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`status` <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStatusGreaterThan(Short value) { addCriterion("`status` >", value, "status"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStatusGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`status` > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Short value) { addCriterion("`status` >=", value, "status"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStatusGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`status` >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStatusLessThan(Short value) { addCriterion("`status` <", value, "status"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStatusLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`status` < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Short value) { addCriterion("`status` <=", value, "status"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStatusLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`status` <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStatusIn(List<Short> values) { addCriterion("`status` in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Short> values) { addCriterion("`status` not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Short value1, Short value2) { addCriterion("`status` between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Short value1, Short value2) { addCriterion("`status` not between", value1, value2, "status"); return (Criteria) this; } public Criteria andGoodsTypeIsNull() { addCriterion("goods_type is null"); return (Criteria) this; } public Criteria andGoodsTypeIsNotNull() { addCriterion("goods_type is not null"); return (Criteria) this; } public Criteria andGoodsTypeEqualTo(Short value) { addCriterion("goods_type =", value, "goodsType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsTypeEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_type = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsTypeNotEqualTo(Short value) { addCriterion("goods_type <>", value, "goodsType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsTypeNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_type <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsTypeGreaterThan(Short value) { addCriterion("goods_type >", value, "goodsType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsTypeGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_type > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsTypeGreaterThanOrEqualTo(Short value) { addCriterion("goods_type >=", value, "goodsType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsTypeGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_type >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsTypeLessThan(Short value) { addCriterion("goods_type <", value, "goodsType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsTypeLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_type < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsTypeLessThanOrEqualTo(Short value) { addCriterion("goods_type <=", value, "goodsType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsTypeLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_type <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsTypeIn(List<Short> values) { addCriterion("goods_type in", values, "goodsType"); return (Criteria) this; } public Criteria andGoodsTypeNotIn(List<Short> values) { addCriterion("goods_type not in", values, "goodsType"); return (Criteria) this; } public Criteria andGoodsTypeBetween(Short value1, Short value2) { addCriterion("goods_type between", value1, value2, "goodsType"); return (Criteria) this; } public Criteria andGoodsTypeNotBetween(Short value1, Short value2) { addCriterion("goods_type not between", value1, value2, "goodsType"); return (Criteria) this; } public Criteria andGoodsValueIsNull() { addCriterion("goods_value is null"); return (Criteria) this; } public Criteria andGoodsValueIsNotNull() { addCriterion("goods_value is not null"); return (Criteria) this; } public Criteria andGoodsValueEqualTo(Integer[] value) { addGoodsValueCriterion("goods_value =", value, "goodsValue"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsValueEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_value = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsValueNotEqualTo(Integer[] value) { addGoodsValueCriterion("goods_value <>", value, "goodsValue"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsValueNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_value <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsValueGreaterThan(Integer[] value) { addGoodsValueCriterion("goods_value >", value, "goodsValue"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsValueGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_value > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsValueGreaterThanOrEqualTo(Integer[] value) { addGoodsValueCriterion("goods_value >=", value, "goodsValue"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsValueGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_value >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsValueLessThan(Integer[] value) { addGoodsValueCriterion("goods_value <", value, "goodsValue"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsValueLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_value < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsValueLessThanOrEqualTo(Integer[] value) { addGoodsValueCriterion("goods_value <=", value, "goodsValue"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andGoodsValueLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("goods_value <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andGoodsValueLike(Integer[] value) { addGoodsValueCriterion("goods_value like", value, "goodsValue"); return (Criteria) this; } public Criteria andGoodsValueNotLike(Integer[] value) { addGoodsValueCriterion("goods_value not like", value, "goodsValue"); return (Criteria) this; } public Criteria andGoodsValueIn(List<Integer[]> values) { addGoodsValueCriterion("goods_value in", values, "goodsValue"); return (Criteria) this; } public Criteria andGoodsValueNotIn(List<Integer[]> values) { addGoodsValueCriterion("goods_value not in", values, "goodsValue"); return (Criteria) this; } public Criteria andGoodsValueBetween(Integer[] value1, Integer[] value2) { addGoodsValueCriterion("goods_value between", value1, value2, "goodsValue"); return (Criteria) this; } public Criteria andGoodsValueNotBetween(Integer[] value1, Integer[] value2) { addGoodsValueCriterion("goods_value not between", value1, value2, "goodsValue"); return (Criteria) this; } public Criteria andCodeIsNull() { addCriterion("code is null"); return (Criteria) this; } public Criteria andCodeIsNotNull() { addCriterion("code is not null"); return (Criteria) this; } public Criteria andCodeEqualTo(String value) { addCriterion("code =", value, "code"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andCodeEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("code = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCodeNotEqualTo(String value) { addCriterion("code <>", value, "code"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andCodeNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("code <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCodeGreaterThan(String value) { addCriterion("code >", value, "code"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andCodeGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("code > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCodeGreaterThanOrEqualTo(String value) { addCriterion("code >=", value, "code"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andCodeGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("code >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCodeLessThan(String value) { addCriterion("code <", value, "code"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andCodeLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("code < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCodeLessThanOrEqualTo(String value) { addCriterion("code <=", value, "code"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andCodeLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("code <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCodeLike(String value) { addCriterion("code like", value, "code"); return (Criteria) this; } public Criteria andCodeNotLike(String value) { addCriterion("code not like", value, "code"); return (Criteria) this; } public Criteria andCodeIn(List<String> values) { addCriterion("code in", values, "code"); return (Criteria) this; } public Criteria andCodeNotIn(List<String> values) { addCriterion("code not in", values, "code"); return (Criteria) this; } public Criteria andCodeBetween(String value1, String value2) { addCriterion("code between", value1, value2, "code"); return (Criteria) this; } public Criteria andCodeNotBetween(String value1, String value2) { addCriterion("code not between", value1, value2, "code"); return (Criteria) this; } public Criteria andTimeTypeIsNull() { addCriterion("time_type is null"); return (Criteria) this; } public Criteria andTimeTypeIsNotNull() { addCriterion("time_type is not null"); return (Criteria) this; } public Criteria andTimeTypeEqualTo(Short value) { addCriterion("time_type =", value, "timeType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTimeTypeEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("time_type = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTimeTypeNotEqualTo(Short value) { addCriterion("time_type <>", value, "timeType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTimeTypeNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("time_type <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTimeTypeGreaterThan(Short value) { addCriterion("time_type >", value, "timeType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTimeTypeGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("time_type > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTimeTypeGreaterThanOrEqualTo(Short value) { addCriterion("time_type >=", value, "timeType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTimeTypeGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("time_type >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTimeTypeLessThan(Short value) { addCriterion("time_type <", value, "timeType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTimeTypeLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("time_type < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTimeTypeLessThanOrEqualTo(Short value) { addCriterion("time_type <=", value, "timeType"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andTimeTypeLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("time_type <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andTimeTypeIn(List<Short> values) { addCriterion("time_type in", values, "timeType"); return (Criteria) this; } public Criteria andTimeTypeNotIn(List<Short> values) { addCriterion("time_type not in", values, "timeType"); return (Criteria) this; } public Criteria andTimeTypeBetween(Short value1, Short value2) { addCriterion("time_type between", value1, value2, "timeType"); return (Criteria) this; } public Criteria andTimeTypeNotBetween(Short value1, Short value2) { addCriterion("time_type not between", value1, value2, "timeType"); return (Criteria) this; } public Criteria andDaysIsNull() { addCriterion("`days` is null"); return (Criteria) this; } public Criteria andDaysIsNotNull() { addCriterion("`days` is not null"); return (Criteria) this; } public Criteria andDaysEqualTo(Short value) { addCriterion("`days` =", value, "days"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDaysEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`days` = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDaysNotEqualTo(Short value) { addCriterion("`days` <>", value, "days"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDaysNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`days` <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDaysGreaterThan(Short value) { addCriterion("`days` >", value, "days"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDaysGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`days` > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDaysGreaterThanOrEqualTo(Short value) { addCriterion("`days` >=", value, "days"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDaysGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`days` >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDaysLessThan(Short value) { addCriterion("`days` <", value, "days"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDaysLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`days` < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDaysLessThanOrEqualTo(Short value) { addCriterion("`days` <=", value, "days"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDaysLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("`days` <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDaysIn(List<Short> values) { addCriterion("`days` in", values, "days"); return (Criteria) this; } public Criteria andDaysNotIn(List<Short> values) { addCriterion("`days` not in", values, "days"); return (Criteria) this; } public Criteria andDaysBetween(Short value1, Short value2) { addCriterion("`days` between", value1, value2, "days"); return (Criteria) this; } public Criteria andDaysNotBetween(Short value1, Short value2) { addCriterion("`days` not between", value1, value2, "days"); return (Criteria) this; } public Criteria andStartTimeIsNull() { addCriterion("start_time is null"); return (Criteria) this; } public Criteria andStartTimeIsNotNull() { addCriterion("start_time is not null"); return (Criteria) this; } public Criteria andStartTimeEqualTo(LocalDateTime value) { addCriterion("start_time =", value, "startTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStartTimeEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("start_time = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStartTimeNotEqualTo(LocalDateTime value) { addCriterion("start_time <>", value, "startTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStartTimeNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("start_time <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStartTimeGreaterThan(LocalDateTime value) { addCriterion("start_time >", value, "startTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStartTimeGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("start_time > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStartTimeGreaterThanOrEqualTo(LocalDateTime value) { addCriterion("start_time >=", value, "startTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStartTimeGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("start_time >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStartTimeLessThan(LocalDateTime value) { addCriterion("start_time <", value, "startTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStartTimeLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("start_time < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStartTimeLessThanOrEqualTo(LocalDateTime value) { addCriterion("start_time <=", value, "startTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andStartTimeLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("start_time <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andStartTimeIn(List<LocalDateTime> values) { addCriterion("start_time in", values, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotIn(List<LocalDateTime> values) { addCriterion("start_time not in", values, "startTime"); return (Criteria) this; } public Criteria andStartTimeBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("start_time between", value1, value2, "startTime"); return (Criteria) this; } public Criteria andStartTimeNotBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("start_time not between", value1, value2, "startTime"); return (Criteria) this; } public Criteria andEndTimeIsNull() { addCriterion("end_time is null"); return (Criteria) this; } public Criteria andEndTimeIsNotNull() { addCriterion("end_time is not null"); return (Criteria) this; } public Criteria andEndTimeEqualTo(LocalDateTime value) { addCriterion("end_time =", value, "endTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andEndTimeEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("end_time = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andEndTimeNotEqualTo(LocalDateTime value) { addCriterion("end_time <>", value, "endTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andEndTimeNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("end_time <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andEndTimeGreaterThan(LocalDateTime value) { addCriterion("end_time >", value, "endTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andEndTimeGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("end_time > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andEndTimeGreaterThanOrEqualTo(LocalDateTime value) { addCriterion("end_time >=", value, "endTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andEndTimeGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("end_time >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andEndTimeLessThan(LocalDateTime value) { addCriterion("end_time <", value, "endTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andEndTimeLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("end_time < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andEndTimeLessThanOrEqualTo(LocalDateTime value) { addCriterion("end_time <=", value, "endTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andEndTimeLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("end_time <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andEndTimeIn(List<LocalDateTime> values) { addCriterion("end_time in", values, "endTime"); return (Criteria) this; } public Criteria andEndTimeNotIn(List<LocalDateTime> values) { addCriterion("end_time not in", values, "endTime"); return (Criteria) this; } public Criteria andEndTimeBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("end_time between", value1, value2, "endTime"); return (Criteria) this; } public Criteria andEndTimeNotBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("end_time not between", value1, value2, "endTime"); return (Criteria) this; } public Criteria andAddTimeIsNull() { addCriterion("add_time is null"); return (Criteria) this; } public Criteria andAddTimeIsNotNull() { addCriterion("add_time is not null"); return (Criteria) this; } public Criteria andAddTimeEqualTo(LocalDateTime value) { addCriterion("add_time =", value, "addTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andAddTimeEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("add_time = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andAddTimeNotEqualTo(LocalDateTime value) { addCriterion("add_time <>", value, "addTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andAddTimeNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("add_time <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andAddTimeGreaterThan(LocalDateTime value) { addCriterion("add_time >", value, "addTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andAddTimeGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("add_time > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andAddTimeGreaterThanOrEqualTo(LocalDateTime value) { addCriterion("add_time >=", value, "addTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andAddTimeGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("add_time >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andAddTimeLessThan(LocalDateTime value) { addCriterion("add_time <", value, "addTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andAddTimeLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("add_time < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andAddTimeLessThanOrEqualTo(LocalDateTime value) { addCriterion("add_time <=", value, "addTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andAddTimeLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("add_time <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andAddTimeIn(List<LocalDateTime> values) { addCriterion("add_time in", values, "addTime"); return (Criteria) this; } public Criteria andAddTimeNotIn(List<LocalDateTime> values) { addCriterion("add_time not in", values, "addTime"); return (Criteria) this; } public Criteria andAddTimeBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("add_time between", value1, value2, "addTime"); return (Criteria) this; } public Criteria andAddTimeNotBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("add_time not between", value1, value2, "addTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(LocalDateTime value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andUpdateTimeEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("update_time = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(LocalDateTime value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andUpdateTimeNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("update_time <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(LocalDateTime value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andUpdateTimeGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("update_time > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(LocalDateTime value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andUpdateTimeGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("update_time >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdateTimeLessThan(LocalDateTime value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andUpdateTimeLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("update_time < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(LocalDateTime value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andUpdateTimeLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("update_time <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdateTimeIn(List<LocalDateTime> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<LocalDateTime> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(LocalDateTime value1, LocalDateTime value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andDeletedIsNull() { addCriterion("deleted is null"); return (Criteria) this; } public Criteria andDeletedIsNotNull() { addCriterion("deleted is not null"); return (Criteria) this; } public Criteria andDeletedEqualTo(Boolean value) { addCriterion("deleted =", value, "deleted"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDeletedEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("deleted = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDeletedNotEqualTo(Boolean value) { addCriterion("deleted <>", value, "deleted"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDeletedNotEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("deleted <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDeletedGreaterThan(Boolean value) { addCriterion("deleted >", value, "deleted"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDeletedGreaterThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("deleted > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDeletedGreaterThanOrEqualTo(Boolean value) { addCriterion("deleted >=", value, "deleted"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDeletedGreaterThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("deleted >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDeletedLessThan(Boolean value) { addCriterion("deleted <", value, "deleted"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDeletedLessThanColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("deleted < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDeletedLessThanOrEqualTo(Boolean value) { addCriterion("deleted <=", value, "deleted"); return (Criteria) this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andDeletedLessThanOrEqualToColumn(LitemallCoupon.Column column) { addCriterion(new StringBuilder("deleted <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andDeletedIn(List<Boolean> values) { addCriterion("deleted in", values, "deleted"); return (Criteria) this; } public Criteria andDeletedNotIn(List<Boolean> values) { addCriterion("deleted not in", values, "deleted"); return (Criteria) this; } public Criteria andDeletedBetween(Boolean value1, Boolean value2) { addCriterion("deleted between", value1, value2, "deleted"); return (Criteria) this; } public Criteria andDeletedNotBetween(Boolean value1, Boolean value2) { addCriterion("deleted not between", value1, value2, "deleted"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table litemall_coupon * * @mbg.generated do_not_delete_during_merge */ public static class Criteria extends GeneratedCriteria { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ private LitemallCouponExample example; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ protected Criteria(LitemallCouponExample example) { super(); this.example = example; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public LitemallCouponExample example() { return this.example; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andIf(boolean ifAdd, ICriteriaAdd add) { if (ifAdd) { add.add(this); } return this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public Criteria andLogicalDeleted(boolean deleted) { return deleted ? andDeletedEqualTo(LitemallCoupon.IS_DELETED) : andDeletedNotEqualTo(LitemallCoupon.IS_DELETED); } /** * This interface was generated by MyBatis Generator. * This interface corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public interface ICriteriaAdd { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_coupon * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ Criteria add(Criteria add); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table litemall_coupon * * @mbg.generated */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package io.fabric8.kubernetes.api.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Version; import io.sundr.builder.annotations.Buildable; import lombok.EqualsAndHashCode; import lombok.ToString; @JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "apiVersion", "kind", "metadata", "command", "container", "stderr", "stdin", "stdout", "tty" }) @ToString @EqualsAndHashCode @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = true, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder") @Version("v1") @Group("") public class PodExecOptions implements KubernetesResource { /** * * (Required) * */ @JsonProperty("apiVersion") private String apiVersion = "v1"; @JsonProperty("command") private List<String> command = new ArrayList<String>(); @JsonProperty("container") private String container; /** * * (Required) * */ @JsonProperty("kind") private String kind = "PodExecOptions"; @JsonProperty("stderr") private Boolean stderr; @JsonProperty("stdin") private Boolean stdin; @JsonProperty("stdout") private Boolean stdout; @JsonProperty("tty") private Boolean tty; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public PodExecOptions() { } /** * * @param container * @param stdin * @param apiVersion * @param stdout * @param kind * @param tty * @param stderr * @param command */ public PodExecOptions(String apiVersion, List<String> command, String container, String kind, Boolean stderr, Boolean stdin, Boolean stdout, Boolean tty) { super(); this.apiVersion = apiVersion; this.command = command; this.container = container; this.kind = kind; this.stderr = stderr; this.stdin = stdin; this.stdout = stdout; this.tty = tty; } /** * * (Required) * */ @JsonProperty("apiVersion") public String getApiVersion() { return apiVersion; } /** * * (Required) * */ @JsonProperty("apiVersion") public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } @JsonProperty("command") public List<String> getCommand() { return command; } @JsonProperty("command") public void setCommand(List<String> command) { this.command = command; } @JsonProperty("container") public String getContainer() { return container; } @JsonProperty("container") public void setContainer(String container) { this.container = container; } /** * * (Required) * */ @JsonProperty("kind") public String getKind() { return kind; } /** * * (Required) * */ @JsonProperty("kind") public void setKind(String kind) { this.kind = kind; } @JsonProperty("stderr") public Boolean getStderr() { return stderr; } @JsonProperty("stderr") public void setStderr(Boolean stderr) { this.stderr = stderr; } @JsonProperty("stdin") public Boolean getStdin() { return stdin; } @JsonProperty("stdin") public void setStdin(Boolean stdin) { this.stdin = stdin; } @JsonProperty("stdout") public Boolean getStdout() { return stdout; } @JsonProperty("stdout") public void setStdout(Boolean stdout) { this.stdout = stdout; } @JsonProperty("tty") public Boolean getTty() { return tty; } @JsonProperty("tty") public void setTty(Boolean tty) { this.tty = tty; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
/* * 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.phoenix.end2end; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_SEQUENCE; import static org.apache.phoenix.util.TestUtil.ATABLE_NAME; import static org.apache.phoenix.util.TestUtil.ATABLE_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.BTABLE_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_FULL_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_NAME; import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.GROUPBYTEST_NAME; import static org.apache.phoenix.util.TestUtil.MDTEST_NAME; import static org.apache.phoenix.util.TestUtil.MDTEST_SCHEMA_NAME; import static org.apache.phoenix.util.TestUtil.PHOENIX_JDBC_URL; import static org.apache.phoenix.util.TestUtil.PTSDB_NAME; import static org.apache.phoenix.util.TestUtil.STABLE_NAME; import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Properties; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.coprocessor.GroupedAggregateRegionObserver; import org.apache.phoenix.coprocessor.ServerCachingEndpointImpl; import org.apache.phoenix.coprocessor.UngroupedAggregateRegionObserver; import org.apache.phoenix.exception.SQLExceptionCode; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; import org.apache.phoenix.schema.ColumnNotFoundException; import org.apache.phoenix.schema.PDataType; import org.apache.phoenix.schema.PTable.ViewType; import org.apache.phoenix.schema.PTableType; import org.apache.phoenix.schema.ReadOnlyTableException; import org.apache.phoenix.schema.TableNotFoundException; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.SchemaUtil; import org.apache.phoenix.util.StringUtil; import org.apache.phoenix.util.TestUtil; import org.junit.Test; public class QueryDatabaseMetaDataIT extends BaseClientManagedTimeIT { @Test public void testTableMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), ATABLE_NAME, null, ts); ensureTableCreated(getUrl(), STABLE_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); DatabaseMetaData dbmd = conn.getMetaData(); String aTableName = StringUtil.escapeLike(TestUtil.ATABLE_NAME); String aSchemaName = TestUtil.ATABLE_SCHEMA_NAME; ResultSet rs = dbmd.getTables(null, aSchemaName, aTableName, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_NAME"),aTableName); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertEquals(rs.getString(3),aTableName); assertEquals(PTableType.TABLE.toString(), rs.getString(4)); assertFalse(rs.next()); rs = dbmd.getTables(null, null, null, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_NAME"),SYSTEM_CATALOG_TABLE); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_NAME"),TYPE_SEQUENCE); assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),ATABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),STABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); rs = dbmd.getTables(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString("TABLE_NAME"),CUSTOM_ENTITY_DATA_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertFalse(rs.next()); try { rs.getString("RANDOM_COLUMN_NAME"); fail(); } catch (ColumnNotFoundException e) { // expected } assertFalse(rs.next()); rs = dbmd.getTables(null, "", "_TABLE", new String[] {PTableType.TABLE.toString()}); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),ATABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),STABLE_NAME); assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE")); assertFalse(rs.next()); } @Test public void testSchemaMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getSchemas(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString("TABLE_CATALOG"),null); assertFalse(rs.next()); rs = dbmd.getSchemas(null, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_CATALOG"),null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),CUSTOM_ENTITY_DATA_SCHEMA_NAME); assertEquals(rs.getString("TABLE_CATALOG"),null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA); assertEquals(rs.getString("TABLE_CATALOG"),null); assertFalse(rs.next()); } @Test public void testColumnMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getColumns(null, "", MDTEST_NAME, null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNoNulls, rs.getShort("NULLABLE")); assertEquals(PDataType.CHAR.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(1, rs.getInt("ORDINAL_POSITION")); assertEquals(1, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.LONG.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(3, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(4, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(5, rs.getInt("ORDINAL_POSITION")); assertEquals(5, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(6, rs.getInt("ORDINAL_POSITION")); assertEquals(6, rs.getInt("COLUMN_SIZE")); assertEquals(3, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.next()); // Look up only columns in a column family rs = dbmd.getColumns(null, "", MDTEST_NAME, "A."); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertFalse(rs.next()); // Look up KV columns in a column family rs = dbmd.getColumns("", "", MDTEST_NAME, "%.COL%"); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.INTEGER.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(2, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.LONG.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(3, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(4, rs.getInt("ORDINAL_POSITION")); assertEquals(0, rs.getInt("COLUMN_SIZE")); assertTrue(rs.wasNull()); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(5, rs.getInt("ORDINAL_POSITION")); assertEquals(5, rs.getInt("COLUMN_SIZE")); assertEquals(0, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.wasNull()); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE")); assertEquals(PDataType.DECIMAL.getSqlType(), rs.getInt("DATA_TYPE")); assertEquals(6, rs.getInt("ORDINAL_POSITION")); assertEquals(6, rs.getInt("COLUMN_SIZE")); assertEquals(3, rs.getInt("DECIMAL_DIGITS")); assertFalse(rs.next()); // Look up KV columns in a column family rs = dbmd.getColumns("", "", MDTEST_NAME, "B.COL2"); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); } @Test public void testPrimaryKeyMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs; rs = dbmd.getPrimaryKeys(null, "", MDTEST_NAME); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(MDTEST_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertEquals(1, rs.getInt("KEY_SEQ")); assertEquals(null, rs.getString("PK_NAME")); assertFalse(rs.next()); rs = dbmd.getPrimaryKeys(null, CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"), rs.getString("COLUMN_NAME")); assertEquals(3, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertEquals(2, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("organization_id"), rs.getString("COLUMN_NAME")); assertEquals(1, rs.getInt("KEY_SEQ")); assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); // TODO: this is on the table row assertFalse(rs.next()); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, null); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("organization_id"), rs.getString("COLUMN_NAME")); assertEquals(rs.getInt("COLUMN_SIZE"), 15); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertEquals(rs.getInt("COLUMN_SIZE"), 3); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"), rs.getString("COLUMN_NAME")); // The above returns all columns, starting with the PK columns assertTrue(rs.next()); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, "KEY_PREFIX"); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); rs = dbmd.getColumns("", CUSTOM_ENTITY_DATA_SCHEMA_NAME, CUSTOM_ENTITY_DATA_NAME, "KEY_PREFIX"); assertTrue(rs.next()); assertEquals(CUSTOM_ENTITY_DATA_SCHEMA_NAME, rs.getString("TABLE_SCHEM")); assertEquals(CUSTOM_ENTITY_DATA_NAME, rs.getString("TABLE_NAME")); assertEquals(null, rs.getString("TABLE_CAT")); assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); } @Test public void testMultiTableColumnsMetadataScan() throws SQLException { long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); ensureTableCreated(getUrl(), GROUPBYTEST_NAME, null, ts); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts); ensureTableCreated(getUrl(), CUSTOM_ENTITY_DATA_FULL_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); DatabaseMetaData dbmd = conn.getMetaData(); ResultSet rs = dbmd.getColumns(null, "", "%TEST%", null); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(null, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("uri"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),GROUPBYTEST_NAME); assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("appcpu"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(null, rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME")); assertTrue(rs.next()); assertEquals(rs.getString("TABLE_SCHEM"),null); assertEquals(rs.getString("TABLE_NAME"),MDTEST_NAME); assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY")); assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME")); assertFalse(rs.next()); } @Test public void testCreateDropTable() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); ensureTableCreated(getUrl(), BTABLE_NAME, null, ts-2); ensureTableCreated(getUrl(), PTSDB_NAME, null, ts-2); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String query = "SELECT a_string FROM aTable"; // Data should still be there b/c we only dropped the schema props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); assertTrue(conn5.prepareStatement(query).executeQuery().next()); conn5.createStatement().executeUpdate("DROP TABLE " + ATABLE_NAME); // Confirm that data is no longer there because we dropped the table // This needs to be done natively b/c the metadata is gone HTableInterface htable = conn5.unwrap(PhoenixConnection.class).getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(ATABLE_SCHEMA_NAME, ATABLE_NAME)); Scan scan = new Scan(); scan.setFilter(new FirstKeyOnlyFilter()); scan.setTimeRange(0, ts+9); assertNull(htable.getScanner(scan).next()); conn5.close(); // Still should work b/c we're at an earlier timestamp than when table was deleted props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn2 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); Connection conn10 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { conn10.prepareStatement(query).executeQuery().next(); fail(); } catch (TableNotFoundException e) { } } @Test public void testCreateOnExistingTable() throws Exception { PhoenixConnection pconn = DriverManager.getConnection(PHOENIX_JDBC_URL, TEST_PROPERTIES).unwrap(PhoenixConnection.class); String tableName = MDTEST_NAME; String schemaName = MDTEST_SCHEMA_NAME; byte[] cfA = Bytes.toBytes(SchemaUtil.normalizeIdentifier("a")); byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b")); byte[] cfC = Bytes.toBytes("c"); byte[][] familyNames = new byte[][] {cfB, cfC}; byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName); HBaseAdmin admin = pconn.getQueryServices().getAdmin(); try { admin.disableTable(htableName); admin.deleteTable(htableName); admin.enableTable(htableName); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { } HTableDescriptor descriptor = new HTableDescriptor(htableName); for (byte[] familyName : familyNames) { HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName); descriptor.addFamily(columnDescriptor); } admin.createTable(descriptor); long ts = nextTimestamp(); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); PhoenixConnection conn1 = DriverManager.getConnection(PHOENIX_JDBC_URL, props).unwrap(PhoenixConnection.class); ensureTableCreated(getUrl(), tableName, null, ts); descriptor = admin.getTableDescriptor(htableName); assertEquals(3,descriptor.getColumnFamilies().length); HColumnDescriptor cdA = descriptor.getFamily(cfA); assertTrue(cdA.getKeepDeletedCells()); assertEquals(DataBlockEncoding.NONE, cdA.getDataBlockEncoding()); // Overriden using WITH assertEquals(1,cdA.getMaxVersions());// Overriden using WITH HColumnDescriptor cdB = descriptor.getFamily(cfB); assertFalse(cdB.getKeepDeletedCells()); // Allow KEEP_DELETED_CELLS to be false for VEIW assertEquals(DataBlockEncoding.NONE, cdB.getDataBlockEncoding()); // Should keep the original value. // CF c should stay the same since it's not a Phoenix cf. HColumnDescriptor cdC = descriptor.getFamily(cfC); assertNotNull("Column family not found", cdC); assertFalse(cdC.getKeepDeletedCells()); assertFalse(SchemaUtil.DEFAULT_DATA_BLOCK_ENCODING == cdC.getDataBlockEncoding()); assertTrue(descriptor.hasCoprocessor(UngroupedAggregateRegionObserver.class.getName())); assertTrue(descriptor.hasCoprocessor(GroupedAggregateRegionObserver.class.getName())); assertTrue(descriptor.hasCoprocessor(ServerCachingEndpointImpl.class.getName())); admin.close(); int rowCount = 5; String upsert = "UPSERT INTO " + tableName + "(id,col1,col2) VALUES(?,?,?)"; PreparedStatement ps = conn1.prepareStatement(upsert); for (int i = 0; i < rowCount; i++) { ps.setString(1, Integer.toString(i)); ps.setInt(2, i+1); ps.setInt(3, i+2); ps.execute(); } conn1.commit(); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String query = "SELECT count(1) FROM " + tableName; ResultSet rs = conn2.createStatement().executeQuery(query); assertTrue(rs.next()); assertEquals(rowCount, rs.getLong(1)); query = "SELECT id, col1,col2 FROM " + tableName; rs = conn2.createStatement().executeQuery(query); for (int i = 0; i < rowCount; i++) { assertTrue(rs.next()); assertEquals(Integer.toString(i),rs.getString(1)); assertEquals(i+1, rs.getInt(2)); assertEquals(i+2, rs.getInt(3)); } assertFalse(rs.next()); conn2.close(); } @Test public void testCreateViewOnExistingTable() throws Exception { PhoenixConnection pconn = DriverManager.getConnection(PHOENIX_JDBC_URL, TEST_PROPERTIES).unwrap(PhoenixConnection.class); String tableName = MDTEST_NAME; String schemaName = MDTEST_SCHEMA_NAME; byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b")); byte[] cfC = Bytes.toBytes("c"); byte[][] familyNames = new byte[][] {cfB, cfC}; byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName); HBaseAdmin admin = pconn.getQueryServices().getAdmin(); try { admin.disableTable(htableName); admin.deleteTable(htableName); admin.enableTable(htableName); } catch (org.apache.hadoop.hbase.TableNotFoundException e) { } finally { admin.close(); } HTableDescriptor descriptor = new HTableDescriptor(htableName); for (byte[] familyName : familyNames) { HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName); descriptor.addFamily(columnDescriptor); } admin.createTable(descriptor); long ts = nextTimestamp(); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String createStmt = "create view bogusTable" + " (id char(1) not null primary key,\n" + " a.col1 integer,\n" + " d.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (TableNotFoundException e) { // expected to fail b/c table doesn't exist } catch (ReadOnlyTableException e) { // expected to fail b/c table doesn't exist } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " a.col1 integer,\n" + " b.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c cf a doesn't exist } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " c.col2 bigint)\n"; try { conn1.createStatement().execute(createStmt); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c cf C doesn't exist (case issue) } createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) \n"; // should be ok now conn1.createStatement().execute(createStmt); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); PhoenixConnection conn2 = DriverManager.getConnection(PHOENIX_JDBC_URL, props).unwrap(PhoenixConnection.class); ResultSet rs = conn2.getMetaData().getTables(null, null, MDTEST_NAME, null); assertTrue(rs.next()); assertEquals(ViewType.MAPPED.name(), rs.getString(PhoenixDatabaseMetaData.VIEW_TYPE)); assertFalse(rs.next()); String deleteStmt = "DELETE FROM " + MDTEST_NAME; PreparedStatement ps = conn2.prepareStatement(deleteStmt); try { ps.execute(); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c table is read-only } try { String upsert = "UPSERT INTO " + MDTEST_NAME + "(id,col1,col2) VALUES(?,?,?)"; ps = conn2.prepareStatement(upsert); try { ps.setString(1, Integer.toString(0)); ps.setInt(2, 1); ps.setInt(3, 2); ps.execute(); fail(); } catch (ReadOnlyTableException e) { // expected to fail b/c table is read-only } conn2.createStatement().execute("ALTER VIEW " + MDTEST_NAME + " SET IMMUTABLE_ROWS=TRUE"); HTableInterface htable = conn2.getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(MDTEST_SCHEMA_NAME,MDTEST_NAME)); Put put = new Put(Bytes.toBytes("0")); put.add(cfB, Bytes.toBytes("COL1"), ts+6, PDataType.INTEGER.toBytes(1)); put.add(cfC, Bytes.toBytes("COL2"), ts+6, PDataType.LONG.toBytes(2)); htable.put(put); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10)); Connection conn7 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); // Should be ok b/c we've marked the view with IMMUTABLE_ROWS=true conn7.createStatement().execute("CREATE INDEX idx ON " + MDTEST_NAME + "(B.COL1)"); String select = "SELECT col1 FROM " + MDTEST_NAME + " WHERE col2=?"; ps = conn7.prepareStatement(select); ps.setInt(1, 2); rs = ps.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 12)); Connection conn75 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String dropTable = "DROP TABLE " + MDTEST_NAME ; ps = conn75.prepareStatement(dropTable); try { ps.execute(); fail(); } catch (TableNotFoundException e) { // expected to fail b/c it is a view } String dropView = "DROP VIEW " + MDTEST_NAME ; ps = conn75.prepareStatement(dropView); ps.execute(); conn75.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 15)); Connection conn8 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) IMMUTABLE_ROWS=true\n"; // should be ok to create a view with IMMUTABLE_ROWS = true conn8.createStatement().execute(createStmt); conn8.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 20)); Connection conn9 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); conn9.createStatement().execute("CREATE INDEX idx ON " + MDTEST_NAME + "(B.COL1)"); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 30)); Connection conn91 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); ps = conn91.prepareStatement(dropView); ps.execute(); conn91.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 35)); Connection conn92 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); createStmt = "create view " + MDTEST_NAME + " (id char(1) not null primary key,\n" + " b.col1 integer,\n" + " \"c\".col2 bigint) as\n" + " select * from " + MDTEST_NAME + " where b.col1 = 1"; conn92.createStatement().execute(createStmt); conn92.close(); put = new Put(Bytes.toBytes("1")); put.add(cfB, Bytes.toBytes("COL1"), ts+39, PDataType.INTEGER.toBytes(3)); put.add(cfC, Bytes.toBytes("COL2"), ts+39, PDataType.LONG.toBytes(4)); htable.put(put); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 40)); Connection conn92a = DriverManager.getConnection(PHOENIX_JDBC_URL, props); rs = conn92a.createStatement().executeQuery("select count(*) from " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(1,rs.getInt(1)); conn92a.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 45)); Connection conn93 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { String alterView = "alter view " + MDTEST_NAME + " drop column b.col1"; conn93.createStatement().execute(alterView); fail(); } catch (SQLException e) { assertEquals(SQLExceptionCode.CANNOT_MUTATE_TABLE.getErrorCode(), e.getErrorCode()); } conn93.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 50)); Connection conn94 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String alterView = "alter view " + MDTEST_NAME + " drop column \"c\".col2"; conn94.createStatement().execute(alterView); conn94.close(); } finally { HTableInterface htable = pconn.getQueryServices().getTable(SchemaUtil.getTableNameAsBytes(MDTEST_SCHEMA_NAME,MDTEST_NAME)); Delete delete1 = new Delete(Bytes.toBytes("0")); Delete delete2 = new Delete(Bytes.toBytes("1")); htable.batch(Arrays.asList(delete1, delete2)); } } @Test public void testAddKVColumnToExistingFamily() throws Throwable { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); // Failed attempt to repro table not found bug // TestUtil.clearMetaDataCache(conn1); // PhoenixConnection pconn = conn1.unwrap(PhoenixConnection.class); // pconn.removeTable(ATABLE_SCHEMA_NAME, ATABLE_NAME); conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_integer integer"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String query = "SELECT z_integer FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testAddKVColumnToNewFamily() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD newcf.z_integer integer"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String query = "SELECT z_integer FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testAddPKColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_string varchar not null primary key"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 1006 (42J04): Only nullable columns may be added to a multi-part row key.")); } conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD z_string varchar primary key"); conn1.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String query = "SELECT z_string FROM aTable"; assertTrue(conn2.prepareStatement(query).executeQuery().next()); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { conn3.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } } @Test public void testDropKVColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); assertTrue(conn5.createStatement().executeQuery("SELECT 1 FROM atable WHERE b_string IS NOT NULL").next()); conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN b_string"); conn5.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn2 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String query = "SELECT b_string FROM aTable"; try { conn2.prepareStatement(query).executeQuery().next(); fail(); } catch (ColumnNotFoundException e) { } conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); assertTrue(conn3.prepareStatement(query).executeQuery().next()); conn3.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 7)); Connection conn7 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); conn7.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " ADD b_string VARCHAR"); conn7.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); Connection conn8 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); assertFalse(conn8.createStatement().executeQuery("SELECT 1 FROM atable WHERE b_string IS NOT NULL").next()); conn8.close(); } @Test public void testDropPKColumn() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, getDefaultSplits(tenantId), null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn1 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); try { conn1.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN entity_id"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 506 (42817): Primary key column may not be dropped.")); } conn1.close(); } @Test public void testDropAllKVCols() throws Exception { ResultSet rs; long ts = nextTimestamp(); ensureTableCreated(getUrl(), MDTEST_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn2 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); conn2.createStatement().executeUpdate("UPSERT INTO " + MDTEST_NAME + " VALUES('a',1,1)"); conn2.createStatement().executeUpdate("UPSERT INTO " + MDTEST_NAME + " VALUES('b',2,2)"); conn2.commit(); conn2.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 3)); Connection conn3 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); rs = conn3.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn3.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); conn5.createStatement().executeUpdate("ALTER TABLE " + MDTEST_NAME + " DROP COLUMN col1"); conn5.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 6)); Connection conn6 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); rs = conn6.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn6.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 7)); Connection conn7 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); conn7.createStatement().executeUpdate("ALTER TABLE " + MDTEST_NAME + " DROP COLUMN col2"); conn7.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 8)); Connection conn8 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); rs = conn8.createStatement().executeQuery("SELECT count(1) FROM " + MDTEST_NAME); assertTrue(rs.next()); assertEquals(2, rs.getLong(1)); conn8.close(); } @Test public void testNewerTableDisallowed() throws Exception { long ts = nextTimestamp(); ensureTableCreated(getUrl(), ATABLE_NAME, null, ts); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5)); Connection conn5 = DriverManager.getConnection(PHOENIX_JDBC_URL, props); conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN x_integer"); try { conn5.createStatement().executeUpdate("ALTER TABLE " + ATABLE_NAME + " DROP COLUMN y_integer"); fail(); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 1013 (42M04): Table already exists. tableName=ATABLE")); } conn5.close(); } }
/******************************************************************************* * Copyright 2016, 2018 vanilladb.org contributors * * 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.vanilladb.core.server; import static org.vanilladb.core.sql.Type.INTEGER; import static org.vanilladb.core.sql.Type.VARCHAR; import java.io.File; import java.sql.Connection; import java.util.logging.Level; import java.util.logging.Logger; import org.vanilladb.core.sql.Constant; import org.vanilladb.core.sql.IntegerConstant; import org.vanilladb.core.sql.Schema; import org.vanilladb.core.sql.Type; import org.vanilladb.core.sql.VarcharConstant; import org.vanilladb.core.storage.file.BlockId; import org.vanilladb.core.storage.file.FileMgr; import org.vanilladb.core.storage.file.Page; import org.vanilladb.core.storage.metadata.CatalogMgr; import org.vanilladb.core.storage.metadata.TableInfo; import org.vanilladb.core.storage.metadata.statistics.StatMgr; import org.vanilladb.core.storage.record.RecordFile; import org.vanilladb.core.storage.tx.Transaction; import org.vanilladb.core.storage.tx.recovery.RecoveryMgr; public class ServerInit { private static Logger logger = Logger.getLogger(ServerInit.class.getName()); public static int courseMax = 300, studentMax = 900, deptMax = 40, sectMax = 1200, enrollMax = 2000; public static final String DB_MAIN_DIR = "vanilladb_testdbs"; // Flags private static final BlockId FLAG_DATA_BLOCK = new BlockId("testing_flags", 0); private static final int LOADED_FLAG_POS = 0; private static final Type LOADED_FLAG_TYPE = Type.INTEGER; private static final Constant DATA_LOADED_VALUE = new IntegerConstant(1); public static String resetDb(Class<?> testClass) { String testClassName = testClass.getName(); String dbName = DB_MAIN_DIR + "/" + testClassName; // Creates the main directory if it was not created before File dbPath = new File(FileMgr.DB_FILES_DIR, DB_MAIN_DIR); if (!dbPath.exists()) dbPath.mkdir(); // Deletes the existing database deleteDB(dbName); return dbName; } /** * Initiates {@link VanillaDb}. * * <p> * Note that for each test class, members (e.g., static fields, * constructors, etc) of all VanillaDb classes should be accessed after * calling this method to ensure the proper class loading. * </p> */ public static void init(Class<?> testClass) { String dbName = resetDb(testClass); // Initializes a fresh database VanillaDb.init(dbName); } /** * Set up a database for testing. */ public static void loadTestbed() { if (!checkIfTestbedLoaded()) { if (logger.isLoggable(Level.INFO)) logger.info("loading data"); CatalogMgr md = VanillaDb.catalogMgr(); StatMgr stat = VanillaDb.statMgr(); Transaction tx = VanillaDb.txMgr().newTransaction( Connection.TRANSACTION_SERIALIZABLE, false); // create and populate the course table Schema sch = new Schema(); sch.addField("cid", INTEGER); sch.addField("title", VARCHAR(20)); sch.addField("deptid", INTEGER); md.createTable("course", sch, tx); TableInfo ti = md.getTableInfo("course", tx); RecordFile rf = ti.open(tx, true); rf.beforeFirst(); while (rf.next()) rf.delete(); rf.close(); rf = ti.open(tx, true); for (int id = 0; id < courseMax; id++) { rf.insert(); IntegerConstant cid = new IntegerConstant(id); rf.setVal("cid", cid); rf.setVal("title", new VarcharConstant("course" + id)); rf.setVal("deptid", new IntegerConstant(id % deptMax)); } rf.close(); // refresh the statistical information after populating this table stat.getTableStatInfo(ti, tx); // create and populate the student table sch = new Schema(); sch.addField("sid", INTEGER); sch.addField("sname", VARCHAR(10)); sch.addField("majorid", INTEGER); sch.addField("gradyear", INTEGER); md.createTable("student", sch, tx); ti = md.getTableInfo("student", tx); rf = ti.open(tx, true); rf.beforeFirst(); while (rf.next()) rf.delete(); rf.close(); rf = ti.open(tx, true); for (int id = 0; id < studentMax; id++) { rf.insert(); IntegerConstant sid = new IntegerConstant(id); rf.setVal("sid", sid); rf.setVal("sname", new VarcharConstant("student" + id)); rf.setVal("majorid", new IntegerConstant(id % deptMax)); rf.setVal("gradyear", new IntegerConstant((id % 50) + 1960)); } rf.close(); // refresh the statistical information after populating this table stat.getTableStatInfo(ti, tx); // create and populate the dept table sch = new Schema(); sch.addField("did", INTEGER); sch.addField("dname", VARCHAR(8)); md.createTable("dept", sch, tx); ti = md.getTableInfo("dept", tx); rf = ti.open(tx, true); rf.beforeFirst(); while (rf.next()) rf.delete(); rf.close(); rf = ti.open(tx, true); for (int id = 0; id < deptMax; id++) { rf.insert(); IntegerConstant did = new IntegerConstant(id); rf.setVal("did", did); rf.setVal("dname", new VarcharConstant("dept" + id)); } rf.close(); // refresh the statistical information after populating this table stat.getTableStatInfo(ti, tx); // create and populate the section table sch = new Schema(); sch.addField("sectid", INTEGER); sch.addField("prof", VARCHAR(8)); sch.addField("courseid", INTEGER); sch.addField("yearoffered", INTEGER); md.createTable("section", sch, tx); ti = md.getTableInfo("section", tx); rf = ti.open(tx, true); rf.beforeFirst(); while (rf.next()) rf.delete(); rf.close(); rf = ti.open(tx, true); for (int id = 0; id < sectMax; id++) { rf.insert(); IntegerConstant sectid = new IntegerConstant(id); rf.setVal("sectid", sectid); int profnum = id % 20; rf.setVal("prof", new VarcharConstant("prof" + profnum)); rf.setVal("courseid", new IntegerConstant(id % courseMax)); rf.setVal("yearoffered", new IntegerConstant((id % 50) + 1960)); } rf.close(); // refresh the statistical information after populating this table stat.getTableStatInfo(ti, tx); // create and populate the enroll table sch = new Schema(); sch.addField("eid", INTEGER); sch.addField("grade", VARCHAR(2)); sch.addField("studentid", INTEGER); sch.addField("sectionid", INTEGER); md.createTable("enroll", sch, tx); ti = md.getTableInfo("enroll", tx); rf = ti.open(tx, true); rf.beforeFirst(); while (rf.next()) rf.delete(); rf.close(); rf = ti.open(tx, true); String[] grades = new String[] { "A", "B", "C", "D", "F" }; for (int id = 0; id < enrollMax; id++) { rf.insert(); IntegerConstant eid = new IntegerConstant(id); rf.setVal("eid", eid); rf.setVal("grade", new VarcharConstant(grades[id % 5])); rf.setVal("studentid", new IntegerConstant(id % studentMax)); rf.setVal("sectionid", new IntegerConstant(id % sectMax)); } rf.close(); // refresh the statistical information after populating this table stat.getTableStatInfo(ti, tx); tx.commit(); // add a checkpoint record to limit rollback tx = VanillaDb.txMgr().newTransaction( Connection.TRANSACTION_SERIALIZABLE, false); RecoveryMgr.initializeSystem(tx); tx.commit(); // Set the flag indicating that the data is loaded setFlagAsLoaded(); } } private static void deleteDB(String dbName) { File dbPath = new File(FileMgr.DB_FILES_DIR, dbName); if (dbPath.exists()) { File[] files = dbPath.listFiles(); for (File file : files) { if (!file.delete()) throw new RuntimeException("cannot delete the file: " + file); } if (!dbPath.delete()) throw new RuntimeException("cannot delete the directory: " + dbPath); } } private static void setFlagAsLoaded() { Page page = new Page(); page.setVal(LOADED_FLAG_POS, DATA_LOADED_VALUE); page.write(FLAG_DATA_BLOCK); } private static boolean checkIfTestbedLoaded() { Page page = new Page(); page.read(FLAG_DATA_BLOCK); Constant isLoaded = page.getVal(LOADED_FLAG_POS, LOADED_FLAG_TYPE); if (isLoaded.equals(DATA_LOADED_VALUE)) return true; return false; } }
package com.sequenceiq.environment.resourcepersister; import java.util.List; import java.util.Optional; import javax.transaction.Transactional; import javax.transaction.Transactional.TxType; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; @Transactional(TxType.REQUIRED) public interface ResourceRepository extends CrudRepository<Resource, Long> { @Query("SELECT r FROM Resource r WHERE r.crn = :crn AND r.resourceName = :name AND r.resourceType = :type") Optional<Resource> findByStackIdAndNameAndType(@Param("crn") String crnId, @Param("name") String name, @Param("type") com.sequenceiq.environment.resourcepersister.ResourceType type); @Query("SELECT r FROM Resource r WHERE r.crn = :crn") List<Resource> findAllByStackId(@Param("crn") String crn); }
package lesson12; public class Lesson12 { public static void main(String[] args) { Mammal m = new Mammal(); Kangoroo k = new Kangoroo(); Dog d = new Dog(); System.out.println("==================="); m.setWeight(5.70f); m.setAge(8); m.setMembers(4); m.move(); m.eat(); m.emitSound(); System.out.println("==================="); k.setWeight(55.30f); k.setAge(3); k.setMembers(4); k.move(); k.eat(); k.emitSound(); k.useBag(); System.out.println("==================="); d.setWeight(3.94f); d.setAge(5); d.setPelageColor("Marrom"); d.setMembers(4); d.move(); d.eat(); d.emitSound(); d.wagTail(); System.out.println("==================="); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.oozie.service; import org.apache.oozie.test.XTestCase; public class TestInstrumentationService extends XTestCase { public void testInstrumentation() throws Exception { Services services = new Services(); services.init(); assertNotNull(services.get(InstrumentationService.class)); assertNotNull(services.get(InstrumentationService.class).get()); services.destroy(); } }
package com.opsunv.mt4.api; import com.opsunv.mt4.api.bean.TradeRecord; import com.opsunv.mt4.api.exception.InitFailedException; public class MT4 implements ManagerAPI{ //manager的指针地址 private int ptr; public MT4() { ptr = init(); if(ptr<0){ throw new InitFailedException(); } } /** * 初始化 * @return 返回CManagerInterface实例的地址 */ private native int init(); /** * 释放manager实例 * @param ptr * @return */ private native int Release(int ptr); /** * 获取错误信息 * @param ptr * @param code * @return */ private native String ErrorDescription(int ptr,int code); /** * 连接到服务端 * @param ptr * @param server * @return */ private native int Connect(int ptr,String server); /** * 断开链接 * @param ptr * @return */ private native int Disconnect(int ptr); /** * 是否连接 * @param ptr * @return */ private native int IsConnected(int ptr); /** * 登陆 * @param ptr * @param uid * @param password * @return */ private native int Login(int ptr,int uid,String password); //orders /** * 交易信息 * @param ptr * @return */ private native TradeRecord[] TradesRequest(int ptr); private native TradeRecord[] TradesUserHistory(int ptr); /** * 加载socket */ private static native void WinsockStartup(); static{ System.loadLibrary("MT4Wrapper"); WinsockStartup(); } @Override public int release() { return Release(ptr); } @Override public String getErrorDescription(int code) { return ErrorDescription(ptr,code); } @Override public int connect(String server) { return Connect(ptr, server); } @Override public int disconnect() { return Disconnect(ptr); } @Override public boolean isConnected() { return IsConnected(ptr)==1; } @Override public int login(int uid, String password) { return Login(ptr, uid, password); } @Override public TradeRecord[] getTradesRequest() { return TradesRequest(ptr); } @Override public TradeRecord[] getTradesUserHistory() { return null; } }
/* * Copyright 2021 Collate * 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.openmetadata.catalog.jdbi3; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; import org.jdbi.v3.sqlobject.transaction.Transaction; import org.openmetadata.catalog.Entity; import org.openmetadata.catalog.type.DailyCount; import org.openmetadata.catalog.type.EntityReference; import org.openmetadata.catalog.type.EntityUsage; import org.openmetadata.catalog.type.UsageDetails; import org.openmetadata.catalog.type.UsageStats; import org.openmetadata.catalog.util.EntityUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.UUID; public class UsageRepository { private static final Logger LOG = LoggerFactory.getLogger(UsageRepository.class); private final CollectionDAO dao; public UsageRepository(CollectionDAO dao) { this.dao = dao; } @Transaction public EntityUsage get(String entityType, String id, String date, int days) throws IOException { EntityReference ref = Entity.getEntityReference(entityType, UUID.fromString(id)); List<UsageDetails> usageDetails = dao.usageDAO().getUsageById(id, date, days - 1); return new EntityUsage().withUsage(usageDetails).withEntity(ref); } @Transaction public EntityUsage getByName(String entityType, String fqn, String date, int days) throws IOException { EntityReference ref = Entity.getEntityReferenceByName(entityType, fqn); List<UsageDetails> usageDetails = dao.usageDAO().getUsageById(ref.getId().toString(), date, days - 1); return new EntityUsage().withUsage(usageDetails).withEntity(ref); } @Transaction public void create(String entityType, String id, DailyCount usage) throws IOException { // Validate data entity for which usage is being collected Entity.getEntityReference(entityType, UUID.fromString(id)); addUsage(entityType, id, usage); } @Transaction public void createByName(String entityType, String fullyQualifiedName, DailyCount usage) throws IOException { EntityReference ref = Entity.getEntityReferenceByName(entityType, fullyQualifiedName); addUsage(entityType, ref.getId().toString(), usage); LOG.info("Usage successfully posted by name"); } @Transaction public void computePercentile(String entityType, String date) { dao.usageDAO().computePercentile(entityType, date); } private void addUsage(String entityType, String entityId, DailyCount usage) { // Insert usage record dao.usageDAO().insert(usage.getDate(), entityId, entityType, usage.getCount()); // If table usage was reported, add the usage count to database if (entityType.equalsIgnoreCase(Entity.TABLE)) { List<String> databaseIds = dao.relationshipDAO().findFrom(entityId, Relationship.CONTAINS.ordinal(), Entity.DATABASE); dao.usageDAO().insertOrUpdateCount(usage.getDate(), databaseIds.get(0), Entity.DATABASE, usage.getCount()); } } public static class UsageDetailsMapper implements RowMapper<UsageDetails> { @Override public UsageDetails map(ResultSet r, StatementContext ctx) throws SQLException { UsageStats dailyStats = new UsageStats().withCount(r.getInt("count1")).withPercentileRank(r.getDouble( "percentile1")); UsageStats weeklyStats = new UsageStats().withCount(r.getInt("count7")).withPercentileRank(r.getDouble( "percentile7")); UsageStats monthlyStats = new UsageStats().withCount(r.getInt("count30")).withPercentileRank(r.getDouble( "percentile30")); return new UsageDetails().withDate(r.getString("usageDate")).withDailyStats(dailyStats) .withWeeklyStats(weeklyStats).withMonthlyStats(monthlyStats); } } }
package io.swagger.v3.core.filter.resources; import io.swagger.v3.core.filter.AbstractSpecFilter; import io.swagger.v3.oas.models.OpenAPI; import java.util.List; import java.util.Map; import java.util.Optional; /** * Does nothing **/ public class NoOpenAPIFilter extends AbstractSpecFilter { public static final String VERSION = "3.0.1"; @Override public Optional<OpenAPI> filterOpenAPI(OpenAPI openAPI, Map<String, List<String>> params, Map<String, List<String>> cookies, Map<String, List<String>> headers) { if (VERSION.equals(openAPI.getOpenapi())) { return Optional.empty(); } return Optional.of(openAPI); } }
package com.rohan.dp.visitor.solution.ex1; public class HighlightOperation implements Operation { @Override public void apply(HeadingNode heading) { System.out.println("highlight-heading"); } @Override public void apply(AnchorNode anchor) { System.out.println("highlight-anchor"); } }
package com.github.fcannizzaro.materialstepper.util; import com.github.fcannizzaro.materialstepper.AbstractStep; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Francesco Cannizzaro (fcannizzaro). */ public class StepUtils { private ArrayList<AbstractStep> mSteps = new ArrayList<>(); private ArrayList<Boolean> mActiveDots = new ArrayList<>(); private int mCurrent; public ArrayList<AbstractStep> getSteps() { return mSteps; } public AbstractStep get(int position) { return mSteps.get(position); } public boolean isActive(int i) { return mActiveDots.get(i); } public boolean setActive(int i, boolean set) { return mActiveDots.set(i, set); } public AbstractStep getCurrent() { return get(mCurrent); } public int total() { return mSteps.size(); } public void add(AbstractStep step) { mSteps.add(step); mActiveDots.add(false); } public void addAll(List<AbstractStep> mSteps) { this.mSteps.addAll(mSteps); Collections.fill(mActiveDots, false); } public void current(int mCurrent) { this.mCurrent = mCurrent; } public int current() { return mCurrent; } }
/* * #%L * ImgLib2: a general-purpose, multidimensional image processing library. * %% * Copyright (C) 2009 - 2021 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld, * John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke, * Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner, * Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert, * Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin, * Jean-Yves Tinevez and Michael Zinsmaier. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * 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 HOLDERS 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. * #L% */ package net.imglib2.algorithm.tree; /** * A tree. * * @param <T> * the node type * * @author Tobias Pietzsch */ public interface Tree< T extends TreeNode< T > > extends Forest< T > { /** * Get the root component. * * @return root component. */ public T root(); }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.structureView.newStructureView; import com.intellij.ide.CopyPasteUtil; import com.intellij.ide.structureView.ModelListener; import com.intellij.ide.structureView.StructureViewModel; import com.intellij.ide.structureView.StructureViewTreeElement; import com.intellij.ide.util.treeView.*; import com.intellij.ide.util.treeView.smartTree.SmartTreeStructure; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.util.StatusBarProgress; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.Alarm; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.tree.DefaultTreeModel; public class StructureTreeBuilder extends AbstractTreeBuilder { private final Project myProject; private final StructureViewModel myStructureModel; private final CopyPasteUtil.DefaultCopyPasteListener myCopyPasteListener; private final PsiTreeChangeListener myPsiTreeChangeListener; private final ModelListener myModelListener; private final Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, this); public StructureTreeBuilder(Project project, JTree tree, DefaultTreeModel treeModel, AbstractTreeStructure treeStructure, StructureViewModel structureModel) { super( tree, treeModel, treeStructure, null, false ); myProject = project; myStructureModel = structureModel; myPsiTreeChangeListener = new MyPsiTreeChangeListener(); myModelListener = new ModelListener() { @Override public void onModelChanged() { addRootToUpdate(); } }; PsiManager.getInstance(myProject).addPsiTreeChangeListener(myPsiTreeChangeListener); myCopyPasteListener = new CopyPasteUtil.DefaultCopyPasteListener(getUpdater()); CopyPasteManager.getInstance().addContentChangedListener(myCopyPasteListener); initRootNode(); myStructureModel.addModelListener(myModelListener); setCanYieldUpdate(!ApplicationManager.getApplication().isUnitTestMode()); } @Override public final void dispose() { PsiManager.getInstance(myProject).removePsiTreeChangeListener(myPsiTreeChangeListener); CopyPasteManager.getInstance().removeContentChangedListener(myCopyPasteListener); myStructureModel.removeModelListener(myModelListener); super.dispose(); } @Override protected final boolean isAlwaysShowPlus(NodeDescriptor nodeDescriptor) { return ((AbstractTreeNode)nodeDescriptor).isAlwaysShowPlus(); } @Override protected final boolean isAutoExpandNode(NodeDescriptor nodeDescriptor) { StructureViewModel model = myStructureModel; if (model instanceof TreeModelWrapper) { model = ((TreeModelWrapper) model).getModel(); } if (model instanceof StructureViewModel.ExpandInfoProvider) { StructureViewModel.ExpandInfoProvider provider = (StructureViewModel.ExpandInfoProvider)model; Object element = nodeDescriptor.getElement(); StructureViewTreeElement value = null; if (element instanceof StructureViewComponent.StructureViewTreeElementWrapper) { StructureViewComponent.StructureViewTreeElementWrapper wrapper = (StructureViewComponent.StructureViewTreeElementWrapper)element; if (wrapper.getValue() instanceof StructureViewTreeElement) { value = (StructureViewTreeElement)wrapper.getValue(); } } if (value != null) { return provider.isAutoExpand(value); } } // expand root node & its immediate children final NodeDescriptor parent = nodeDescriptor.getParentDescriptor(); return super.isAutoExpandNode(parent == null ? nodeDescriptor : parent); } @Override protected final boolean isSmartExpand() { StructureViewModel model = myStructureModel; if (model instanceof TreeModelWrapper) { model = ((TreeModelWrapper) model).getModel(); } if (model instanceof StructureViewModel.ExpandInfoProvider) { return ((StructureViewModel.ExpandInfoProvider)model).isSmartExpand(); } return false; } @Override @NotNull protected final ProgressIndicator createProgressIndicator() { return new StatusBarProgress(); } private final class MyPsiTreeChangeListener extends PsiTreeChangeAdapter { private final PsiModificationTracker myModificationTracker; private long myOutOfCodeBlockModificationCount; private MyPsiTreeChangeListener() { myModificationTracker = PsiManager.getInstance(myProject).getModificationTracker(); myOutOfCodeBlockModificationCount = myModificationTracker.getOutOfCodeBlockModificationCount(); } @Override public void childRemoved(@NotNull PsiTreeChangeEvent event) { PsiElement child = event.getOldChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } @Override public void childAdded(@NotNull PsiTreeChangeEvent event) { PsiElement child = event.getNewChild(); if (child instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } @Override public void childReplaced(@NotNull PsiTreeChangeEvent event) { /** Test comment */ PsiElement oldChild = event.getOldChild(); PsiElement newChild = event.getNewChild(); if (oldChild instanceof PsiWhiteSpace && newChild instanceof PsiWhiteSpace) return; //optimization childrenChanged(); } @Override public void childMoved(@NotNull PsiTreeChangeEvent event) { childrenChanged(); } @Override public void childrenChanged(@NotNull PsiTreeChangeEvent event) { childrenChanged(); } private void childrenChanged() { long newModificationCount = myModificationTracker.getOutOfCodeBlockModificationCount(); if (newModificationCount == myOutOfCodeBlockModificationCount) return; myOutOfCodeBlockModificationCount = newModificationCount; setupUpdateAlarm(); } @Override public void propertyChanged(@NotNull PsiTreeChangeEvent event) { childrenChanged(); } } private void setupUpdateAlarm() { myUpdateAlarm.cancelAllRequests(); myUpdateAlarm.addRequest(new Runnable() { @Override public void run() { if (!isDisposed() && !myProject.isDisposed()) { addRootToUpdate(); } } }, 300, ModalityState.stateForComponent(getTree())); } final void addRootToUpdate() { final AbstractTreeStructure structure = getTreeStructure(); structure.asyncCommit().doWhenDone(new Runnable() { @Override public void run() { ((SmartTreeStructure)structure).rebuildTree(); getUpdater().addSubtreeToUpdate(getRootNode()); } }); } @Override @NotNull protected final AbstractTreeNode createSearchingTreeNodeWrapper() { return new StructureViewComponent.StructureViewTreeElementWrapper(null,null, 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.pig.backend.hadoop.executionengine.spark.converter; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POCollectedGroup; import org.apache.pig.backend.hadoop.executionengine.spark.FlatMapFunctionAdapter; import org.apache.pig.backend.hadoop.executionengine.spark.SparkShims; import org.apache.pig.backend.hadoop.executionengine.spark.SparkUtil; import org.apache.pig.data.Tuple; import org.apache.spark.rdd.RDD; @SuppressWarnings({"serial"}) public class CollectedGroupConverter implements RDDConverter<Tuple, Tuple, POCollectedGroup> { @Override public RDD<Tuple> convert(List<RDD<Tuple>> predecessors, POCollectedGroup physicalOperator) throws IOException { SparkUtil.assertPredecessorSize(predecessors, physicalOperator, 1); RDD<Tuple> rdd = predecessors.get(0); CollectedGroupFunction collectedGroupFunction = new CollectedGroupFunction(physicalOperator); return rdd.toJavaRDD().mapPartitions(SparkShims.getInstance().flatMapFunction(collectedGroupFunction), true) .rdd(); } private static class CollectedGroupFunction implements FlatMapFunctionAdapter<Iterator<Tuple>, Tuple> { private POCollectedGroup poCollectedGroup; public long current_val; private CollectedGroupFunction(POCollectedGroup poCollectedGroup) { this.poCollectedGroup = poCollectedGroup; this.current_val = 0; } @Override public Iterator<Tuple> call(final Iterator<Tuple> input) { return new OutputConsumerIterator(input) { @Override protected void attach(Tuple tuple) { poCollectedGroup.setInputs(null); poCollectedGroup.attachInput(tuple); } @Override protected Result getNextResult() throws ExecException { return poCollectedGroup.getNextTuple(); } @Override protected void endOfInput() { poCollectedGroup.setEndOfInput(true); } }; } } }
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.dogecoin.net; import java.util.Timer; import java.util.TimerTask; /** * <p>A base class which provides basic support for socket timeouts. It is used instead of integrating timeouts into the * NIO select thread both for simplicity and to keep code shared between NIO and blocking sockets as much as possible. * </p> */ public abstract class AbstractTimeoutHandler { // TimerTask and timeout value which are added to a timer to kill the connection on timeout private TimerTask timeoutTask; private long timeoutMillis = 0; private boolean timeoutEnabled = true; // A timer which manages expiring channels as their timeouts occur (if configured). private static final Timer timeoutTimer = new Timer("AbstractTimeoutHandler timeouts", true); /** * <p>Enables or disables the timeout entirely. This may be useful if you want to store the timeout value but wish * to temporarily disable/enable timeouts.</p> * * <p>The default is for timeoutEnabled to be true but timeoutMillis to be set to 0 (ie disabled).</p> * * <p>This call will reset the current progress towards the timeout.</p> */ public synchronized void setTimeoutEnabled(boolean timeoutEnabled) { this.timeoutEnabled = timeoutEnabled; resetTimeout(); } /** * <p>Sets the receive timeout to the given number of milliseconds, automatically killing the connection if no * messages are received for this long</p> * * <p>A timeout of 0 is interpreted as no timeout.</p> * * <p>The default is for timeoutEnabled to be true but timeoutMillis to be set to 0 (ie disabled).</p> * * <p>This call will reset the current progress towards the timeout.</p> */ public synchronized void setSocketTimeout(int timeoutMillis) { this.timeoutMillis = timeoutMillis; resetTimeout(); } /** * Resets the current progress towards timeout to 0. */ protected synchronized void resetTimeout() { if (timeoutTask != null) timeoutTask.cancel(); if (timeoutMillis == 0 || !timeoutEnabled) return; timeoutTask = new TimerTask() { @Override public void run() { timeoutOccurred(); } }; timeoutTimer.schedule(timeoutTask, timeoutMillis); } protected abstract void timeoutOccurred(); }
/* Copyright 2000- Francois de Bertrand de Beuvron This file is part of CoursBeuvron. CoursBeuvron 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, either version 3 of the License, or (at your option) any later version. CoursBeuvron 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 CoursBeuvron. If not, see <http://www.gnu.org/licenses/>. */ package fr.insa.beuvron.web.amour.vues; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.html.Paragraph; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.textfield.TextField; import fr.insa.beuvron.web.amour.VuePrincipale; import fr.insa.beuvron.web.amour.bdd.Aime; import java.sql.SQLException; /** * * @author francois */ public class DefConnectionBDD extends MyVerticalLayout { private VuePrincipale main; private TextField vtHost; private TextField vtPort; private TextField vtDatabase; private TextField vtUser; private TextField vtPass; private Button vbRetryConnect; public DefConnectionBDD(VuePrincipale main) { this.main = main; Paragraph note = new Paragraph("Note : normalement ce panneau ne devrait pas faire partie " + "de l'interface web. Il est inclu ici pour s'adapter au diverses " + "configurations des ordinateurs des étudiants"); note.getStyle().set("font-family", "Monospace") .set("font-size", "0.8em").set("color", "red") .set("font-style", "italic"); this.add(note); this.getStyle().set("border", "2px solid " + "red"); this.vtHost = new TextField("host"); this.vtHost.setValue("localhost"); this.vtPort = new TextField("port"); this.vtPort.setValue("5439"); this.vtDatabase = new TextField("database"); this.vtDatabase.setValue("postgres"); this.vtUser = new TextField("user"); this.vtUser.setValue("postgres"); this.vtPass = new TextField("password"); this.vtPass.setValue("pass"); this.vbRetryConnect = new Button("retenter de se connecter"); this.vbRetryConnect.addClickListener((event) -> { try { this.main.getSessionInfo().setConBdD( Aime.connectGeneralPostGres( this.vtHost.getValue(), Integer.parseInt(this.vtPort.getValue()), this.vtDatabase.getValue(), this.vtUser.getValue(), this.vtPass.getValue())); this.main.setEntete(new InitialLoginEntete(this.main)); this.main.setMainContent(new BienvenueMainVue(this.main)); } catch (ClassNotFoundException | SQLException ex) { Notification.show("Problème : " + ex.getLocalizedMessage()); } }); this.add(vtHost, vtPort, vtDatabase, vtUser, vtPass, vbRetryConnect); } }
package dev.paddock.adp.mCubed.scrobble; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.http.NameValuePair; import dev.paddock.adp.mCubed.utilities.Log; import dev.paddock.adp.mCubed.utilities.Utilities; public abstract class ScrobbleRequest<TResponse extends ScrobbleResponse> { private final List<ScrobbleKeyValuePair> scrobblePairs = new ArrayList<ScrobbleKeyValuePair>(); private static final String API_KEY = "06bd23c697c83e151b2447c204f9c9bb"; private static final String API_SECRET = "7763946374c097697b86e23d148cf46b"; private final Class<TResponse> responseClass; public ScrobbleRequest(Class<TResponse> responseClass) { this.responseClass = responseClass; setupCommonPairs(); } private void setupCommonPairs() { setValue("api_key", API_KEY); setValue("method", getMethod()); if (requiresSessionKey()) { String sessionKey = ScrobbleService.getSessionKey(); if (!Utilities.isNullOrEmpty(sessionKey)) { setValue("sk", sessionKey); } } } private String calculateSignature() { StringBuilder builder = new StringBuilder(); Collections.sort(scrobblePairs, new ScrobbleKeyValuePairComparator()); for (ScrobbleKeyValuePair pair : scrobblePairs) { if (!pair.getKey().equals("api_sig")) { Object value = pair.getValue(); builder.append(pair.getKey()); builder.append(value == null ? "" : value.toString()); } } builder.append(API_SECRET); try { byte[] bytes = builder.toString().getBytes("UTF-8"); byte[] hashedBytes = MessageDigest.getInstance("MD5").digest(bytes); StringBuilder hashedBuilder = new StringBuilder(2 * hashedBytes.length); for (byte hashedByte : hashedBytes) { hashedBuilder.append(String.format("%02x", hashedByte & 0xff)); } return hashedBuilder.toString(); } catch (Exception e) { Log.e(e); return null; } } private void updateSignature() { setValue("api_sig", calculateSignature()); } public List<NameValuePair> createParameters() { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); updateSignature(); for (ScrobbleKeyValuePair pair : scrobblePairs) { parameters.add(pair.createNameValuePair()); } return parameters; } public Class<TResponse> getResponseClass() { return responseClass; } public List<ScrobbleKeyValuePair> getScrobblePairs() { return Collections.unmodifiableList(scrobblePairs); } public <T> T getValue(Class<T> clazz, String key) { for (ScrobbleKeyValuePair pair : scrobblePairs) { if (pair.getKey().equals(key)) { return Utilities.cast(clazz, pair.getValue()); } } return null; } public void setValue(String key, Object value) { for (ScrobbleKeyValuePair pair : scrobblePairs) { if (pair.getKey().equals(key)) { pair.setValue(value); return; } } scrobblePairs.add(new ScrobbleKeyValuePair(key, value)); } protected boolean requiresSessionKey() { return true; } public abstract String getMethod(); }
package Lexer.TransitionMatrix.SemanticActions; import Lexer.Token; import Lexer.WrapperCode; public interface SemanticAction { Token execute(WrapperCode code, String lexeme); }
package seedu.siasa.logic.commands.client; import static java.util.Objects.requireNonNull; import java.util.List; import seedu.siasa.commons.core.Messages; import seedu.siasa.commons.core.index.Index; import seedu.siasa.logic.commands.Command; import seedu.siasa.logic.commands.CommandResult; import seedu.siasa.logic.commands.exceptions.CommandException; import seedu.siasa.model.Model; import seedu.siasa.model.person.Person; import seedu.siasa.model.policy.Policy; import seedu.siasa.model.policy.PolicyIsOwnedByPredicate; /** * Deletes a client's policies identified using it's displayed index from the client list. */ public class ClearClientPolicyCommand extends Command { public static final String COMMAND_WORD = "clearpolicy"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Deletes the policies belonging to a client as given by the " + "index number used in the displayed user list.\n" + "Parameters: INDEX (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " 1"; public static final String MESSAGE_CLEAR_CLIENT_POLICY_SUCCESS = "Deleted %1$s policies belonging to client %2$s"; private final Index targetIndex; public ClearClientPolicyCommand(Index targetIndex) { this.targetIndex = targetIndex; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); List<Person> lastShownList = model.getFilteredPersonList(); if (targetIndex.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } Person owner = lastShownList.get(targetIndex.getZeroBased()); model.updateFilteredPolicyList(new PolicyIsOwnedByPredicate(owner)); List<Policy> policyList = model.getFilteredPolicyList(); int deletedPolicies = policyList.size(); model.removePoliciesBelongingTo(owner); // Remove filter to display policies correctly in UI model.updateFilteredPolicyList(x -> true); return new CommandResult( String.format(MESSAGE_CLEAR_CLIENT_POLICY_SUCCESS, deletedPolicies, targetIndex.getOneBased())); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ClearClientPolicyCommand // instanceof handles nulls && targetIndex.equals(((ClearClientPolicyCommand) other).targetIndex)); // state check } }
// 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.cloud.network.security.dao; import java.util.List; import com.cloud.network.security.SecurityGroupVO; import com.cloud.utils.db.GenericDao; public interface SecurityGroupDao extends GenericDao<SecurityGroupVO, Long> { List<SecurityGroupVO> listByAccountId(long accountId); boolean isNameInUse(Long accountId, Long domainId, String name); SecurityGroupVO findByAccountAndName(Long accountId, String name); List<SecurityGroupVO> findByAccountAndNames(Long accountId, String... names); int removeByAccountId(long accountId); }
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.subsystems; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.can.TalonFX; import com.revrobotics.CANSparkMax; import edu.wpi.first.networktables.NetworkTableEntry; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.command.Subsystem; import frc.robot.commands.DoNothing; import frc.robot.commands.ManualShooterSpeed; //import edu.wpi.first.wpiutil.math.*; public class Shooter extends Subsystem { private Double rpmSetpoint; private final int SHOOTER_MOTOR_CAN_ID = 13; public static final double DEFAULT_RPM = 0.0; public static final double MAX_RPM = 6500.0; public static final double MAX_VEL = 22000.0; /** * Creates a new shooter. */ TalonFX shooterMotor; CANSparkMax feedMotor; //DigitalInput feedTriggerSwitch; public Shooter() { shooterMotor = new TalonFX(SHOOTER_MOTOR_CAN_ID); shooterMotor.setNeutralMode(NeutralMode.Coast); shooterMotor.config_kF(0, 0.048, 0); shooterMotor.config_kP(0, 0.010, 0); //Leftover from 2020 code, separated into feed subsystem // feedMotor = new CANSparkMax(FEED_MOTOR_CAN_ID, MotorType.kBrushless); // feedMotor.setIdleMode(IdleMode.kCoast); // feedMotor.setSmartCurrentLimit(20); rpmSetpoint = DEFAULT_RPM; //feedTriggerSwitch = new DigitalInput(0); } public Double getRpm() { Double countsPerHundredMs = shooterMotor.getSelectedSensorVelocity(); Double rpm = countsPerHundredMs * 60000.0 / (100 * 2048); return rpm; } @Override public void periodic() { // This method will be called once per scheduler run //SmartDashboard.putBoolean("Ball Ready", ballReady()); SmartDashboard.putNumber("Shooter RPM", getRpm()); SmartDashboard.putNumber("Shooter VEL", shooterMotor.getSelectedSensorVelocity()); } // public boolean ballReady() { // return !feedTriggerSwitch.get(); // } public void setMotorRPM(double rpm) { double velocity = (rpm * 100.0 * 2048.0 )/ 60000.0; shooterMotor.set(ControlMode.Velocity, velocity); //System.out.println("shooter velocity = " + velocity); } public void setMotorPercent(double value) { shooterMotor.set(ControlMode.PercentOutput, value); } public void setMotorVelocity(double vel) { shooterMotor.set(ControlMode.Velocity, vel); } // public void setFeedSpeed(double speed) { // feedMotor.set(.5*speed); // } @Override public void initDefaultCommand() { setDefaultCommand(new ManualShooterSpeed()); } // public boolean ballReady() { // return false; //} }
package com.woodfish.security.config; import com.woodfish.security.authentication.config.SmsCodeAuthenticationSecurityConfig; import com.woodfish.security.authentication.config.ValidateCodeAuthenticationSecurityConfig; import com.woodfish.security.properties.SecurityProperties; import com.woodfish.security.utils.SecurityConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.social.security.SpringSocialConfigurer; @Configuration @EnableResourceServer public class AppResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private AuthenticationSuccessHandler woodfishAuthenticationSuccessHandler; @Autowired private AuthenticationFailureHandler woodfishAuthenticationFailureHandler; // 验证码安全配置器 @Autowired private ValidateCodeAuthenticationSecurityConfig validateCodeAuthenticationSecurityConfig; // 手机验证码的安全配置器 @Autowired private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig; @Autowired private SecurityProperties securityProperties; @Autowired private SpringSocialConfigurer woodfishSocialConfigurer; /** * http Basic 实际上就是将我门的用户名和密码连接起来然后 使用base64进行加密,将加密后的密文放在http 的header 中进行验证 * http.formLogin() * .loginPage("/woodfish-login.html") * .loginProcessingUrl("/authentication/form") // 登录请求路径 action请求路径 * .and() //表单的提交 * .authorizeRequests() // 认证的请求 * .antMatchers("/woodfish-login.html").permitAll() // 放行这个链接 * .anyRequest()// 任意的请求都拦截 * .authenticated() * .and() * .csrf().disable(); * * @param http * @throws Exception */ @Override public void configure(HttpSecurity http) throws Exception { http.formLogin() .loginPage(SecurityConstants.DEFAULT_AUTHENTICATION_URL) .loginProcessingUrl(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_FORM) .successHandler(woodfishAuthenticationSuccessHandler) .failureHandler(woodfishAuthenticationFailureHandler); http/*.apply(validateCodeAuthenticationSecurityConfig) .and()*/ .apply(smsCodeAuthenticationSecurityConfig) .and() .authorizeRequests() .antMatchers( SecurityConstants.DEFAULT_AUTHENTICATION_URL, SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_MOBILE, SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/*" ).permitAll().anyRequest() .authenticated() .and() .csrf().disable(); } }
package com.mamh.clevermap.listener.route; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.amap.api.services.route.BusPath; import com.amap.api.services.route.BusRouteResult; import com.amap.api.services.route.DrivePath; import com.amap.api.services.route.DriveRouteResult; import com.amap.api.services.route.RidePath; import com.amap.api.services.route.RideRouteResult; import com.amap.api.services.route.RouteSearch; import com.amap.api.services.route.WalkPath; import com.amap.api.services.route.WalkRouteResult; import com.mamh.clevermap.overlay.BusRouteOverlay; import com.mamh.clevermap.overlay.DriveRouteOverlay; import com.mamh.clevermap.overlay.RideRouteOverlay; import com.mamh.clevermap.overlay.WalkRouteOverlay; import com.mamh.clevermap.util.ErrorHandler; public class RouteSearchHelper extends RouteSearch implements RouteSearch.OnRouteSearchListener { private static final String TAG = "RouteSearchHelper成功"; private final Context context; //步行图层和结果处理 private WalkRouteOverlay walkRouteOverlay; //骑行图层和结果处理 private RideRouteOverlay rideRouteOverlay; //驾车图层和结果处理 private DriveRouteOverlay driveRouteOverlay; public RouteSearchHelper(Context context) { super(context); this.context = context; setRouteSearchListener(this); } /** * 解析并展示公交与步行结合路线 * * @param busRouteResult 后端发回的步行路线 * @param i 状态码,1000为正常,其他状态码进行异常处理 */ @Override public void onBusRouteSearched(BusRouteResult busRouteResult, int i) { if (i == 1000) { //公交路径,这里仅仅绘制一个图层,采用第一个 BusPath busPath = busRouteResult.getPaths().get(0); //公交图层和结果处理 BusRouteOverlay busRouteOverlay = new BusRouteOverlay(context, busPath, busRouteResult.getStartPos(), busRouteResult.getTargetPos()); //将busPath添加到地图 busRouteOverlay.addToMap(); //移动和缩放到导航位置 busRouteOverlay.zoomToSpan(); } else { Log.e(TAG, "onBusRouteSearched: 计算公交路线时发生异常,详情见下方"); String err = ErrorHandler.handleErrorCode(i); Toast.makeText(context, err, Toast.LENGTH_SHORT).show(); } } /** * 解析并展示驾车路线 * * @param driveRouteResult 后端发回的驾车路线 * @param i 状态码,1000为正常,其他状态码进行异常处理 */ @Override public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) { if (i == 1000) { //驾车路径,这里仅仅绘制一个图层,采用第一个 DrivePath drivePath = driveRouteResult.getPaths().get(0); //如果该图层具有内容,则移除添加新的内容 if (driveRouteOverlay != null) { driveRouteOverlay.remove(); } driveRouteOverlay = new DriveRouteOverlay(context, drivePath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos()); //将drivePath添加到地图 driveRouteOverlay.addToMap(); //移动和缩放到导航位置 driveRouteOverlay.zoomToSpan(); } else { Log.e(TAG, "onDriveRouteSearched: 计算驾车路线时发生异常,详情见下方"); String err = ErrorHandler.handleErrorCode(i); Toast.makeText(context, err, Toast.LENGTH_SHORT).show(); } } /** * 解析并展示步行路线 * * @param walkRouteResult 后端发回的步行路线 * @param i 状态码,1000为正常,其他状态码进行异常处理 */ @Override public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) { //如若一切正常,开始绘制图层,否则异常处理 if (i == 1000) { //步行路径,这里仅仅绘制一个图层,采用第一个 WalkPath walkPath = walkRouteResult.getPaths().get(0); //如果该图层具有内容,则移除添加新的内容 if (walkRouteOverlay != null) { walkRouteOverlay.remove(); } //最后两个参数为LatLonPoint对象 walkRouteOverlay = new WalkRouteOverlay(context, walkPath, walkRouteResult.getStartPos(), walkRouteResult.getTargetPos()); //将walkPath添加到地图 walkRouteOverlay.addToMap(); //移动和缩放到导航位置 walkRouteOverlay.zoomToSpan(); } else { Log.e(TAG, "onWalkRouteSearched: 计算步行路线时发生异常,详情见下方"); String err = ErrorHandler.handleErrorCode(i); Toast.makeText(context, err, Toast.LENGTH_LONG).show(); } } /** * 解析并展示骑行路线 * * @param rideRouteResult 后端发回的骑行路线 * @param i 状态码,1000为正常,其他状态码进行异常处理 */ @Override public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) { if (i == 1000) { //骑行路径,这里仅仅绘制一个图层,采用第一个搜索结果 RidePath ridePath = rideRouteResult.getPaths().get(0); //如果该图层具有内容,则移除添加新的内容 if (rideRouteOverlay != null) { rideRouteOverlay.remove(); } //最后两个参数为LatLonPoint对象 rideRouteOverlay = new RideRouteOverlay(context, ridePath, rideRouteResult.getStartPos(), rideRouteResult.getTargetPos()); //将ridePath添加到地图 rideRouteOverlay.addToMap(); //移动和缩放到导航位置 rideRouteOverlay.zoomToSpan(); } else { Log.e(TAG, "onRideRouteSearched: 计算骑行路线时发生异常,详情见下方"); String err = ErrorHandler.handleErrorCode(i); Toast.makeText(context, err, Toast.LENGTH_LONG).show(); } } }
package smallville7123.UI; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewPropertyAnimator; import android.widget.FrameLayout; import android.widget.HorizontalScrollView; import androidx.annotation.ColorInt; import java.util.ArrayList; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; public class ClipView extends HorizontalScrollView { public ClipView(Context context) { super(context); init(context, null); } public ClipView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public ClipView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } Context mContext; AttributeSet mAttrs; FrameLayout content; private void init(Context context, AttributeSet attrs) { mContext = context; mAttrs = attrs; // make scroll view match parent width setFillViewport(true); FrameLayout frame = new FrameLayout(context, attrs); content = frame; frame.setLayoutParams( new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT ) ); frame.setTag(Internal); addView(frame); Clip A = newClip(); A.setColor(Color.LTGRAY); A.setX(0); A.setWidth(100); addClip(A); setPaint(); } class Clip { View content; Clip(Context context) { content = new FrameLayout(context); setWidth(100); } Clip(Context context, AttributeSet attrs) { content = new FrameLayout(context, attrs); setWidth(100); } public Clip(View content) { content = content; } public void setColor(@ColorInt int color) { content.setBackgroundColor(color); } public void setX(float x) { ViewGroup.LayoutParams p = content.getLayoutParams(); if (p != null) { if (p instanceof MarginLayoutParams) { ((MarginLayoutParams) p).leftMargin = (int) x; content.setLayoutParams(p); } else { throw new RuntimeException("layout is not an instance of MarginLayoutParams"); } } else { content.setLayoutParams( new MarginLayoutParams( MATCH_PARENT, MATCH_PARENT ) { { leftMargin = (int) x; } } ); } } public float getX() { return content.getX(); } public void setWidth(int width) { ViewGroup.LayoutParams p = content.getLayoutParams(); if (p != null) { p.width = width; content.setLayoutParams(p); } else { content.setLayoutParams( new MarginLayoutParams( width, MATCH_PARENT ) ); } } public int getWidth() { return content.getWidth(); } public ViewPropertyAnimator animate() { return content.animate(); } } /* in ``` | scroll view start | | content view start | | 0px | | 5px | | 10px | | scroll view end | | 15px | | content view end | ``` i want to obtain 15px, but for some reason i can only obtain 10px :( */ Clip newClip() { return new Clip(mContext, mAttrs); }; private static class Internal {} Internal Internal = new Internal(); ArrayList<Clip> clips = new ArrayList<>(); public void addClip(Clip clip) { clips.add(clip); content.addView(clip.content); } private static final String TAG = "ClipView"; private float relativeToViewX; boolean scrolling = false; boolean clipTouch = false; Clip touchedClip; float downDX; float downRawX; float currentRawX; @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: for (Clip clip : clips) { boolean ret = onClipTouchEvent(clip, event); if (ret) { clipTouch = true; touchedClip = clip; return ret; } } scrolling = true; return super.onTouchEvent(event); case MotionEvent.ACTION_MOVE: return clipTouch ? onClipTouchEvent(touchedClip, event) : super.onTouchEvent(event); case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (clipTouch) { boolean ret = onClipTouchEvent(touchedClip, event); clipTouch = false; return ret; } scrolling = false; return super.onTouchEvent(event); } return super.onTouchEvent(event); } public float touchZoneWidthLeft = 80.0f; public float touchZoneWidthLeftOffset = 80.0f; public float touchZoneWidthRight = 80.0f; public float touchZoneWidthRightOffset = 80.0f; Paint highlightPaint; Paint touchZonePaint; private void setPaint() { highlightPaint = new Paint(); touchZonePaint = new Paint(); highlightPaint.setARGB(200, 0, 0, 255); touchZonePaint.setARGB(160, 0, 90, 0); } @Override public void onDrawForeground(Canvas canvas) { super.onDrawForeground(canvas); int width = getWidth(); int height = getHeight(); if (isResizing) { drawHighlight(canvas, width, height, highlightPaint); } // drawTouchZones(canvas, width, height, touchZonePaint); } void drawHighlight(Canvas canvas, int width, int height, Paint paint) { float clipStart = touchedClip.getX(); float clipWidth = touchedClip.getWidth(); float clipEnd = clipStart + clipWidth; canvas.drawRect(clipStart, 0, clipEnd, height, paint); } void drawTouchZones(Canvas canvas, int width, int height, Paint paint) { for (Clip clip : clips) { float clipStart = clip.getX(); float clipWidth = clip.getWidth(); float clipEnd = clipStart + clipWidth; // left canvas.drawRect(clipStart - touchZoneWidthLeftOffset, 0, (clipStart + touchZoneWidthLeft) - touchZoneWidthLeftOffset, height, paint); // right canvas.drawRect((clipEnd - touchZoneWidthRight) + touchZoneWidthRightOffset, 0, clipEnd + touchZoneWidthRightOffset, height, paint); } } boolean isResizing; boolean isDragging; float clipOriginalStart; float clipOriginalWidth; float clipOriginalEnd; boolean resizingLeft; boolean resizingRight; public boolean onClipTouchEvent(Clip clip, MotionEvent event) { currentRawX = event.getRawX(); relativeToViewX = event.getX() + getScrollX(); switch (event.getAction()) { case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (!isResizing && isDragging) { isDragging = false; return true; } else if (isResizing && !isDragging) { isResizing = false; invalidate(); return true; } return false; case MotionEvent.ACTION_MOVE: if (!isResizing && isDragging) { if (currentRawX + downDX >= 0) { clip.setX(currentRawX + downDX); } else { clip.setX(0); } return true; } else if (isResizing && !isDragging) { MarginLayoutParams layoutParams = (MarginLayoutParams) clip.content.getLayoutParams(); if (resizingLeft) { float bounds = currentRawX + downDX; if (layoutParams.width > 0) { if (bounds > clipOriginalEnd) bounds = clipOriginalEnd; float newWidth = clipOriginalWidth - (bounds - clipOriginalStart); if (newWidth < 1.0f) newWidth = 1.0f; clip.setX(bounds); clip.setWidth((int) newWidth); } } else if (resizingRight) { float bounds = currentRawX + downDX; if (layoutParams.width > 0) { float newWidth = clipOriginalWidth + (bounds - clipOriginalStart); if (newWidth < 1.0f) newWidth = 1.0f; clip.setWidth((int) newWidth); } } return true; } return false; case MotionEvent.ACTION_DOWN: isDragging = false; isResizing = false; clipOriginalStart = clip.getX(); clipOriginalWidth = clip.getWidth(); clipOriginalEnd = clipOriginalStart + clipOriginalWidth; downRawX = currentRawX; resizingLeft = false; resizingRight = false; float leftStart = clipOriginalStart - touchZoneWidthLeftOffset; float leftEnd = (clipOriginalStart + touchZoneWidthLeft) - touchZoneWidthLeftOffset; float rightStart = (clipOriginalEnd - touchZoneWidthRight) + touchZoneWidthRightOffset; float rightEnd = clipOriginalEnd + touchZoneWidthRightOffset; if (within(relativeToViewX, leftStart, leftEnd)) { resizingLeft = true; isResizing = true; } else if (within(relativeToViewX, rightStart, rightEnd)) { resizingRight = true; isResizing = true; } else if (within(relativeToViewX, clipOriginalStart, clipOriginalEnd)) { isDragging = true; } if (isResizing || isDragging) { invalidate(); downDX = clipOriginalStart - downRawX; return true; } default: return false; } } boolean within(float point, float start, float end) { return point >= start && point <= end; } /** * <p>Adds a child view. If no layout parameters are already set on the child, the * default parameters for this ViewGroup are set on the child.</p> * * <p><strong>Note:</strong> do not invoke this method from * {@link #draw(Canvas)}, {@link #onDraw(Canvas)}, * {@link #dispatchDraw(Canvas)} or any related method.</p> * * @param child the child view to add * * @see #generateDefaultLayoutParams() */ @Override public void addView(View child) { addView(child, -1); } /** * Adds a child view. If no layout parameters are already set on the child, the * default parameters for this ViewGroup are set on the child. * * <p><strong>Note:</strong> do not invoke this method from * {@link #draw(Canvas)}, {@link #onDraw(Canvas)}, * {@link #dispatchDraw(Canvas)} or any related method.</p> * * @param child the child view to add * @param index the position at which to add the child * * @see #generateDefaultLayoutParams() */ @Override public void addView(View child, int index) { if (child == null) { throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup"); } ViewGroup.LayoutParams params = child.getLayoutParams(); if (params == null) { params = generateDefaultLayoutParams(); if (params == null) { throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null"); } } addView(child, index, params); } /** * Adds a child view with this ViewGroup's default layout parameters and the * specified width and height. * * <p><strong>Note:</strong> do not invoke this method from * {@link #draw(Canvas)}, {@link #onDraw(Canvas)}, * {@link #dispatchDraw(Canvas)} or any related method.</p> * * @param child the child view to add */ @Override public void addView(View child, int width, int height) { final ViewGroup.LayoutParams params = generateDefaultLayoutParams(); params.width = width; params.height = height; addView(child, -1, params); } /** * Adds a child view with the specified layout parameters. * * <p><strong>Note:</strong> do not invoke this method from * {@link #draw(Canvas)}, {@link #onDraw(Canvas)}, * {@link #dispatchDraw(Canvas)} or any related method.</p> * * @param child the child view to add * @param params the layout parameters to set on the child */ @Override public void addView(View child, ViewGroup.LayoutParams params) { addView(child, -1, params); } /** * Adds a child view with the specified layout parameters. * * <p><strong>Note:</strong> do not invoke this method from * {@link #draw(Canvas)}, {@link #onDraw(Canvas)}, * {@link #dispatchDraw(Canvas)} or any related method.</p> * * @param child the child view to add * @param index the position at which to add the child or -1 to add last * @param params the layout parameters to set on the child */ @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { Object tag = child.getTag(); if (tag instanceof Internal) super.addView(child, index, params); else addClip(new Clip(child)); } }
/* * Copyright (C) 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * Copyright (C) 2010 Connor Tumbleson <connor.tumbleson@gmail.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 * * 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 brut.androlib.res.data; import brut.androlib.AndrolibException; import brut.androlib.err.UndefinedResObjectException; import brut.androlib.meta.VersionInfo; import brut.androlib.res.AndrolibResources; import brut.androlib.res.data.value.ResValue; import java.util.*; public class ResTable { private final AndrolibResources mAndRes; private final Map<Integer, ResPackage> mPackagesById = new HashMap<Integer, ResPackage>(); private final Map<String, ResPackage> mPackagesByName = new HashMap<String, ResPackage>(); private final Set<ResPackage> mMainPackages = new LinkedHashSet<ResPackage>(); private final Set<ResPackage> mFramePackages = new LinkedHashSet<ResPackage>(); private String mPackageRenamed; private String mPackageOriginal; private int mPackageId; private boolean mAnalysisMode = false; private boolean mSharedLibrary = false; private boolean mSparseResources = false; private Map<String, String> mSdkInfo = new LinkedHashMap<>(); private VersionInfo mVersionInfo = new VersionInfo(); public ResTable() { mAndRes = null; } public ResTable(AndrolibResources andRes) { mAndRes = andRes; } public ResResSpec getResSpec(int resID) throws AndrolibException { // The pkgId is 0x00. That means a shared library is using its // own resource, so lie to the caller replacing with its own // packageId if (resID >> 24 == 0) { int pkgId = (mPackageId == 0 ? 2 : mPackageId); resID = (0xFF000000 & (pkgId << 24)) | resID; } return getResSpec(new ResID(resID)); } public ResResSpec getResSpec(ResID resID) throws AndrolibException { return getPackage(resID.package_).getResSpec(resID); } public Set<ResPackage> listMainPackages() { return mMainPackages; } public Set<ResPackage> listFramePackages() { return mFramePackages; } public ResPackage getPackage(int id) throws AndrolibException { ResPackage pkg = mPackagesById.get(id); if (pkg != null) { return pkg; } if (mAndRes != null) { return mAndRes.loadFrameworkPkg(this, id, mAndRes.apkOptions.frameworkTag); } throw new UndefinedResObjectException(String.format("package: id=%d", id)); } public ResPackage getHighestSpecPackage() throws AndrolibException { int id = 0; int value = 0; for (ResPackage resPackage : mPackagesById.values()) { if (resPackage.getResSpecCount() > value && !resPackage.getName().equalsIgnoreCase("android")) { value = resPackage.getResSpecCount(); id = resPackage.getId(); } } // if id is still 0, we only have one pkgId which is "android" -> 1 return (id == 0) ? getPackage(1) : getPackage(id); } public ResPackage getCurrentResPackage() throws AndrolibException { ResPackage pkg = mPackagesById.get(mPackageId); if (pkg != null) { return pkg; } else { if (mMainPackages.size() == 1) { return mMainPackages.iterator().next(); } return getHighestSpecPackage(); } } public ResPackage getPackage(String name) throws AndrolibException { ResPackage pkg = mPackagesByName.get(name); if (pkg == null) { throw new UndefinedResObjectException("package: name=" + name); } return pkg; } public ResValue getValue(String package_, String type, String name) throws AndrolibException { return getPackage(package_).getType(type).getResSpec(name).getDefaultResource().getValue(); } public void addPackage(ResPackage pkg, boolean main) throws AndrolibException { Integer id = pkg.getId(); if (mPackagesById.containsKey(id)) { throw new AndrolibException("Multiple packages: id=" + id.toString()); } String name = pkg.getName(); if (mPackagesByName.containsKey(name)) { throw new AndrolibException("Multiple packages: name=" + name); } mPackagesById.put(id, pkg); mPackagesByName.put(name, pkg); if (main) { mMainPackages.add(pkg); } else { mFramePackages.add(pkg); } } public void setAnalysisMode(boolean mode) { mAnalysisMode = mode; } public void setPackageRenamed(String pkg) { mPackageRenamed = pkg; } public void setPackageOriginal(String pkg) { mPackageOriginal = pkg; } public void setPackageId(int id) { mPackageId = id; } public void setSharedLibrary(boolean flag) { mSharedLibrary = flag; } public void setSparseResources(boolean flag) { mSparseResources = flag; } public void clearSdkInfo() { mSdkInfo.clear(); } public void addSdkInfo(String key, String value) { mSdkInfo.put(key, value); } public void setVersionName(String versionName) { mVersionInfo.versionName = versionName; } public void setVersionCode(String versionCode) { mVersionInfo.versionCode = versionCode; } public VersionInfo getVersionInfo() { return mVersionInfo; } public Map<String, String> getSdkInfo() { return mSdkInfo; } public boolean getAnalysisMode() { return mAnalysisMode; } public String getPackageRenamed() { return mPackageRenamed; } public String getPackageOriginal() { return mPackageOriginal; } public int getPackageId() { return mPackageId; } public boolean getSharedLibrary() { return mSharedLibrary; } public boolean getSparseResources() { return mSparseResources; } }
package io.toolisticon.jigsawbyap.processor; import io.toolisticon.annotationprocessortoolkit.tools.corematcher.ValidationMessage; /** * Messages used by annotation processors. */ public enum JigsawByApProcessorMessages implements ValidationMessage { ERROR_COULD_NOT_FIND_MODULE_FILE("JIGSAW_BY_AP_ERROR_001", "Could not find module files"); /** * the message code. */ private final String code; /** * the message text. */ private final String message; /** * Constructor. * * @param code the message code * @param message the message text */ JigsawByApProcessorMessages(String code, String message) { this.code = code; this.message = message; } /** * Gets the code of the message. * * @return the message code */ public String getCode() { return this.code; } /** * Gets the message text. * * @return the message text */ public String getMessage() { return message; } }
package Aula_03_vetores_e_funcoes; import static Aula_03_vetores_e_funcoes.Ex01_InverterNumeroComFuncao.leInteiroPositivo; import static Aula_03_vetores_e_funcoes.Ex02_MaiorDoVetor.exibeVetor; import static Aula_03_vetores_e_funcoes.Ex02_MaiorDoVetor.leVetorAleatorio; import static Aula_03_vetores_e_funcoes.Ex06_BuscaBinaria.buscaBinaria; public class Ex07_InterseccaoDeDoisVetores { public static void main(String[] args) { int dimensao1 = leInteiroPositivo(); int vetor1[] = leVetorAleatorio(dimensao1); System.out.print("Elementos do vetor1: "); exibeVetor(vetor1); System.out.println(""); int dimensao2 = leInteiroPositivo(); int vetor2[] = leVetorAleatorio(dimensao2); System.out.print("Elementos do vetor2: "); exibeVetor(vetor2); int interseccao[] = new int[dimensao1]; int tamanho = intersecaoVetores(interseccao, vetor1, vetor2); System.out.print("\n\nElementos do vetor interseccionado: "); exibeVetorTamanho(interseccao, tamanho); System.out.println(""); } public static int intersecaoVetores(int interseccao[], int vetor1[], int vetor2[]) { int k = 0; // quantidade for (int i=0; i < vetor1.length; i++) { if (buscaBinaria(vetor2, vetor1[i]) != -1) { if (buscaBinaria(interseccao, vetor1[i]) == -1) { // ou seja, se o elemento ja nao está no vetor interseccionado. interseccao[k] = vetor1[i]; k++; } } } return k; } public static void exibeVetorTamanho(int vetor[], int k) { // retorna um vetor de inteiros, com k posicoes. for (int i=0; i < k; i++) System.out.print(vetor[i] + " "); } }
/* * Swift Parallel Scripting Language (http://swift-lang.org) * Code from Java CoG Kit Project (see notice below) with modifications. * * Copyright 2005-2014 University of Chicago * * 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. */ //---------------------------------------------------------------------- //This code is developed as part of the Java CoG Kit project //The terms of the license can be found at http://www.cogkit.org/license //This message may not be removed or altered. //---------------------------------------------------------------------- /* * Created on Nov 28, 2006 */ package org.globus.cog.abstraction.impl.file; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.PasswordAuthentication; 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 org.apache.log4j.Logger; import org.globus.cog.abstraction.impl.common.AbstractionFactory; import org.globus.cog.abstraction.impl.common.IdentityImpl; import org.globus.cog.abstraction.impl.common.ProviderMethodException; import org.globus.cog.abstraction.impl.common.task.InvalidProviderException; import org.globus.cog.abstraction.impl.common.task.InvalidSecurityContextException; import org.globus.cog.abstraction.impl.common.task.ServiceImpl; import org.globus.cog.abstraction.interfaces.FileFragment; import org.globus.cog.abstraction.interfaces.FileResource; import org.globus.cog.abstraction.interfaces.GridFile; import org.globus.cog.abstraction.interfaces.GridResource; import org.globus.cog.abstraction.interfaces.Identity; import org.globus.cog.abstraction.interfaces.ProgressMonitor; import org.globus.cog.abstraction.interfaces.SecurityContext; import org.globus.cog.abstraction.interfaces.Service; import org.globus.cog.abstraction.interfaces.ServiceContact; public abstract class AbstractFileResource implements FileResource { public static final Logger logger = Logger.getLogger(AbstractFileResource.class); private String name; private Map<String, Object> attributes; private Service service; private Identity identity; private final int type = GridResource.FILE; private String protocol; private boolean started; protected AbstractFileResource(String name, String protocol, ServiceContact serviceContact, SecurityContext securityContext) { this(name, protocol, new ServiceImpl(protocol, serviceContact, securityContext)); } protected AbstractFileResource(String name, String protocol, Service service) { attributes = new HashMap<String, Object>(); identity = new IdentityImpl(); this.name = name; if (protocol == null) { throw new NullPointerException(); } this.protocol = protocol; this.service = service; } protected ServiceContact getAndCheckServiceContact() throws IllegalHostException { ServiceContact serviceContact = getServiceContact(); if (serviceContact == null) { throw new IllegalHostException("No service contact specified"); } return serviceContact; } protected SecurityContext getOrCreateSecurityContext(String provider, ServiceContact serviceContact) throws InvalidProviderException, ProviderMethodException { SecurityContext securityContext = getSecurityContext(); if (securityContext == null) { securityContext = AbstractionFactory.getSecurityContext("gsiftp", serviceContact); } return securityContext; } protected PasswordAuthentication getCredentialsAsPasswordAuthentication(SecurityContext securityContext) throws InvalidSecurityContextException { Object credentials = securityContext.getCredentials(); if (credentials == null) { if (logger.isInfoEnabled()) { logger.info(name + ": credentials are null; using default username/password."); } return getDefaultUsernameAndPassword(); } if (!(credentials instanceof PasswordAuthentication)) { throw new InvalidSecurityContextException("FTP only supports password authentication. Credentials supplied: " + credentials.getClass().getName()); } return (PasswordAuthentication) credentials; } protected PasswordAuthentication getDefaultUsernameAndPassword() { return new PasswordAuthentication("", new char[0]); } /** Set the name of the resource */ public void setName(String name) { this.name = name; } /** Return name of the resource */ public String getName() { return this.name; } /** set service contact */ public void setServiceContact(ServiceContact serviceContact) { service.setServiceContact(serviceContact); } /** return service contact */ public ServiceContact getServiceContact() { return service.getServiceContact(); } /** Set identity of the resource */ public void setIdentity(Identity identity) { this.identity = identity; } /** return identity of the resource */ public Identity getIdentity() { return this.identity; } /** return type = FILE which is defined in GridResource */ public int getType() { return this.type; } /** return protocol */ public String getProtocol() { return this.protocol; } /** Set the appropriate SecurityContext for the FileResource */ public void setSecurityContext(SecurityContext securityContext) { service.setSecurityContext(securityContext); } /** Get the securityContext for the remote resource */ public SecurityContext getSecurityContext() { return service.getSecurityContext(); } public Service getService() { return service; } public void setService(Service service) { this.service = service; } public boolean isStarted() { return started; } protected synchronized void setStarted(boolean started) { this.started = started; } /** set attribute for ftp resource */ public void setAttribute(String name, Object value) { this.attributes.put(name, value); } public Collection<String> getAttributeNames() { return this.attributes.keySet(); } /** get attribute */ public Object getAttribute(String name) { return this.attributes.get(name); } public void getFile(String remoteFileName, String localFileName) throws FileResourceException { getFile(new FileFragmentImpl(remoteFileName), new FileFragmentImpl(localFileName)); } public void getFile(String remoteFileName, String localFileName, ProgressMonitor progressMonitor) throws FileResourceException { getFile(new FileFragmentImpl(remoteFileName), new FileFragmentImpl(localFileName), progressMonitor); } public void getFile(FileFragment remote, FileFragment local) throws FileResourceException { getFile(remote, local, null); } public void putFile(String localFileName, String remoteFileName) throws FileResourceException { putFile(new FileFragmentImpl(localFileName), new FileFragmentImpl(remoteFileName)); } public void putFile(String localFileName, String remoteFileName, ProgressMonitor progressMonitor) throws FileResourceException { putFile(new FileFragmentImpl(localFileName), new FileFragmentImpl(remoteFileName), progressMonitor); } public void putFile(FileFragment local, FileFragment remote) throws FileResourceException { putFile(local, remote, null); } /** Equivalent to the cp -r command for copying directories */ public void getDirectory(String remoteDirName, String localDirName) throws FileResourceException { File localDir = new File(localDirName); GridFile gridFile = null; if (!localDir.exists()) { localDir.mkdir(); } if (isDirectory(remoteDirName) == false) { throw new DirectoryNotFoundException("Remote directory not found"); } for (Iterator<GridFile> iterator = list(remoteDirName).iterator(); iterator .hasNext();) { gridFile = iterator.next(); if (gridFile.isFile()) { getFile(remoteDirName + "/" + gridFile.getName(), localDirName + File.separator + gridFile.getName()); } else { getDirectory(remoteDirName + "/" + gridFile.getName(), localDirName + File.separator + gridFile.getName()); } } } /** Equivalent to cp -r command for copying directories */ public void putDirectory(String localDirName, String remoteDirName) throws FileResourceException { File localDir = new File(localDirName); if (!localDir.exists()) { throw new DirectoryNotFoundException("Local directory not found"); } if (localDir.isFile()) { throw new DirectoryNotFoundException(localDirName + " is a file"); } try { if (!exists(remoteDirName)) { createDirectory(remoteDirName); } } catch (FileNotFoundException fe) { throw new DirectoryNotFoundException( "Cannot create the remote directory: " + remoteDirName); } if (!isDirectory(remoteDirName)) { throw new DirectoryNotFoundException(remoteDirName + " is a file"); } String files[] = localDir.list(); for (int index = 0; index < files.length; index++) { File localFile = new File(localDirName + File.separator + files[index]); if (!localFile.isDirectory()) { putFile(localDirName + File.separator + files[index], remoteDirName + "/" + files[index]); } else { putDirectory(localDirName + File.separator + files[index], remoteDirName + "/" + files[index]); } } } /** * mget - Obtain multiple files from the remote server */ public void getMultipleFiles(String[] remoteFileNames, String[] localFileNames) throws FileResourceException { // If the list of sources not equal to destination lists then error if (localFileNames.length != remoteFileNames.length) throw new IllegalArgumentException( "Number of source and destination file names has to be the same"); // Check every remote file name provided. If file, use getfile else use // getdir for (int index = 0; index < remoteFileNames.length; index++) { if (exists(remoteFileNames[index])) { if (isDirectory(remoteFileNames[index]) == false) { getFile(remoteFileNames[index], localFileNames[index]); } else { getDirectory(remoteFileNames[index], localFileNames[index]); } } } } /** * mget - Obtain multiple files from the ftp server */ public void getMultipleFiles(String[] remoteFileNames, String localDirName) throws FileResourceException { for (int index = 0; index < remoteFileNames.length; index++) { // Extract only the file name to be appended to the destination // directory // in getfile or getdir String remoteFileName = remoteFileNames[index] .substring(remoteFileNames[index].lastIndexOf("/") + 1); if (exists(remoteFileNames[index])) { // Check every remote file name provided. If file, use // getfile else use getdir if (isDirectory(remoteFileNames[index]) == false) { getFile(remoteFileNames[index], localDirName + File.separator + remoteFileName); } else { getDirectory(remoteFileNames[index], localDirName + File.separator + remoteFileName); } } } } /** * mput - copy multiple files to the resource */ public void putMultipleFiles(String[] localFileNames, String remoteDirName) throws FileResourceException { for (int index = 0; index < localFileNames.length; index++) { // Check every remote file name provided. If file, use putfile else // use putdir File localFile = new File(localFileNames[index]); if (!localFile.isDirectory()) { putFile(localFileNames[index], remoteDirName + "/" + localFile.getName()); } else { putDirectory(localFileNames[index], remoteDirName + "/" + localFile.getName()); } } } /** * mput - copy multiple files into the resource server */ public void putMultipleFiles(String[] localFileNames, String[] remoteFileNames) throws FileResourceException { // If list of sources not equal to list of destinations then error if (localFileNames.length != remoteFileNames.length) throw new IllegalArgumentException( "Number of source and destination file names has to be the same"); for (int index = 0; index < localFileNames.length; index++) { // Check every local file name provided. If file, use putfile else // use putdir File localFile = new File(localFileNames[index]); if (!localFile.isDirectory()) { putFile(localFileNames[index], remoteFileNames[index]); } else { putDirectory(localFileNames[index], remoteFileNames[index]); } } } public void createDirectories(String dir) throws FileResourceException { // TODO there is an assumption here on the path separators // I'd really suggest enforcing only one of them (hint: '/') at the // level of the // interface if (dir.equals("/")) { return; } try { if (!exists(dir)) { int i = dir.lastIndexOf('/'); if (i <= 0) { createDirectory(dir); } else { createDirectories(dir.substring(0, i)); if (i != dir.length() - 1) { createDirectory(dir); } else { // trailing '/' } } } } catch (FileResourceException e) { if (!isDirectory(dir)) { throw e; } } } public InputStream openInputStream(String name) throws FileResourceException { throw new UnsupportedOperationException(); } public OutputStream openOutputStream(String name) throws FileResourceException { throw new UnsupportedOperationException(); } public boolean supportsStreams() { return false; } public String toString() { return "FileResource: " + name; } public void thirdPartyTransfer(FileResource sourceResource, FileFragment source, FileFragment destination) throws FileResourceException { throw new UnsupportedOperationException("The " + getName() + " provider does not support third party transfers"); } protected void checkNoPartialTransfers(FileFragment f1, FileFragment f2, String name) { if (f1.isFragment() || f2.isFragment()) { throw new UnsupportedOperationException("The " + name + " provider does not support partial transfers"); } } /** * Convenience method to implement filtering. Providers should implement their * own, more efficient, filtering * @throws FileResourceException * @throws DirectoryNotFoundException */ @Override public Collection<GridFile> list(String dir, FileResourceFileFilter filter) throws DirectoryNotFoundException, FileResourceException { List<GridFile> nl = new ArrayList<GridFile>(); Collection<GridFile> ol = list(dir); for (GridFile f : ol) { if (filter.accept(f)) { nl.add(f); } } return nl; } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.rest.api.service; import io.gravitee.repository.management.model.Parameter; import io.gravitee.rest.api.model.PortalConfigEntity; import io.gravitee.rest.api.model.parameters.Key; import io.gravitee.rest.api.service.impl.ConfigServiceImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.env.ConfigurableEnvironment; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static io.gravitee.rest.api.model.parameters.Key.COMPANY_NAME; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; /** * @author Nicolas GERAUD (nicolas.geraud at graviteesource.com) * @author GraviteeSource Team */ @RunWith(MockitoJUnitRunner.class) public class ConfigServiceTest { @InjectMocks private ConfigServiceImpl configService = new ConfigServiceImpl(); @Mock private ParameterService mockParameterService; @Mock private ConfigurableEnvironment environment; @Test public void shouldGetPortalConfig() { Map<String, List<String>> params = new HashMap<>(); params.put(COMPANY_NAME.key(), singletonList("ACME")); params.put(Key.AUTHENTICATION_FORCELOGIN_ENABLED.key(), singletonList("true")); params.put(Key.AUTHENTICATION_OAUTH2_SCOPE.key(), Arrays.asList("scope1", "scope2")); params.put(Key.SCHEDULER_NOTIFICATIONS.key(), singletonList("11")); params.put(Key.PORTAL_ANALYTICS_ENABLED.key(), singletonList("true")); when(mockParameterService.findAll(any(List.class))).thenReturn(params); PortalConfigEntity portalConfig = configService.getPortalConfig(); assertNotNull(portalConfig); assertEquals("company name", "ACME", portalConfig.getCompany().getName()); assertEquals("force login", true, portalConfig.getAuthentication().getForceLogin().isEnabled()); assertEquals("scopes", 2, portalConfig.getAuthentication().getOauth2().getScope().size()); assertEquals("scheduler notifications", Integer.valueOf(11), portalConfig.getScheduler().getNotificationsInSeconds()); assertEquals("analytics", Boolean.TRUE, portalConfig.getPortal().getAnalytics().isEnabled()); } @Test public void shouldCreateProtalConfig() { PortalConfigEntity portalConfigEntity = new PortalConfigEntity(); portalConfigEntity.getCompany().setName("ACME"); when(mockParameterService.save(COMPANY_NAME, "ACME")).thenReturn(new Parameter()); configService.save(portalConfigEntity); verify(mockParameterService, times(1)).save(COMPANY_NAME, "ACME"); } }
/* * MusicTag Copyright (C)2003,2004 * * 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, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jaudiotagger.tag.id3.framebody; import org.jaudiotagger.tag.InvalidTagException; import org.jaudiotagger.tag.id3.ID3v24Frames; import org.jaudiotagger.tag.reference.Languages; import java.nio.ByteBuffer; /** * Language(s) Text information frame. * <p>The 'Language(s)' frame should contain the languages of the text or lyrics spoken or sung in the audio. The language is represented with three characters according to ISO-639-2. If more than one language is used in the text their language codes should follow according to their usage. * <p/> * <p>For more details, please refer to the ID3 specifications: * <ul> * <li><a href="http://www.id3.org/id3v2.3.0.txt">ID3 v2.3.0 Spec</a> * </ul> * <p/> * TODO:Although rare TLAN can actually return multiple language codes, at the moment they are all returned as a single * string via getText(), any additional parsrsing has to be done externally. * * @author : Paul Taylor * @author : Eric Farng * @version $Id: FrameBodyTLAN.java 832 2009-11-12 13:25:38Z paultaylor $ */ public class FrameBodyTLAN extends AbstractFrameBodyTextInfo implements ID3v24FrameBody, ID3v23FrameBody { /** * Creates a new FrameBodyTLAN datatype. */ public FrameBodyTLAN() { super(); } public FrameBodyTLAN(FrameBodyTLAN body) { super(body); } /** * Creates a new FrameBodyTLAN datatype. * * @param textEncoding * @param text */ public FrameBodyTLAN(byte textEncoding, String text) { super(textEncoding, text); } /** * Creates a new FrameBodyTLAN datatype. * * @param byteBuffer * @param frameSize * @throws InvalidTagException */ public FrameBodyTLAN(ByteBuffer byteBuffer, int frameSize) throws InvalidTagException { super(byteBuffer, frameSize); } /** * The ID3v2 frame identifier * * @return the ID3v2 frame identifier for this frame type */ public String getIdentifier() { return ID3v24Frames.FRAME_ID_LANGUAGE; } /** * * @return true if text value is valid language code */ public boolean isValid() { return Languages.getInstanceOf().getValueForId(getFirstTextValue())!=null; } }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.linalg.cpu.nativecpu.buffer; import lombok.NonNull; import org.bytedeco.javacpp.DoublePointer; import org.bytedeco.javacpp.FloatPointer; import org.bytedeco.javacpp.IntPointer; import org.bytedeco.javacpp.Pointer; import org.bytedeco.javacpp.indexer.DoubleIndexer; import org.bytedeco.javacpp.indexer.FloatIndexer; import org.bytedeco.javacpp.indexer.Indexer; import org.bytedeco.javacpp.indexer.IntIndexer; import org.nd4j.linalg.api.buffer.*; import org.nd4j.linalg.api.buffer.factory.DataBufferFactory; import org.nd4j.linalg.api.memory.MemoryWorkspace; import org.nd4j.common.util.ArrayUtil; import java.nio.ByteBuffer; /** * Normal data buffer creation * * @author Adam Gibson */ public class DefaultDataBufferFactory implements DataBufferFactory { protected DataBuffer.AllocationMode allocationMode; @Override public void setAllocationMode(DataBuffer.AllocationMode allocationMode) { this.allocationMode = allocationMode; } @Override public DataBuffer.AllocationMode allocationMode() { if (allocationMode == null) { String otherAlloc = System.getProperty("alloc"); if (otherAlloc.equals("heap")) setAllocationMode(DataBuffer.AllocationMode.HEAP); else if (otherAlloc.equals("direct")) setAllocationMode(DataBuffer.AllocationMode.DIRECT); else if (otherAlloc.equals("javacpp")) setAllocationMode(DataBuffer.AllocationMode.JAVACPP); } return allocationMode; } @Override public DataBuffer create(DataBuffer underlyingBuffer, long offset, long length) { if (underlyingBuffer.dataType() == DataType.DOUBLE) { return new DoubleBuffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.FLOAT) { return new FloatBuffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.INT) { return new IntBuffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.LONG) { return new LongBuffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.BOOL) { return new BoolBuffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.SHORT) { return new Int16Buffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.BYTE) { return new Int8Buffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.UBYTE) { return new UInt8Buffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.UINT16) { return new UInt16Buffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.UINT32) { return new UInt32Buffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.UINT64) { return new UInt64Buffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.BFLOAT16) { return new BFloat16Buffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.HALF) { return new HalfBuffer(underlyingBuffer, length, offset); } else if (underlyingBuffer.dataType() == DataType.UTF8) { return new Utf8Buffer(underlyingBuffer, length, offset); } return null; } @Override public DataBuffer createDouble(long offset, int length) { return new DoubleBuffer(length, 8, offset); } @Override public DataBuffer createFloat(long offset, int length) { return new FloatBuffer(length, 4, offset); } @Override public DataBuffer createInt(long offset, int length) { return new IntBuffer(length, 4, offset); } @Override public DataBuffer createDouble(long offset, int[] data) { return createDouble(offset, data, true); } @Override public DataBuffer createFloat(long offset, int[] data) { FloatBuffer ret = new FloatBuffer(ArrayUtil.toFloats(data), true, offset); return ret; } @Override public DataBuffer createInt(long offset, int[] data) { return new IntBuffer(data, true, offset); } @Override public DataBuffer createDouble(long offset, double[] data) { return new DoubleBuffer(data, true, offset); } @Override public DataBuffer createDouble(long offset, double[] data, MemoryWorkspace workspace) { return new DoubleBuffer(data, true, offset, workspace); } @Override public DataBuffer createDouble(long offset, byte[] data, int length) { return createDouble(offset, ArrayUtil.toDoubleArray(data), true); } @Override public DataBuffer createFloat(long offset, byte[] data, int length) { return createFloat(offset, ArrayUtil.toFloatArray(data), true); } @Override public DataBuffer createFloat(long offset, double[] data) { return new FloatBuffer(ArrayUtil.toFloats(data), true, offset); } @Override public DataBuffer createInt(long offset, double[] data) { return new IntBuffer(ArrayUtil.toInts(data), true, offset); } @Override public DataBuffer createDouble(long offset, float[] data) { return new DoubleBuffer(ArrayUtil.toDoubles(data), true, offset); } @Override public DataBuffer createFloat(long offset, float[] data) { return new FloatBuffer(data, true, offset); } @Override public DataBuffer createFloat(long offset, float[] data, MemoryWorkspace workspace) { return new FloatBuffer(data, true, offset, workspace); } @Override public DataBuffer createInt(long offset, float[] data) { return new IntBuffer(ArrayUtil.toInts(data), true, offset); } @Override public DataBuffer createDouble(long offset, int[] data, boolean copy) { return new DoubleBuffer(ArrayUtil.toDoubles(data), true, offset); } @Override public DataBuffer createFloat(long offset, int[] data, boolean copy) { return new FloatBuffer(ArrayUtil.toFloats(data), copy, offset); } @Override public DataBuffer createInt(long offset, int[] data, boolean copy) { return new IntBuffer(data, copy, offset); } @Override public DataBuffer createDouble(long offset, double[] data, boolean copy) { return new DoubleBuffer(data, copy, offset); } @Override public DataBuffer createFloat(long offset, double[] data, boolean copy) { return new FloatBuffer(ArrayUtil.toFloats(data), copy, offset); } @Override public DataBuffer createInt(long offset, double[] data, boolean copy) { return new IntBuffer(ArrayUtil.toInts(data), copy, offset); } @Override public DataBuffer createDouble(long offset, float[] data, boolean copy) { return new DoubleBuffer(ArrayUtil.toDoubles(data), copy, offset); } @Override public DataBuffer createFloat(long offset, float[] data, boolean copy) { return new FloatBuffer(data, copy, offset); } @Override public DataBuffer createInt(long offset, float[] data, boolean copy) { return new IntBuffer(ArrayUtil.toInts(data), copy, offset); } @Override public DataBuffer createDouble(long length) { return new DoubleBuffer(length); } @Override public DataBuffer createDouble(long length, boolean initialize) { return new DoubleBuffer(length, initialize); } @Override public DataBuffer createFloat(long length) { return new FloatBuffer(length); } @Override public DataBuffer createFloat(long length, boolean initialize) { return new FloatBuffer(length, initialize); } @Override public DataBuffer createFloat(long length, boolean initialize, MemoryWorkspace workspace) { return new FloatBuffer(length, initialize, workspace); } @Override public DataBuffer create(ByteBuffer underlyingBuffer, DataType dataType, long length, long offset) { switch (dataType) { case DOUBLE: return new DoubleBuffer(underlyingBuffer, dataType, length, offset); case FLOAT: return new FloatBuffer(underlyingBuffer, dataType, length, offset); case HALF: return new HalfBuffer(underlyingBuffer, dataType, length, offset); case BFLOAT16: return new BFloat16Buffer(underlyingBuffer, dataType, length, offset); case LONG: return new LongBuffer(underlyingBuffer, dataType, length, offset); case INT: return new IntBuffer(underlyingBuffer, dataType, length, offset); case SHORT: return new Int16Buffer(underlyingBuffer, dataType, length, offset); case UBYTE: return new UInt8Buffer(underlyingBuffer, dataType, length, offset); case UINT16: return new UInt16Buffer(underlyingBuffer, dataType, length, offset); case UINT32: return new UInt32Buffer(underlyingBuffer, dataType, length, offset); case UINT64: return new UInt64Buffer(underlyingBuffer, dataType, length, offset); case BYTE: return new Int8Buffer(underlyingBuffer, dataType, length, offset); case BOOL: return new BoolBuffer(underlyingBuffer, dataType, length, offset); case UTF8: return new Utf8Buffer(underlyingBuffer, dataType, length, offset); default: throw new IllegalStateException("Unknown datatype used: [" + dataType + "]"); } } @Override public DataBuffer create(@NonNull DataType dataType, long length, boolean initialize) { switch (dataType) { case DOUBLE: return new DoubleBuffer(length, initialize); case FLOAT: return new FloatBuffer(length, initialize); case HALF: return new HalfBuffer(length, initialize); case BFLOAT16: return new BFloat16Buffer(length, initialize); case LONG: return new LongBuffer(length, initialize); case INT: return new IntBuffer(length, initialize); case SHORT: return new Int16Buffer(length, initialize); case UBYTE: return new UInt8Buffer(length, initialize); case UINT16: return new UInt16Buffer(length, initialize); case UINT32: return new UInt32Buffer(length, initialize); case UINT64: return new UInt64Buffer(length, initialize); case BYTE: return new Int8Buffer(length, initialize); case BOOL: return new BoolBuffer(length, initialize); case UTF8: return new Utf8Buffer(length, true); default: throw new IllegalStateException("Unknown datatype used: [" + dataType + "]"); } } @Override public DataBuffer create(DataType dataType, long length, boolean initialize, MemoryWorkspace workspace) { switch (dataType) { case DOUBLE: return new DoubleBuffer(length, initialize, workspace); case FLOAT: return new FloatBuffer(length, initialize, workspace); case BFLOAT16: return new BFloat16Buffer(length, initialize, workspace); case HALF: return new HalfBuffer(length, initialize, workspace); case LONG: return new LongBuffer(length, initialize, workspace); case INT: return new IntBuffer(length, initialize, workspace); case SHORT: return new Int16Buffer(length, initialize, workspace); case UBYTE: return new UInt8Buffer(length, initialize, workspace); case UINT16: return new UInt16Buffer(length, initialize, workspace); case UINT32: return new UInt32Buffer(length, initialize, workspace); case UINT64: return new UInt64Buffer(length, initialize, workspace); case BYTE: return new Int8Buffer(length, initialize, workspace); case BOOL: return new BoolBuffer(length, initialize, workspace); default: throw new IllegalStateException("Unknown datatype used: [" + dataType + "]"); } } @Override public DataBuffer createInt(long length) { return new IntBuffer(length); } @Override public DataBuffer createBFloat16(long length) { return new BFloat16Buffer(length); } @Override public DataBuffer createUInt(long length) { return new UInt32Buffer(length); } @Override public DataBuffer createUShort(long length) { return new UInt16Buffer(length); } @Override public DataBuffer createUByte(long length) { return new UInt8Buffer(length); } @Override public DataBuffer createULong(long length) { return new UInt64Buffer(length); } @Override public DataBuffer createBool(long length) { return new BoolBuffer(length); } @Override public DataBuffer createShort(long length) { return new Int16Buffer(length); } @Override public DataBuffer createByte(long length) { return new Int8Buffer(length); } @Override public DataBuffer createBFloat16(long length, boolean initialize) { return new BFloat16Buffer(length, initialize); } @Override public DataBuffer createUInt(long length, boolean initialize) { return new UInt32Buffer(length, initialize); } @Override public DataBuffer createUShort(long length, boolean initialize) { return new UInt16Buffer(length, initialize); } @Override public DataBuffer createUByte(long length, boolean initialize) { return new UInt8Buffer(length, initialize); } @Override public DataBuffer createULong(long length, boolean initialize) { return new UInt64Buffer(length, initialize); } @Override public DataBuffer createBool(long length, boolean initialize) { return new BoolBuffer(length, initialize); } @Override public DataBuffer createShort(long length, boolean initialize) { return new Int16Buffer(length, initialize); } @Override public DataBuffer createByte(long length, boolean initialize) { return new Int8Buffer(length, initialize); } @Override public DataBuffer createInt(long length, boolean initialize) { return new IntBuffer(length, initialize); } @Override public DataBuffer createBFloat16(long length, boolean initialize, MemoryWorkspace workspace) { return new BFloat16Buffer(length, initialize, workspace); } @Override public DataBuffer createUInt(long length, boolean initialize, MemoryWorkspace workspace) { return new UInt32Buffer(length, initialize, workspace); } @Override public DataBuffer createUShort(long length, boolean initialize, MemoryWorkspace workspace) { return new UInt16Buffer(length, initialize, workspace); } @Override public DataBuffer createUByte(long length, boolean initialize, MemoryWorkspace workspace) { return new UInt8Buffer(length, initialize, workspace); } @Override public DataBuffer createULong(long length, boolean initialize, MemoryWorkspace workspace) { return new UInt64Buffer(length, initialize, workspace); } @Override public DataBuffer createBool(long length, boolean initialize, MemoryWorkspace workspace) { return new BoolBuffer(length, initialize, workspace); } @Override public DataBuffer createShort(long length, boolean initialize, MemoryWorkspace workspace) { return new Int16Buffer(length, initialize, workspace); } @Override public DataBuffer createByte(long length, boolean initialize, MemoryWorkspace workspace) { return new Int8Buffer(length, initialize, workspace); } @Override public DataBuffer createInt(long length, boolean initialize, MemoryWorkspace workspace) { return new IntBuffer(length, initialize, workspace); } /** * This method will create new DataBuffer of the same dataType & same length * * @param buffer * @return */ @Override public DataBuffer createSame(DataBuffer buffer, boolean init) { return create(buffer.dataType(), buffer.length(), init); } /** * This method will create new DataBuffer of the same dataType & same length * * @param buffer * @param workspace * @return */ @Override public DataBuffer createSame(DataBuffer buffer, boolean init, MemoryWorkspace workspace) { return create(buffer.dataType(), buffer.length(), init, workspace); } @Override public DataBuffer createDouble(int[] data) { return createDouble(data, true); } @Override public DataBuffer createFloat(int[] data) { return createFloat(data, true); } @Override public DataBuffer createInt(int[] data) { return createInt(data, true); } @Override public DataBuffer createInt(int[] data, MemoryWorkspace workspace) { return createInt(data, true, workspace); } @Override public DataBuffer createInt(int[] data, boolean copy, MemoryWorkspace workspace) { return new IntBuffer(data, copy, workspace); } @Override public DataBuffer createDouble(double[] data) { return createDouble(data, true); } @Override public DataBuffer createFloat(double[] data) { return createFloat(data, true); } @Override public DataBuffer createInt(double[] data) { return createInt(data, true); } @Override public DataBuffer createDouble(float[] data) { return createDouble(data, true); } @Override public DataBuffer createFloat(float[] data) { return createFloat(data, true); } @Override public DataBuffer createFloat(float[] data, MemoryWorkspace workspace) { return createFloat(data, true, workspace); } @Override public DataBuffer createInt(float[] data) { return createInt(data, true); } @Override public DataBuffer createDouble(int[] data, boolean copy) { return new DoubleBuffer(ArrayUtil.toDoubles(data), copy); } @Override public DataBuffer createFloat(int[] data, boolean copy) { return new FloatBuffer(ArrayUtil.toFloats(data), copy); } @Override public DataBuffer createInt(int[] data, boolean copy) { return new IntBuffer(data, copy); } @Override public DataBuffer createLong(int[] data, boolean copy) { return new LongBuffer(ArrayUtil.toLongArray(data), copy); } @Override public DataBuffer createDouble(long[] data, boolean copy) { return new DoubleBuffer(ArrayUtil.toDouble(data), copy); } @Override public DataBuffer createFloat(long[] data, boolean copy) { return new FloatBuffer(ArrayUtil.toFloats(data), copy); } @Override public DataBuffer createInt(long[] data, boolean copy) { return new IntBuffer(ArrayUtil.toInts(data), copy); } @Override public DataBuffer createLong(long[] data) { return createLong(data, true); } @Override public DataBuffer createLong(long[] data, boolean copy) { return new LongBuffer(data, copy); } @Override public DataBuffer createLong(long[] data, MemoryWorkspace workspace) { return new LongBuffer(data, true, workspace); } @Override public DataBuffer createLong(long length) { return new LongBuffer(length); } @Override public DataBuffer createLong(long length, boolean initialize) { return new LongBuffer(length, initialize); } @Override public DataBuffer createLong(long length, boolean initialize, MemoryWorkspace workspace) { return new LongBuffer(length, initialize, workspace); } @Override public DataBuffer createDouble(double[] data, boolean copy) { return new DoubleBuffer(data, copy); } @Override public DataBuffer createDouble(double[] data, MemoryWorkspace workspace) { return createDouble(data, true, workspace); } @Override public DataBuffer createDouble(double[] data, boolean copy, MemoryWorkspace workspace) { return new DoubleBuffer(data, copy, workspace); } @Override public DataBuffer createDouble(long length, boolean initialize, MemoryWorkspace workspace) { return new DoubleBuffer(length, initialize, workspace); } @Override public DataBuffer createFloat(double[] data, boolean copy) { return new FloatBuffer(ArrayUtil.toFloats(data), copy); } @Override public DataBuffer createInt(double[] data, boolean copy) { return new IntBuffer(ArrayUtil.toInts(data), copy); } @Override public DataBuffer createDouble(float[] data, boolean copy) { return new DoubleBuffer(data, copy); } @Override public DataBuffer createFloat(float[] data, boolean copy) { return new FloatBuffer(data, copy); } @Override public DataBuffer createFloat(float[] data, boolean copy, MemoryWorkspace workspace) { return new FloatBuffer(data, copy, workspace); } @Override public DataBuffer createInt(float[] data, boolean copy) { return new IntBuffer(ArrayUtil.toInts(data), copy); } /** * Create a data buffer based on the * given pointer, data buffer opType, * and length of the buffer * * @param pointer the pointer to use * @param type the opType of buffer * @param length the length of the buffer * @param indexer the indexer for the pointer * @return the data buffer * backed by this pointer with the given * opType and length. */ @Override public DataBuffer create(Pointer pointer, DataType type, long length, @NonNull Indexer indexer) { switch (type) { case BOOL: return new BoolBuffer(pointer, indexer, length); case BYTE: return new Int8Buffer(pointer, indexer, length); case UBYTE: return new UInt8Buffer(pointer, indexer, length); case UINT16: return new UInt16Buffer(pointer, indexer, length); case UINT32: return new UInt32Buffer(pointer, indexer, length); case UINT64: return new UInt64Buffer(pointer, indexer, length); case SHORT: return new Int16Buffer(pointer, indexer, length); case INT: return new IntBuffer(pointer, indexer, length); case LONG: return new LongBuffer(pointer, indexer, length); case HALF: return new HalfBuffer(pointer, indexer, length); case BFLOAT16: return new BFloat16Buffer(pointer, indexer, length); case FLOAT: return new FloatBuffer(pointer, indexer, length); case DOUBLE: return new DoubleBuffer(pointer, indexer, length); } throw new IllegalArgumentException("Invalid opType " + type); } @Override public DataBuffer create(Pointer pointer, Pointer specialPointer, DataType type, long length, @NonNull Indexer indexer) { return create(pointer, type, length, indexer); } /** * @param doublePointer * @param length * @return */ @Override public DataBuffer create(DoublePointer doublePointer, long length) { doublePointer.capacity(length); doublePointer.limit(length); doublePointer.position(0); return new DoubleBuffer(doublePointer, DoubleIndexer.create(doublePointer), length); } /** * @param intPointer * @param length * @return */ @Override public DataBuffer create(IntPointer intPointer, long length) { intPointer.capacity(length); intPointer.limit(length); intPointer.position(0); return new IntBuffer(intPointer, IntIndexer.create(intPointer), length); } /** * @param floatPointer * @param length * @return */ @Override public DataBuffer create(FloatPointer floatPointer, long length) { floatPointer.capacity(length); floatPointer.limit(length); floatPointer.position(0); return new FloatBuffer(floatPointer, FloatIndexer.create(floatPointer), length); } @Override public DataBuffer createHalf(long length) { return new HalfBuffer(length); } @Override public DataBuffer createHalf(long length, boolean initialize) { return new HalfBuffer(length, initialize); } /** * Creates a half-precision data buffer * * @param data the data to create the buffer from * @param copy * @return the new buffer */ @Override public DataBuffer createHalf(float[] data, boolean copy) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param data the data to create the buffer from * @param copy * @return the new buffer */ @Override public DataBuffer createHalf(double[] data, boolean copy) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param offset * @param data the data to create the buffer from * @param copy * @return the new buffer */ @Override public DataBuffer createHalf(long offset, double[] data, boolean copy) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param offset * @param data the data to create the buffer from * @param copy * @return the new buffer */ @Override public DataBuffer createHalf(long offset, float[] data, boolean copy) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param offset * @param data the data to create the buffer from * @param copy * @return the new buffer */ @Override public DataBuffer createHalf(long offset, int[] data, boolean copy) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param offset * @param data the data to create the buffer from * @return the new buffer */ @Override public DataBuffer createHalf(long offset, double[] data) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param offset * @param data the data to create the buffer from * @return the new buffer */ @Override public DataBuffer createHalf(long offset, float[] data) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } @Override public DataBuffer createHalf(long offset, float[] data, MemoryWorkspace workspace) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param offset * @param data the data to create the buffer from * @return the new buffer */ @Override public DataBuffer createHalf(long offset, int[] data) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param offset * @param data the data to create the buffer from * @param copy * @return the new buffer */ @Override public DataBuffer createHalf(long offset, byte[] data, boolean copy) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param data the data to create the buffer from * @param copy * @return the new buffer */ @Override public DataBuffer createHalf(int[] data, boolean copy) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param data the data to create the buffer from * @return the new buffer */ @Override public DataBuffer createHalf(float[] data) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param data the data to create the buffer from * @return the new buffer */ @Override public DataBuffer createHalf(double[] data) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param data the data to create the buffer from * @return the new buffer */ @Override public DataBuffer createHalf(int[] data) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } /** * Creates a half-precision data buffer * * @param offset * @param length * @return the new buffer */ @Override public DataBuffer createHalf(long offset, int length) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } @Override public DataBuffer createHalf(long length, boolean initialize, MemoryWorkspace workspace) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } @Override public DataBuffer createHalf(float[] data, MemoryWorkspace workspace) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } @Override public DataBuffer createHalf(float[] data, boolean copy, MemoryWorkspace workspace) { throw new UnsupportedOperationException("FP16 isn't supported for CPU yet"); } @Override public Class<? extends DataBuffer> intBufferClass() { return IntBuffer.class; } @Override public Class<? extends DataBuffer> longBufferClass() { return LongBuffer.class; } @Override public Class<? extends DataBuffer> halfBufferClass() { return null; //Not yet supported } @Override public Class<? extends DataBuffer> floatBufferClass() { return FloatBuffer.class; } @Override public Class<? extends DataBuffer> doubleBufferClass() { return DoubleBuffer.class; } public DataBuffer createUtf8Buffer(byte[] data, long product) { return new Utf8Buffer(data, product); } }
/** * */ package me.learn.personal.month5; import java.util.ArrayList; import java.util.List; /** * Title 131: * * Date : Dec 22, 2020 * * @author bramanarayan * */ public class PalindromePartitioning { /** * @param args */ public static void main(String[] args) { PalindromePartitioning solution = new PalindromePartitioning(); System.out.println(solution.partition("aab")); } List<List<String>> result = new ArrayList<>(); // Return the list of all possible palindromes public List<List<String>> partition(String s) { dfs(s, 0, new ArrayList<String>()); return result; } private void dfs(String s, int start, ArrayList<String> temp) { if(start == s.length()) { result.add(new ArrayList<String>(temp)); } for(int i = start;i< s.length(); i++) { if(isPalindrome(s, start, i)) { temp.add(s.substring(start, i+1)); dfs(s, i+1, temp); temp.remove(temp.size()-1); } } } private boolean isPalindrome(String s, int start, int end) { int lo = start; int high = end; while (lo <= high) { if(s.charAt(lo) != s.charAt(high)) return false; lo++; high--; } return true; } }
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.commons.util; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; /** * @author Lars Helge Overland */ class ExpressionFunctionsTest { @Test void testDaysBetween() { assertEquals( new Long( 1 ), ExpressionFunctions.daysBetween( "2014-03-04", "2014-03-05" ) ); assertEquals( new Long( 32 ), ExpressionFunctions.daysBetween( "2015-04-04", "2015-05-06" ) ); } }
/* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.cloud.loadbalancer.cache; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import com.stoyanr.evictor.map.ConcurrentHashMapWithTimedEviction; import com.stoyanr.evictor.scheduler.DelayedTaskEvictionScheduler; import org.springframework.cache.Cache; import org.springframework.lang.Nullable; import static org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME; /** * An {@link DefaultLoadBalancerCache}-based {@link LoadBalancerCacheManager} * implementation. * * NOTE: This is a very basic implementation as required for the LoadBalancer caching * mechanism at the moment. The underlying implementation can be modified in future to * allow for passing different properties per cache name. * * @author Olga Maciaszek-Sharma * @since 2.2.0 * @see <a href="https://github.com/stoyanr/Evictor">Evictor</a> * @see ConcurrentHashMapWithTimedEviction */ public class DefaultLoadBalancerCacheManager implements LoadBalancerCacheManager { private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>(16); public DefaultLoadBalancerCacheManager(LoadBalancerCacheProperties loadBalancerCacheProperties, String... cacheNames) { cacheMap.putAll(createCaches(cacheNames, loadBalancerCacheProperties).stream() .collect(Collectors.toMap(DefaultLoadBalancerCache::getName, cache -> cache))); } public DefaultLoadBalancerCacheManager(LoadBalancerCacheProperties loadBalancerCacheProperties) { this(loadBalancerCacheProperties, SERVICE_INSTANCE_CACHE_NAME); } private Set<DefaultLoadBalancerCache> createCaches(String[] cacheNames, LoadBalancerCacheProperties loadBalancerCacheProperties) { return Arrays.stream(cacheNames).distinct() .map(name -> new DefaultLoadBalancerCache(name, new ConcurrentHashMapWithTimedEviction<>(loadBalancerCacheProperties.getCapacity(), new DelayedTaskEvictionScheduler<>(aScheduledDaemonThreadExecutor())), loadBalancerCacheProperties.getTtl().toMillis(), false)) .collect(Collectors.toSet()); } private ScheduledExecutorService aScheduledDaemonThreadExecutor() { return Executors.newSingleThreadScheduledExecutor(runnable -> { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setDaemon(true); return thread; }); } @Override @Nullable public Cache getCache(String name) { return cacheMap.get(name); } @Override public Collection<String> getCacheNames() { return Collections.unmodifiableSet(cacheMap.keySet()); } }
package kr.msleague.bcsp.internal.netty.pipeline; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.ReadTimeoutException; import kr.msleague.bcsp.internal.logger.BCSPLogManager; import kr.msleague.bcsp.internal.netty.channel.ChannelWrapper; import kr.msleague.bcsp.internal.netty.channel.DisconnectHandler; import kr.msleague.bcsp.internal.netty.channel.PacketPreProcessHandler; import kr.msleague.bcsp.internal.netty.exception.ByteBufException; import kr.msleague.bcsp.internal.netty.exception.PacketException; import kr.msleague.bcsp.internal.netty.packet.AbstractPacket; import kr.msleague.bcsp.internal.netty.packet.Direction; import kr.msleague.bcsp.internal.netty.packet.sys.HandShakePacket; import lombok.Getter; import lombok.Setter; import java.io.IOException; public class BossHandler extends ChannelInboundHandlerAdapter { @Setter private PacketPreProcessHandler packetPreProcessHandler; @Setter private DisconnectHandler disconnectHandler; @Getter private ConnectionState connectionState; @Getter private ChannelWrapper wrapper; public BossHandler(Channel channel) { this.wrapper = new ChannelWrapper(this, channel); this.connectionState = ConnectionState.IDLE; } public void setConnectionState(ConnectionState state) { this.connectionState = state; BCSPLogManager.getLogger().info("Internal netty connection state is now : " + state.toString()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (this.connectionState != ConnectionState.CONNECTED && !(msg instanceof HandShakePacket)) { BCSPLogManager.getLogger().err("BCSP recieved packet before handshake. Recieved packet dropped."); return; } AbstractPacket packet = (AbstractPacket) msg; if (packetPreProcessHandler != null) packetPreProcessHandler.preprocess(packet, this.getWrapper()); if (packet.isCallBackResult() && getWrapper().getCallBackContainer().complete(packet)) { return; } Direction.INBOUND.onPacketRecieved(packet, wrapper); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof IOException) { BCSPLogManager.getLogger().err("BCSP IOException"); } else if (cause instanceof ByteBufException) { BCSPLogManager.getLogger().err("BCSP Encountered exception while ByteBuf R/W: " + cause.getMessage()); } else if (cause instanceof PacketException) { BCSPLogManager.getLogger().err("BCSP Encountered exception while Packet R/W: " + cause.getMessage()); } else if (cause instanceof ReadTimeoutException) { BCSPLogManager.getLogger().err("BCSP Encountered read timeout exception. Maybe connection broke?"); } else { BCSPLogManager.getLogger().err("BCSP Encountered Exception"); } cause.printStackTrace(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { setConnectionState(ConnectionState.IDLE); if (disconnectHandler != null) { disconnectHandler.onDisconnect(this.getWrapper()); } } }
package com.linkorz.appbase; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
package org.jlab.dtm.business.params; import java.util.Date; import org.jlab.dtm.persistence.enumeration.BinSize; import org.jlab.dtm.persistence.enumeration.RootCause; public class FsdSummaryReportParams { private Date start; private Date end; private Integer maxDuration; private String maxDurationUnits; private Integer maxTypes; private String grouping; private BinSize binSize; private Integer maxY; private String[] legendDataArray; private String chart; private String tripRateBasis; private Boolean sadTrips; private RootCause[] causeArray; public Integer getMaxDuration() { return maxDuration; } public void setMaxDuration(Integer maxDuration) { this.maxDuration = maxDuration; } public String getMaxDurationUnits() { return maxDurationUnits; } public void setMaxDurationUnits(String maxDurationUnits) { this.maxDurationUnits = maxDurationUnits; } public Integer getMaxTypes() { return maxTypes; } public void setMaxTypes(Integer maxTypes) { this.maxTypes = maxTypes; } public String getGrouping() { return grouping; } public void setGrouping(String grouping) { this.grouping = grouping; } public BinSize getBinSize() { return binSize; } public void setBinSize(BinSize binSize) { this.binSize = binSize; } public Integer getMaxY() { return maxY; } public void setMaxY(Integer maxY) { this.maxY = maxY; } public String[] getLegendDataArray() { return legendDataArray; } public void setLegendDataArray(String[] legendDataArray) { this.legendDataArray = legendDataArray; } public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } public Date getEnd() { return end; } public void setEnd(Date end) { this.end = end; } public String getChart() { return chart; } public void setChart(String chart) { this.chart = chart; } public String getTripRateBasis() { return tripRateBasis; } public void setTripRateBasis(String tripRateBasis) { this.tripRateBasis = tripRateBasis; } public Boolean getSadTrips() { return sadTrips; } public void setSadTrips(Boolean sadTrips) { this.sadTrips = sadTrips; } public RootCause[] getCauseArray() { return causeArray; } public void setCauseArray(RootCause[] causeArray) { this.causeArray = causeArray; } }
/* * Copyright 2010 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.drools.kiesession.debug; import java.util.Comparator; public class RightMemorySizeComparator implements Comparator<NodeInfo>{ public int compare(NodeInfo o1, NodeInfo o2) { return (int) ( o2.getFactMemorySize() - o1.getFactMemorySize()) ; } }
package com.github.wolfshotz.wyrmroost.registry; import com.github.wolfshotz.wyrmroost.Wyrmroost; import com.github.wolfshotz.wyrmroost.blocks.tile.WRSignBlockEntity; import com.github.wolfshotz.wyrmroost.util.ModUtils; import net.minecraft.world.level.block.Block; import net.minecraft.client.renderer.blockentity.SignRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import javax.annotation.Nullable; import java.util.function.Function; import java.util.function.Supplier; public class WRBlockEntities<T extends BlockEntity> extends BlockEntityType<T> { public static final DeferredRegister<BlockEntityType<?>> REGISTRY = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, Wyrmroost.MOD_ID); public static final RegistryObject<BlockEntityType<?>> CUSTOM_SIGN = register("sign", WRSignBlockEntity::new, () -> SignRenderer::new); @Nullable private final Supplier<Function<BlockEntityRenderDispatcher, BlockEntityRenderer<T>>> renderer; public WRBlockEntities(Supplier<? extends T> factory, Supplier<Function<BlockEntityRenderDispatcher, BlockEntityRenderer<T>>> renderer) { super(factory, null, null); this.renderer = renderer; } @Override public boolean isValid(Block block) { return block instanceof Validator && ((Validator) block).isValidEntity(this); } public void callBack() { if (ModUtils.isClient() && renderer != null) ClientRegistry.bindTileEntityRenderer(this, renderer.get()); } public static <T extends BlockEntity> RegistryObject<BlockEntityType<?>> register(String name, Supplier<T> factory, @Nullable Supplier<Function<BlockEntityRenderDispatcher, BlockEntityRenderer<T>>> renderer) { return REGISTRY.register(name, () -> new WRBlockEntities<>(factory, renderer)); } public interface Validator { boolean isValidEntity(BlockEntityType<?> type); } }
package org.tain; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class KieaSpringbootSecuritySimple0ApplicationTests { @Test void contextLoads() { } }
/* Copyright (c) 2016, Shanghai YUEWEN Information Technology Co., Ltd. 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 Shanghai YUEWEN Information Technology Co., Ltd. * 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 SHANGHAI YUEWEN INFORMATION TECHNOLOGY CO., LTD. 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 REGENTS AND 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. Copyright (c) 2016 著作权由上海阅文信息技术有限公司所有。著作权人保留一切权利。 这份授权条款,在使用者符合以下三条件的情形下,授予使用者使用及再散播本软件包装原始码及二进位可执行形式的权利,无论此包装是否经改作皆然: * 对于本软件源代码的再散播,必须保留上述的版权宣告、此三条件表列,以及下述的免责声明。 * 对于本套件二进位可执行形式的再散播,必须连带以文件以及/或者其他附于散播包装中的媒介方式,重制上述之版权宣告、此三条件表列,以及下述的免责声明。 * 未获事前取得书面许可,不得使用柏克莱加州大学或本软件贡献者之名称,来为本软件之衍生物做任何表示支持、认可或推广、促销之行为。 免责声明:本软件是由上海阅文信息技术有限公司及本软件之贡献者以现状提供,本软件包装不负任何明示或默示之担保责任, 包括但不限于就适售性以及特定目的的适用性为默示性担保。加州大学董事会及本软件之贡献者,无论任何条件、无论成因或任何责任主义、 无论此责任为因合约关系、无过失责任主义或因非违约之侵权(包括过失或其他原因等)而起,对于任何因使用本软件包装所产生的任何直接性、间接性、 偶发性、特殊性、惩罚性或任何结果的损害(包括但不限于替代商品或劳务之购用、使用损失、资料损失、利益损失、业务中断等等), 不负任何责任,即在该种使用已获事前告知可能会造成此类损害的情形下亦然。 */ package org.albianj.persistence.impl.dbcached; import org.albianj.cached.service.IAlbianCachedService; import org.albianj.persistence.object.IAlbianObject; import org.albianj.service.AlbianServiceRouter; import org.albianj.verify.Validate; public class AlbianPersistenceCacheThread implements Runnable { private String name = null; private String key = null; private Object value = null; private int tto = 300; public AlbianPersistenceCacheThread(String name, String key, Object value, int tto) { this.name = name; this.key = key; this.value = value; this.tto = tto; } @Override public void run() { IAlbianCachedService acs = AlbianServiceRouter.getSingletonService( IAlbianCachedService.class, IAlbianCachedService.Name); try { if (null != acs) { acs.set(Validate.isNullOrEmptyOrAllSpace(name) ? IAlbianObject.AlbianObjectCachedNameDefault : name, key, value, tto); } } catch (Exception e) { } } }
/** * Copyright 2005-2013 Dozer 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 org.dozer.classmap; import org.apache.commons.lang3.StringUtils; /** * @author dmitry.buzdin */ public final class MappingDirection { private static final String BI_DIRECTIONAL_VALUE = "bi-directional"; private static final String ONE_WAY_VALUE = "one-way"; /** * Default mapping approach when a -> b -> a' then a == a' */ public static final MappingDirection BI_DIRECTIONAL = new MappingDirection(); /** * Unidirectional mapping when a -> b -> a' then a != a' */ public static final MappingDirection ONE_WAY = new MappingDirection(); public static MappingDirection valueOf(String mappingDirection) { if (BI_DIRECTIONAL_VALUE.equals(mappingDirection)) { return BI_DIRECTIONAL; } else if (ONE_WAY_VALUE.equals(mappingDirection)) { return ONE_WAY; } else if (StringUtils.isEmpty(mappingDirection)) { return null; } throw new IllegalStateException("type should be bi-directional or one-way. " + mappingDirection); } }
package com.test.project.mapper; import com.test.project.entity.Identity; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Component; import java.util.List; @Mapper @Component public interface IdentityMapper { /** * 根据主键删除一条记录 * * @param id 主键id * @return 删除结果 */ @Delete("delete from identity where id = #{id}") int deleteByPrimaryKey(Integer id); /** * 添加一条记录 * * @param record 记录 * @return 添加结果 */ @Insert("insert into identity (description) values (#{description})") int insert(Identity record); /** * 根据主键查询信息 * * @param id 主键id * @return 查询结果 */ @Select("select id, description from identity where id = #{id};") Identity selectByPrimaryKey(Integer id); @Select("select id, description from identity") @Results(id = "identity", value = { @Result(property = "id", column = "id", javaType = Integer.class), @Result(property = "description", column = "description", javaType = String.class), }) List<Identity> getAll(); /** * 更新记录 * * @param record 记录 * @return 更新结果 */ @Update("update identity set description = #{description} where id = #{id}") int updateByPrimaryKey(Identity record); /** * 通过用户名查找用户角色 * * @param username 用户名 * @return 查询结果 */ @Select("select id, description from identity where id = (select identity from user where username = #{username})") List<Identity> findByUsername(String username); }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v7/services/feed_item_target_service.proto package com.google.ads.googleads.v7.services; /** * <pre> * Request message for [FeedItemTargetService.MutateFeedItemTargets][google.ads.googleads.v7.services.FeedItemTargetService.MutateFeedItemTargets]. * </pre> * * Protobuf type {@code google.ads.googleads.v7.services.MutateFeedItemTargetsRequest} */ public final class MutateFeedItemTargetsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v7.services.MutateFeedItemTargetsRequest) MutateFeedItemTargetsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MutateFeedItemTargetsRequest.newBuilder() to construct. private MutateFeedItemTargetsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateFeedItemTargetsRequest() { customerId_ = ""; operations_ = java.util.Collections.emptyList(); responseContentType_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateFeedItemTargetsRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MutateFeedItemTargetsRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); customerId_ = s; break; } case 18: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { operations_ = new java.util.ArrayList<com.google.ads.googleads.v7.services.FeedItemTargetOperation>(); mutable_bitField0_ |= 0x00000001; } operations_.add( input.readMessage(com.google.ads.googleads.v7.services.FeedItemTargetOperation.parser(), extensionRegistry)); break; } case 24: { validateOnly_ = input.readBool(); break; } case 32: { partialFailure_ = input.readBool(); break; } case 40: { int rawValue = input.readEnum(); responseContentType_ = rawValue; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { operations_ = java.util.Collections.unmodifiableList(operations_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v7.services.FeedItemTargetServiceProto.internal_static_google_ads_googleads_v7_services_MutateFeedItemTargetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v7.services.FeedItemTargetServiceProto.internal_static_google_ads_googleads_v7_services_MutateFeedItemTargetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest.class, com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest.Builder.class); } public static final int CUSTOMER_ID_FIELD_NUMBER = 1; private volatile java.lang.Object customerId_; /** * <pre> * Required. The ID of the customer whose feed item targets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ @java.lang.Override public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } } /** * <pre> * Required. The ID of the customer whose feed item targets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OPERATIONS_FIELD_NUMBER = 2; private java.util.List<com.google.ads.googleads.v7.services.FeedItemTargetOperation> operations_; /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v7.services.FeedItemTargetOperation> getOperationsList() { return operations_; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v7.services.FeedItemTargetOperationOrBuilder> getOperationsOrBuilderList() { return operations_; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public int getOperationsCount() { return operations_.size(); } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public com.google.ads.googleads.v7.services.FeedItemTargetOperation getOperations(int index) { return operations_.get(index); } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ @java.lang.Override public com.google.ads.googleads.v7.services.FeedItemTargetOperationOrBuilder getOperationsOrBuilder( int index) { return operations_.get(index); } public static final int PARTIAL_FAILURE_FIELD_NUMBER = 4; private boolean partialFailure_; /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 4;</code> * @return The partialFailure. */ @java.lang.Override public boolean getPartialFailure() { return partialFailure_; } public static final int RESPONSE_CONTENT_TYPE_FIELD_NUMBER = 5; private int responseContentType_; /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return The enum numeric value on the wire for responseContentType. */ @java.lang.Override public int getResponseContentTypeValue() { return responseContentType_; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return The responseContentType. */ @java.lang.Override public com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() { @SuppressWarnings("deprecation") com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType.valueOf(responseContentType_); return result == null ? com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; private boolean validateOnly_; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_); } for (int i = 0; i < operations_.size(); i++) { output.writeMessage(2, operations_.get(i)); } if (validateOnly_ != false) { output.writeBool(3, validateOnly_); } if (partialFailure_ != false) { output.writeBool(4, partialFailure_); } if (responseContentType_ != com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) { output.writeEnum(5, responseContentType_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_); } for (int i = 0; i < operations_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, operations_.get(i)); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, validateOnly_); } if (partialFailure_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, partialFailure_); } if (responseContentType_ != com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(5, responseContentType_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest)) { return super.equals(obj); } com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest other = (com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest) obj; if (!getCustomerId() .equals(other.getCustomerId())) return false; if (!getOperationsList() .equals(other.getOperationsList())) return false; if (getPartialFailure() != other.getPartialFailure()) return false; if (responseContentType_ != other.responseContentType_) return false; if (getValidateOnly() != other.getValidateOnly()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER; hash = (53 * hash) + getCustomerId().hashCode(); if (getOperationsCount() > 0) { hash = (37 * hash) + OPERATIONS_FIELD_NUMBER; hash = (53 * hash) + getOperationsList().hashCode(); } hash = (37 * hash) + PARTIAL_FAILURE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getPartialFailure()); hash = (37 * hash) + RESPONSE_CONTENT_TYPE_FIELD_NUMBER; hash = (53 * hash) + responseContentType_; hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getValidateOnly()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Request message for [FeedItemTargetService.MutateFeedItemTargets][google.ads.googleads.v7.services.FeedItemTargetService.MutateFeedItemTargets]. * </pre> * * Protobuf type {@code google.ads.googleads.v7.services.MutateFeedItemTargetsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v7.services.MutateFeedItemTargetsRequest) com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v7.services.FeedItemTargetServiceProto.internal_static_google_ads_googleads_v7_services_MutateFeedItemTargetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v7.services.FeedItemTargetServiceProto.internal_static_google_ads_googleads_v7_services_MutateFeedItemTargetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest.class, com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest.Builder.class); } // Construct using com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getOperationsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); customerId_ = ""; if (operationsBuilder_ == null) { operations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { operationsBuilder_.clear(); } partialFailure_ = false; responseContentType_ = 0; validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v7.services.FeedItemTargetServiceProto.internal_static_google_ads_googleads_v7_services_MutateFeedItemTargetsRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest getDefaultInstanceForType() { return com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest build() { com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest buildPartial() { com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest result = new com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest(this); int from_bitField0_ = bitField0_; result.customerId_ = customerId_; if (operationsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { operations_ = java.util.Collections.unmodifiableList(operations_); bitField0_ = (bitField0_ & ~0x00000001); } result.operations_ = operations_; } else { result.operations_ = operationsBuilder_.build(); } result.partialFailure_ = partialFailure_; result.responseContentType_ = responseContentType_; result.validateOnly_ = validateOnly_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest) { return mergeFrom((com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest other) { if (other == com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; onChanged(); } if (operationsBuilder_ == null) { if (!other.operations_.isEmpty()) { if (operations_.isEmpty()) { operations_ = other.operations_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureOperationsIsMutable(); operations_.addAll(other.operations_); } onChanged(); } } else { if (!other.operations_.isEmpty()) { if (operationsBuilder_.isEmpty()) { operationsBuilder_.dispose(); operationsBuilder_ = null; operations_ = other.operations_; bitField0_ = (bitField0_ & ~0x00000001); operationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getOperationsFieldBuilder() : null; } else { operationsBuilder_.addAllMessages(other.operations_); } } } if (other.getPartialFailure() != false) { setPartialFailure(other.getPartialFailure()); } if (other.responseContentType_ != 0) { setResponseContentTypeValue(other.getResponseContentTypeValue()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object customerId_ = ""; /** * <pre> * Required. The ID of the customer whose feed item targets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The ID of the customer whose feed item targets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The ID of the customer whose feed item targets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The customerId to set. * @return This builder for chaining. */ public Builder setCustomerId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customerId_ = value; onChanged(); return this; } /** * <pre> * Required. The ID of the customer whose feed item targets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); onChanged(); return this; } /** * <pre> * Required. The ID of the customer whose feed item targets are being modified. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for customerId to set. * @return This builder for chaining. */ public Builder setCustomerIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customerId_ = value; onChanged(); return this; } private java.util.List<com.google.ads.googleads.v7.services.FeedItemTargetOperation> operations_ = java.util.Collections.emptyList(); private void ensureOperationsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { operations_ = new java.util.ArrayList<com.google.ads.googleads.v7.services.FeedItemTargetOperation>(operations_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v7.services.FeedItemTargetOperation, com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder, com.google.ads.googleads.v7.services.FeedItemTargetOperationOrBuilder> operationsBuilder_; /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<com.google.ads.googleads.v7.services.FeedItemTargetOperation> getOperationsList() { if (operationsBuilder_ == null) { return java.util.Collections.unmodifiableList(operations_); } else { return operationsBuilder_.getMessageList(); } } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public int getOperationsCount() { if (operationsBuilder_ == null) { return operations_.size(); } else { return operationsBuilder_.getCount(); } } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v7.services.FeedItemTargetOperation getOperations(int index) { if (operationsBuilder_ == null) { return operations_.get(index); } else { return operationsBuilder_.getMessage(index); } } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setOperations( int index, com.google.ads.googleads.v7.services.FeedItemTargetOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.set(index, value); onChanged(); } else { operationsBuilder_.setMessage(index, value); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setOperations( int index, com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.set(index, builderForValue.build()); onChanged(); } else { operationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addOperations(com.google.ads.googleads.v7.services.FeedItemTargetOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.add(value); onChanged(); } else { operationsBuilder_.addMessage(value); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addOperations( int index, com.google.ads.googleads.v7.services.FeedItemTargetOperation value) { if (operationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureOperationsIsMutable(); operations_.add(index, value); onChanged(); } else { operationsBuilder_.addMessage(index, value); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addOperations( com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(builderForValue.build()); onChanged(); } else { operationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addOperations( int index, com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder builderForValue) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.add(index, builderForValue.build()); onChanged(); } else { operationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addAllOperations( java.lang.Iterable<? extends com.google.ads.googleads.v7.services.FeedItemTargetOperation> values) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, operations_); onChanged(); } else { operationsBuilder_.addAllMessages(values); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder clearOperations() { if (operationsBuilder_ == null) { operations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { operationsBuilder_.clear(); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder removeOperations(int index) { if (operationsBuilder_ == null) { ensureOperationsIsMutable(); operations_.remove(index); onChanged(); } else { operationsBuilder_.remove(index); } return this; } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder getOperationsBuilder( int index) { return getOperationsFieldBuilder().getBuilder(index); } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v7.services.FeedItemTargetOperationOrBuilder getOperationsOrBuilder( int index) { if (operationsBuilder_ == null) { return operations_.get(index); } else { return operationsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<? extends com.google.ads.googleads.v7.services.FeedItemTargetOperationOrBuilder> getOperationsOrBuilderList() { if (operationsBuilder_ != null) { return operationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(operations_); } } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder addOperationsBuilder() { return getOperationsFieldBuilder().addBuilder( com.google.ads.googleads.v7.services.FeedItemTargetOperation.getDefaultInstance()); } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder addOperationsBuilder( int index) { return getOperationsFieldBuilder().addBuilder( index, com.google.ads.googleads.v7.services.FeedItemTargetOperation.getDefaultInstance()); } /** * <pre> * Required. The list of operations to perform on individual feed item targets. * </pre> * * <code>repeated .google.ads.googleads.v7.services.FeedItemTargetOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder> getOperationsBuilderList() { return getOperationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v7.services.FeedItemTargetOperation, com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder, com.google.ads.googleads.v7.services.FeedItemTargetOperationOrBuilder> getOperationsFieldBuilder() { if (operationsBuilder_ == null) { operationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v7.services.FeedItemTargetOperation, com.google.ads.googleads.v7.services.FeedItemTargetOperation.Builder, com.google.ads.googleads.v7.services.FeedItemTargetOperationOrBuilder>( operations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); operations_ = null; } return operationsBuilder_; } private boolean partialFailure_ ; /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 4;</code> * @return The partialFailure. */ @java.lang.Override public boolean getPartialFailure() { return partialFailure_; } /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 4;</code> * @param value The partialFailure to set. * @return This builder for chaining. */ public Builder setPartialFailure(boolean value) { partialFailure_ = value; onChanged(); return this; } /** * <pre> * If true, successful operations will be carried out and invalid * operations will return errors. If false, all operations will be carried * out in one transaction if and only if they are all valid. * Default is false. * </pre> * * <code>bool partial_failure = 4;</code> * @return This builder for chaining. */ public Builder clearPartialFailure() { partialFailure_ = false; onChanged(); return this; } private int responseContentType_ = 0; /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return The enum numeric value on the wire for responseContentType. */ @java.lang.Override public int getResponseContentTypeValue() { return responseContentType_; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @param value The enum numeric value on the wire for responseContentType to set. * @return This builder for chaining. */ public Builder setResponseContentTypeValue(int value) { responseContentType_ = value; onChanged(); return this; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return The responseContentType. */ @java.lang.Override public com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() { @SuppressWarnings("deprecation") com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType.valueOf(responseContentType_); return result == null ? com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @param value The responseContentType to set. * @return This builder for chaining. */ public Builder setResponseContentType(com.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType value) { if (value == null) { throw new NullPointerException(); } responseContentType_ = value.getNumber(); onChanged(); return this; } /** * <pre> * The response content type setting. Determines whether the mutable resource * or just the resource name should be returned post mutation. * </pre> * * <code>.google.ads.googleads.v7.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 5;</code> * @return This builder for chaining. */ public Builder clearResponseContentType() { responseContentType_ = 0; onChanged(); return this; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</code> * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</code> * @return This builder for chaining. */ public Builder clearValidateOnly() { validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v7.services.MutateFeedItemTargetsRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v7.services.MutateFeedItemTargetsRequest) private static final com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest(); } public static com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateFeedItemTargetsRequest> PARSER = new com.google.protobuf.AbstractParser<MutateFeedItemTargetsRequest>() { @java.lang.Override public MutateFeedItemTargetsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MutateFeedItemTargetsRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MutateFeedItemTargetsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateFeedItemTargetsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v7.services.MutateFeedItemTargetsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/** * <copyright> * </copyright> * * $Id$ */ package org.talend.designer.business.model.business.impl; import org.eclipse.emf.ecore.EClass; import org.talend.designer.business.model.business.BusinessPackage; import org.talend.designer.business.model.business.SapFunctionMetadata; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Sap Function Metadata</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class SapFunctionMetadataImpl extends TalendItemImpl implements SapFunctionMetadata { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SapFunctionMetadataImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EClass eStaticClass() { return BusinessPackage.Literals.SAP_FUNCTION_METADATA; } } //SapFunctionMetadataImpl
package com.supensour.swagger.config.defaults; import com.supensour.model.common.DataRegistry; import com.supensour.swagger.config.SwaggerConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.http.ResponseEntity; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.server.ServerWebExchange; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author Suprayan Yapura * @since 0.1.0 */ @Configuration @ConditionalOnClass(value = {EnableSwagger2.class, ServerWebExchange.class}) public class SwaggerWebConfiguration implements SwaggerConfiguration { @Override public void addGenericModelSubstitutes(DataRegistry<Class<?>> registry) { registry.register(ResponseEntity.class); registry.register(DeferredResult.class); } @Override public void addIgnoredParameterTypes(DataRegistry<Class<?>> registry) { registry.register(ServerWebExchange.class); registry.register(ServerHttpRequest.class); registry.register(org.springframework.http.server.reactive.ServerHttpRequest.class); registry.register(ServerHttpResponse.class); registry.register(org.springframework.http.server.reactive.ServerHttpResponse.class); } }
package org.jesperancinha.jtd.jee.teeth.serialization; import java.io.Serializable; // Note that this EJB needs to be serializable because Marshalling is being used to cache objects. // Counterwise, Unmarshalling is being used to retrieve objects from the database. // Without Serialization, passivation is not possible. // Unable to passivate entry under InfinispanBeanGroupKey(UUIDSessionID [7d529385-2808-47fc-af7a-a4bd4709813d]) // Caused by: org.infinispan.commons.marshall.NotSerializableException: org.jesperancinha.jtd.jee.teeth.serialization.PeriodontitisObject public class PeriodontitisObject implements Serializable { private static final long serialVersionUID = 1L; private final String property; public PeriodontitisObject(String value) { this.property = value; } public String getProperty() { return property; } }
/******************************************************************************* * ENdoSnipe 5.0 - (https://github.com/endosnipe) * * The MIT License (MIT) * * Copyright (c) 2012 Acroquest Technology Co.,Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package jp.co.acroquest.test; import java.lang.management.RuntimeMXBean; import jp.co.acroquest.endosnipe.common.config.JavelinConfig; import jp.co.acroquest.endosnipe.common.logger.SystemLogger; import jp.co.acroquest.endosnipe.javelin.conf.AbstractConversionConfig; import jp.co.acroquest.endosnipe.javelin.conf.ExcludeConversionConfig; import jp.co.acroquest.test.util.JavelinTestUtil; import jp.co.dgic.testing.framework.DJUnitTestCase; /** * Javelinの国際化対応用テストクラス * @author tooru * */ public class InternationalizationTest extends DJUnitTestCase { /** Javelinの設定ファイル */ private JavelinConfig config_; /** * 初期化メソッド<br /> * システムログの初期化を行う。 */ @Override public void setUp() throws Exception { super.setUp(); // オプションファイルから、オプション設定を読み込む。 JavelinTestUtil.camouflageJavelinConfig(getClass(), "/telegram/conf/javelin.properties"); this.config_ = new JavelinConfig(); SystemLogger.initSystemLog(this.config_); } /** * 項番: * 4-1-5 */ public void testFailGetProcessID() { addReturnValue(RuntimeMXBean.class, "getName", ""); String str1 = (String)getArgument(SystemLogger.class, "warn", 0, 0); assertEquals("Failed to get process ID.", str1); } // メール通知機能がDataCollectorに移ったため、 // それを使用していた、以下の項番のテストコードを削除した。 // 4-1-9, 16, 17, 18, 19, 20, 21, 22 /** * 項番: * 4-1-23 */ public void testAnIllegalConfigurationLabel1() { AbstractConversionConfig config = new ExcludeConversionConfig(); String str1 = "この文字列が(上書きされること無く)比較されたら失敗。"; try { config.readConfig(""); } catch (IllegalArgumentException ex) { str1 = ex.getMessage(); } assertEquals("An illegal configuration().", str1); } /** * 項番: * 4-1-24 */ public void testAnIllegalConfigurationLabel2() { AbstractConversionConfig config = new ExcludeConversionConfig(); addReturnValue("AbstractConversionConfig", "parseConfig", new Exception("この例外が出るはず。")); String str1 = "この文字列が(上書きされること無く)比較されたら失敗。"; try { config.readConfig("<内容>"); } catch (IllegalArgumentException ex) { str1 = ex.getMessage(); } assertEquals("An illegal configuration(<内容>).", str1); } }
/* * Copyright 2014-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.io.IOException; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder; import com.amazonaws.services.simpleemail.model.Body; import com.amazonaws.services.simpleemail.model.Content; import com.amazonaws.services.simpleemail.model.Destination; import com.amazonaws.services.simpleemail.model.Message; import com.amazonaws.services.simpleemail.model.SendEmailRequest; public class AmazonSESSample { static final String FROM = "SENDER@EXAMPLE.COM"; // Replace with your "From" address. This address must be verified. static final String TO = "RECIPIENT@EXAMPLE.COM"; // Replace with a "To" address. If you have not yet requested // production access, this address must be verified. static final String BODY = "This email was sent through Amazon SES by using the AWS SDK for Java."; static final String SUBJECT = "Amazon SES test (AWS SDK for Java)"; /* * Before running the code: * Fill in your AWS access credentials in the provided credentials * file template, and be sure to move the file to the default location * (~/.aws/credentials) where the sample code will load the * credentials from. * https://console.aws.amazon.com/iam/home?#security_credential * * WARNING: * To avoid accidental leakage of your credentials, DO NOT keep * the credentials file in your source directory. */ public static void main(String[] args) throws IOException { // Construct an object to contain the recipient address. Destination destination = new Destination().withToAddresses(new String[]{TO}); // Create the subject and body of the message. Content subject = new Content().withData(SUBJECT); Content textBody = new Content().withData(BODY); Body body = new Body().withText(textBody); // Create a message with the specified subject and body. Message message = new Message().withSubject(subject).withBody(body); // Assemble the email. SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination).withMessage(message); try { System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java..."); /* * The ProfileCredentialsProvider will return your [default] * credential profile by reading from the credentials file located at * (~/.aws/credentials). * * TransferManager manages a pool of threads, so we create a * single instance and share it throughout our application. */ AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider().getCredentials(); } catch (Exception e) { throw new AmazonClientException( "Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (~/.aws/credentials), and is in valid format.", e); } // Instantiate an Amazon SES client, which will make the service call with the supplied AWS credentials. // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production // access status, sending limits, and Amazon SES identity-related settings are specific to a given // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using // the US West (Oregon) region. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(Regions.US_WEST_2) .build(); // Send the email. client.sendEmail(request); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); } } }
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.thoughtworks.selenium.corebased; import com.thoughtworks.selenium.InternalSelenseTestBase; import org.junit.After; import org.junit.Test; public class TestTypeRichText extends InternalSelenseTestBase { @After public void resetFrame() { selenium.selectFrame("relative=top"); } @Test public void testTypeRichText() { String isIe = selenium.getEval("browserVersion.isIE"); if (Boolean.valueOf(isIe)) { return; } selenium.open("../tests/html/test_rich_text.html"); selenium.selectFrame("richtext"); verifyEquals(selenium.getText("//body"), ""); selenium.type("//body", "hello world"); verifyEquals(selenium.getText("//body"), "hello world"); } }
package com.zjmy.mvp.layout; import android.app.Activity; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; public final class AutoSize { private static SparseArray<DisplayMetricsInfo> mCache = new SparseArray<>(); private static final int MODE_SHIFT = 30; private static final int MODE_MASK = 0x3 << MODE_SHIFT; private static final int MODE_ON_WIDTH = 1 << MODE_SHIFT; private static final int MODE_DEVICE_SIZE = 2 << MODE_SHIFT; private AutoSize() { throw new IllegalStateException("you can't instantiate me!"); } public static void autoConvertDensityOfGlobal(Activity activity) { if (AutoSizeConfig.getInstance().mInitDensity != -1) {//代表已开启屏幕适配 autoConvertDensity(activity); } } /** * 参考今日头条适配方案的核心代码, 核心在于根据当前设备的实际情况做自动计算并转换 {@link DisplayMetrics#density}、 * {@link DisplayMetrics#scaledDensity}、{@link DisplayMetrics#densityDpi} 这三个值 * @param activity {@link Activity} * @see <a href="https://mp.weixin.qq.com/s/d9QCoBP6kV9VSWvVldVVwA">参考今日头条官方适配方案</a> */ public static void autoConvertDensity(Activity activity) { Preconditions.checkNotNull(activity, "activity == null"); Preconditions.checkMainThread(); AutoSizeConfig config = AutoSizeConfig.getInstance(); //是否按照宽度进行等比例适配, {@code true} 为以宽度进行等比例适配, {@code false} 为以高度进行等比例适配 float designSizeInDp = config.isBaseOnWidth ? config.mDesignWidthInDp : config.mDesignHeightInDp; int key = (int)designSizeInDp & ~MODE_MASK;// 基础key值 key = config.isBaseOnWidth ? (key | MODE_ON_WIDTH) : (key & ~MODE_ON_WIDTH); //横竖屏规则变换,需要重新计算,2 key = config.isBaseOnWidth ? (key | MODE_DEVICE_SIZE) : (key & ~MODE_DEVICE_SIZE);//状态栏是否计入,需要重新计算,2 DisplayMetricsInfo displayMetricsInfo = mCache.get(key); float targetDensity ; int targetDensityDpi ; float targetScaledDensity ; if (displayMetricsInfo == null) { if (config.isBaseOnWidth) { targetDensity = config.getScreenWidth() * 1.0f / designSizeInDp; } else { targetDensity = config.getScreenHeight() * 1.0f / designSizeInDp; } float systemFontScale = config.mInitScaledDensity * 1.0f / config.mInitDensity; targetScaledDensity = targetDensity * systemFontScale; targetDensityDpi = (int) (targetDensity * 160); if (mCache.size() > 4){ mCache.clear(); } mCache.put(key, new DisplayMetricsInfo(targetDensity, targetDensityDpi, targetScaledDensity)); Log.e("test","displayMetricsInfo == null,mCacheSize="+mCache.size()); } else { targetDensity = displayMetricsInfo.density; targetDensityDpi = displayMetricsInfo.densityDpi; targetScaledDensity = displayMetricsInfo.scaledDensity; Log.e("test","displayMetricsInfo != null,mCacheSize="+mCache.size()); } setDensity(activity, targetDensity, targetDensityDpi, targetScaledDensity); } /** * {@link DisplayMetrics} 赋值 * * @param activity {@link Activity} * @param density {@link DisplayMetrics#density} * @param densityDpi {@link DisplayMetrics#densityDpi} * @param scaledDensity {@link DisplayMetrics#scaledDensity} */ private static void setDensity(Activity activity, float density, int densityDpi, float scaledDensity) { DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics(); setDensity(activityDisplayMetrics, density, densityDpi, scaledDensity); DisplayMetrics appDisplayMetrics = activity.getApplication().getResources().getDisplayMetrics(); setDensity(appDisplayMetrics, density, densityDpi, scaledDensity); } /** * 赋值 * * @param displayMetrics {@link DisplayMetrics} * @param density {@link DisplayMetrics#density} * @param densityDpi {@link DisplayMetrics#densityDpi} * @param scaledDensity {@link DisplayMetrics#scaledDensity} */ private static void setDensity(DisplayMetrics displayMetrics, float density, int densityDpi, float scaledDensity) { displayMetrics.density = density; displayMetrics.densityDpi = densityDpi; displayMetrics.scaledDensity = scaledDensity; } }
package algorithm.leetcode; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import utils.JsonHelper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * 猜字谜 * * 外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。 * * 字谜的迷面puzzle 按字符串形式给出,如果一个单词word符合下面两个条件,那么它就可以算作谜底: * * 单词word中包含谜面puzzle的第一个字母。 * 单词word中的每一个字母都可以在谜面puzzle中找到。 * 例如,如果字谜的谜面是 "abcdefg",那么可以作为谜底的单词有 "faced", "cabbage", 和 "baggage";而 "beefed"(不含字母 "a")以及"based"(其中的 "s" 没有出现在谜面中)都不能作为谜底。 * 返回一个答案数组answer,数组中的每个元素answer[i]是在给出的单词列表 words 中可以作为字谜迷面puzzles[i]所对应的谜底的单词数目。 * * * * 示例: * * 输入: * words = ["aaaa","asas","able","ability","actt","actor","access"], * puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] * 输出:[1,1,3,2,4,0] * 解释: * 1 个单词可以作为 "aboveyz" 的谜底 : "aaaa" * 1 个单词可以作为 "abrodyz" 的谜底 : "aaaa" * 3 个单词可以作为 "abslute" 的谜底 : "aaaa", "asas", "able" * 2 个单词可以作为"absoryz" 的谜底 : "aaaa", "asas" * 4 个单词可以作为"actresz" 的谜底 : "aaaa", "asas", "actt", "access" * 没有单词可以作为"gaswxyz" 的谜底,因为列表中的单词都不含字母 'g'。 * * * 提示: * * 1 <= words.length <= 10^5 * 4 <= words[i].length <= 50 * 1 <= puzzles.length <= 10^4 * puzzles[i].length == 7 * words[i][j], puzzles[i][j]都是小写英文字母。 * 每个puzzles[i]所包含的字符都不重复。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle */ @Slf4j public class FindNumOfValidWords { // 状态压缩 public List<Integer> findNumOfValidWords(String[] words, String[] puzzles) { Map<Integer, Integer> wordMap = new HashMap<>(); for (String word : words) { int mask = 0; for (int i = 0; i < word.length(); i++) { mask |= (1 << (word.charAt(i) - 'a')); } if (Integer.bitCount(mask) <= 7) { wordMap.put(mask, wordMap.getOrDefault(mask, 0) + 1); } } List<Integer> res = new ArrayList<>(); for (String puzzle : puzzles) { int total = 0; int mask = 0; for (int i = 1; i < 7; i++) { mask |= (1 << (puzzle.charAt(i) - 'a')); } int firstCharAt = puzzle.charAt(0) - 'a'; // 通用枚举二进制子集方法 int subset = mask; do { int s = subset | (1 << firstCharAt); total += wordMap.getOrDefault(s, 0); subset = (subset - 1) & mask; } while (subset != mask); res.add(total); } return res; } @Test public void test() { String[] words = {"aaaa","asas","able","ability","actt","actor","access"}; String[] puzzles = {"aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"}; List<Integer> numOfValidWords = findNumOfValidWords(words, puzzles); log.info(JsonHelper.toJson(numOfValidWords)); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.core.optimize.sharding.engnie.dml; import com.google.common.base.Optional; import com.google.common.collect.Range; import org.apache.shardingsphere.core.metadata.table.ColumnMetaData; import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData; import org.apache.shardingsphere.core.metadata.table.TableMetaData; import org.apache.shardingsphere.core.optimize.sharding.segment.condition.ShardingCondition; import org.apache.shardingsphere.core.optimize.sharding.segment.condition.ShardingConditions; import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.SelectItems; import org.apache.shardingsphere.core.parse.sql.segment.dml.column.ColumnSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.ExpressionSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.simple.LiteralExpressionSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.item.SelectItemsSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.item.ShorthandSelectItemSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.AndPredicate; import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.PredicateSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.WhereSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.value.PredicateBetweenRightValue; import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.value.PredicateCompareRightValue; import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.value.PredicateInRightValue; import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment; import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement; import org.apache.shardingsphere.core.rule.EncryptRule; import org.apache.shardingsphere.core.rule.ShardingRule; import org.apache.shardingsphere.core.strategy.route.value.ListRouteValue; import org.apache.shardingsphere.core.strategy.route.value.RangeRouteValue; import org.apache.shardingsphere.core.strategy.route.value.RouteValue; import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public final class ShardingSelectOptimizeEngineTest { @Mock private ShardingRule shardingRule; @Mock private ShardingTableMetaData shardingTableMetaData; private SelectStatement selectStatement; @Before public void setUp() { when(shardingRule.isShardingColumn("column", "tbl")).thenReturn(true); EncryptRule encryptRule = mock(EncryptRule.class); when(encryptRule.getShardingEncryptor("tbl", "column")).thenReturn(Optional.<ShardingEncryptor>absent()); when(shardingRule.getEncryptRule()).thenReturn(encryptRule); selectStatement = new SelectStatement(); selectStatement.getAllSQLSegments().add(new TableSegment(0, 0, "tbl")); } @Test public void assertOptimizeAlwaysFalseListConditions() { selectStatement.setSelectItems(new SelectItemsSegment(0, 0, false)); Collection<AndPredicate> andPredicates = new LinkedList<>(); AndPredicate andPredicate = new AndPredicate(); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateInRightValue(Arrays.<ExpressionSegment>asList(new LiteralExpressionSegment(0, 0, 1), new LiteralExpressionSegment(0, 0, 2))))); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateCompareRightValue("=", new LiteralExpressionSegment(0, 0, 3)))); andPredicates.add(andPredicate); WhereSegment whereSegment = new WhereSegment(0, 0, 0); whereSegment.getAndPredicates().addAll(andPredicates); selectStatement.setWhere(whereSegment); ShardingConditions shardingConditions = new ShardingSelectOptimizeEngine().optimize(shardingRule, shardingTableMetaData, "", Collections.emptyList(), selectStatement).getShardingConditions(); assertTrue(shardingConditions.isAlwaysFalse()); } @Test public void assertOptimizeAlwaysFalseRangeConditions() { selectStatement.setSelectItems(new SelectItemsSegment(0, 0, false)); Collection<AndPredicate> andPredicates = new LinkedList<>(); AndPredicate andPredicate = new AndPredicate(); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateInRightValue(Arrays.<ExpressionSegment>asList(new LiteralExpressionSegment(0, 0, 1), new LiteralExpressionSegment(0, 0, 2))))); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateInRightValue(Arrays.<ExpressionSegment>asList(new LiteralExpressionSegment(0, 0, 3), new LiteralExpressionSegment(0, 0, 4))))); andPredicates.add(andPredicate); WhereSegment whereSegment = new WhereSegment(0, 0, 0); whereSegment.getAndPredicates().addAll(andPredicates); selectStatement.setWhere(whereSegment); ShardingConditions shardingConditions = new ShardingSelectOptimizeEngine().optimize(shardingRule, shardingTableMetaData, "", Collections.emptyList(), selectStatement).getShardingConditions(); assertTrue(shardingConditions.isAlwaysFalse()); } @Test public void assertOptimizeAlwaysFalseListConditionsAndRangeConditions() { selectStatement.setSelectItems(new SelectItemsSegment(0, 0, false)); Collection<AndPredicate> andPredicates = new LinkedList<>(); AndPredicate andPredicate = new AndPredicate(); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateInRightValue(Arrays.<ExpressionSegment>asList(new LiteralExpressionSegment(0, 0, 1), new LiteralExpressionSegment(0, 0, 2))))); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateBetweenRightValue(new LiteralExpressionSegment(0, 0, 3), new LiteralExpressionSegment(0, 0, 4)))); andPredicates.add(andPredicate); WhereSegment whereSegment = new WhereSegment(0, 0, 0); whereSegment.getAndPredicates().addAll(andPredicates); selectStatement.setWhere(whereSegment); ShardingConditions shardingConditions = new ShardingSelectOptimizeEngine().optimize(shardingRule, shardingTableMetaData, "", Collections.emptyList(), selectStatement).getShardingConditions(); assertTrue(shardingConditions.isAlwaysFalse()); } @SuppressWarnings("unchecked") @Test public void assertOptimizeListConditions() { selectStatement.setSelectItems(new SelectItemsSegment(0, 0, false)); Collection<AndPredicate> andPredicates = new LinkedList<>(); AndPredicate andPredicate = new AndPredicate(); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateInRightValue(Arrays.<ExpressionSegment>asList(new LiteralExpressionSegment(0, 0, 1), new LiteralExpressionSegment(0, 0, 2))))); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateCompareRightValue("=", new LiteralExpressionSegment(0, 0, 1)))); andPredicates.add(andPredicate); WhereSegment whereSegment = new WhereSegment(0, 0, 0); whereSegment.getAndPredicates().addAll(andPredicates); selectStatement.setWhere(whereSegment); ShardingConditions shardingConditions = new ShardingSelectOptimizeEngine().optimize(shardingRule, shardingTableMetaData, "", Collections.emptyList(), selectStatement).getShardingConditions(); assertFalse(shardingConditions.isAlwaysFalse()); ShardingCondition shardingCondition = shardingConditions.getConditions().get(0); RouteValue shardingValue = shardingCondition.getRouteValues().get(0); Collection<Comparable<?>> values = ((ListRouteValue<Comparable<?>>) shardingValue).getValues(); assertThat(values.size(), is(1)); assertTrue(values.containsAll(Collections.singleton(1))); } @SuppressWarnings("unchecked") @Test public void assertOptimizeRangeConditions() { selectStatement.setSelectItems(new SelectItemsSegment(0, 0, false)); Collection<AndPredicate> andPredicates = new LinkedList<>(); AndPredicate andPredicate = new AndPredicate(); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateBetweenRightValue(new LiteralExpressionSegment(0, 0, 1), new LiteralExpressionSegment(0, 0, 2)))); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateBetweenRightValue(new LiteralExpressionSegment(0, 0, 1), new LiteralExpressionSegment(0, 0, 3)))); andPredicates.add(andPredicate); WhereSegment whereSegment = new WhereSegment(0, 0, 0); whereSegment.getAndPredicates().addAll(andPredicates); selectStatement.setWhere(whereSegment); ShardingConditions shardingConditions = new ShardingSelectOptimizeEngine().optimize(shardingRule, shardingTableMetaData, "", Collections.emptyList(), selectStatement).getShardingConditions(); assertFalse(shardingConditions.isAlwaysFalse()); ShardingCondition shardingCondition = shardingConditions.getConditions().get(0); RouteValue shardingValue = shardingCondition.getRouteValues().get(0); Range<Comparable<?>> values = ((RangeRouteValue<Comparable<?>>) shardingValue).getValueRange(); assertThat(values.lowerEndpoint(), CoreMatchers.<Comparable>is(1)); assertThat(values.upperEndpoint(), CoreMatchers.<Comparable>is(2)); } @SuppressWarnings("unchecked") @Test public void assertOptimizeListConditionsAndRangeConditions() { selectStatement.setSelectItems(new SelectItemsSegment(0, 0, false)); Collection<AndPredicate> andPredicates = new LinkedList<>(); AndPredicate andPredicate = new AndPredicate(); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateInRightValue(Arrays.<ExpressionSegment>asList(new LiteralExpressionSegment(0, 0, 1), new LiteralExpressionSegment(0, 0, 2))))); andPredicate.getPredicates().add(new PredicateSegment(0, 0, createColumnSegment(), new PredicateBetweenRightValue(new LiteralExpressionSegment(0, 0, 1), new LiteralExpressionSegment(0, 0, 2)))); andPredicates.add(andPredicate); WhereSegment whereSegment = new WhereSegment(0, 0, 0); whereSegment.getAndPredicates().addAll(andPredicates); selectStatement.setWhere(whereSegment); ShardingConditions shardingConditions = new ShardingSelectOptimizeEngine().optimize(shardingRule, shardingTableMetaData, "", Collections.emptyList(), selectStatement).getShardingConditions(); assertFalse(shardingConditions.isAlwaysFalse()); ShardingCondition shardingCondition = shardingConditions.getConditions().get(0); RouteValue shardingValue = shardingCondition.getRouteValues().get(0); Collection<Comparable<?>> values = ((ListRouteValue<Comparable<?>>) shardingValue).getValues(); assertThat(values.size(), is(2)); assertTrue(values.containsAll(Arrays.asList(1, 2))); } private ColumnSegment createColumnSegment() { ColumnSegment result = new ColumnSegment(0, 0, "column"); result.setOwner(new TableSegment(0, 0, "tbl")); return result; } @Test public void assertOptimizeWithShorthandItems() { when(shardingTableMetaData.get("tbl")).thenReturn(createTableMetaData()); selectStatement.setSelectItems(createSelectItemsSegment()); selectStatement.getTables().add(new TableSegment(0, 0, "tbl")); SelectItems selectItems = new ShardingSelectOptimizeEngine().optimize(shardingRule, shardingTableMetaData, "", Collections.emptyList(), selectStatement).getSelectItems(); assertThat(selectItems.getColumnLabels().size(), is(2)); assertThat(selectItems.getColumnLabels().get(0), is("id")); assertThat(selectItems.getColumnLabels().get(1), is("user_id")); } private SelectItemsSegment createSelectItemsSegment() { TableSegment owner = mock(TableSegment.class); when(owner.getTableName()).thenReturn("tbl"); ShorthandSelectItemSegment shorthandSelectItemSegment = new ShorthandSelectItemSegment(0, 0, "tbl.*"); shorthandSelectItemSegment.setOwner(owner); SelectItemsSegment result = new SelectItemsSegment(0, 0, false); result.getSelectItems().add(shorthandSelectItemSegment); return result; } private TableMetaData createTableMetaData() { ColumnMetaData idColumnMetaData = new ColumnMetaData("id", "int", true); ColumnMetaData nameColumnMetaData = new ColumnMetaData("user_id", "int", false); return new TableMetaData(Arrays.asList(idColumnMetaData, nameColumnMetaData), Arrays.asList("id", "user_id")); } }
/* * Copyright (c) 2008-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 * * 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.cometd.client; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.cometd.bayeux.Channel; import org.cometd.bayeux.Message; import org.cometd.bayeux.client.ClientSession; import org.cometd.bayeux.client.ClientSessionChannel; import org.cometd.bayeux.server.BayeuxServer; import org.cometd.bayeux.server.ConfigurableServerChannel; import org.cometd.bayeux.server.ServerChannel; import org.cometd.bayeux.server.ServerMessage; import org.cometd.bayeux.server.ServerSession; import org.cometd.client.transport.ClientTransport; import org.cometd.server.DefaultSecurityPolicy; import org.cometd.server.authorizer.GrantAuthorizer; import org.junit.Assert; import org.junit.Test; public class SubscriptionFailureTest extends ClientServerTest { @Test public void testSubscriptionFailedOnClientRemovesListener() throws Exception { startServer(null); long maxNetworkDelay = 2000; final long sleep = maxNetworkDelay + maxNetworkDelay / 2; bayeux.getChannel(Channel.META_SUBSCRIBE).addListener(new ServerChannel.MessageListener() { @Override public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message) { try { Thread.sleep(sleep); } catch (InterruptedException x) { // Ignored } return true; } }); BayeuxClient client = newBayeuxClient(); client.setOption(ClientTransport.MAX_NETWORK_DELAY_OPTION, maxNetworkDelay); client.handshake(); Assert.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED)); final CountDownLatch messageLatch = new CountDownLatch(1); ClientSessionChannel.MessageListener messageCallback = new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { messageLatch.countDown(); } }; final CountDownLatch subscriptionLatch = new CountDownLatch(1); ClientSessionChannel.MessageListener subscriptionCallback = new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { if (!message.isSuccessful()) { subscriptionLatch.countDown(); } } }; String channelName = "/echo"; client.getChannel(channelName).subscribe(messageCallback, subscriptionCallback); Assert.assertTrue(subscriptionLatch.await(5, TimeUnit.SECONDS)); // Wait for subscription to happen on server. Thread.sleep(sleep); // Subscription has failed on client, but not on server. // Publishing a message on server-side must not be notified on the client. bayeux.getChannel(channelName).publish(null, "data"); Assert.assertFalse(messageLatch.await(1, TimeUnit.SECONDS)); disconnectBayeuxClient(client); } @Test public void testSubscriptionFailedOnServerRemovesListener() throws Exception { startServer(null); String channelName = "/echo"; bayeux.createChannelIfAbsent(channelName, new ConfigurableServerChannel.Initializer() { @Override public void configureChannel(ConfigurableServerChannel channel) { channel.addAuthorizer(GrantAuthorizer.GRANT_PUBLISH); } }); BayeuxClient client = newBayeuxClient(); client.handshake(); Assert.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED)); final CountDownLatch messageLatch = new CountDownLatch(1); ClientSessionChannel.MessageListener messageCallback = new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { messageLatch.countDown(); } }; final CountDownLatch subscriptionLatch = new CountDownLatch(1); ClientSessionChannel.MessageListener subscriptionCallback = new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { if (!message.isSuccessful()) { subscriptionLatch.countDown(); } } }; client.getChannel(channelName).subscribe(messageCallback, subscriptionCallback); Assert.assertTrue(subscriptionLatch.await(5, TimeUnit.SECONDS)); // Force subscription on server. bayeux.getChannel(channelName).subscribe(bayeux.getSession(client.getId())); // Subscription has failed on client, but has been forced on server. // Publishing a message on server-side must not be notified on the client. bayeux.getChannel(channelName).publish(null, "data"); Assert.assertFalse(messageLatch.await(1, TimeUnit.SECONDS)); disconnectBayeuxClient(client); } @Test public void testFailedSubscriptionDecrementsSubscriptionCount() throws Exception { startServer(null); final String channelName = "/count"; bayeux.setSecurityPolicy(new DefaultSecurityPolicy() { @Override public boolean canSubscribe(BayeuxServer server, ServerSession session, ServerChannel channel, ServerMessage message) { boolean allowed = super.canSubscribe(server, session, channel, message); Map<String, Object> ext = message.getExt(); return allowed && ext != null && (Boolean)ext.get("token"); } }); BayeuxClient client = newBayeuxClient(); client.handshake(); Assert.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED)); final AtomicBoolean allowed = new AtomicBoolean(); client.addExtension(new ClientSession.Extension.Adapter() { @Override public boolean sendMeta(ClientSession session, Message.Mutable message) { if (Channel.META_SUBSCRIBE.equals(message.getChannel()) && channelName.equals(message.get(Message.SUBSCRIPTION_FIELD))) { message.getExt(true).put("token", allowed.get()); } return true; } }); final CountDownLatch messageLatch = new CountDownLatch(1); ClientSessionChannel.MessageListener messageCallback = new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { messageLatch.countDown(); } }; final CountDownLatch failedSubscription = new CountDownLatch(1); ClientSessionChannel.MessageListener subscriptionCallback = new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { if (!message.isSuccessful()) { failedSubscription.countDown(); } } }; // First subscription fails, the subscription count should be // decremented to zero so that a subsequent subscribe() could succeed. client.getChannel(channelName).subscribe(messageCallback, subscriptionCallback); Assert.assertTrue(failedSubscription.await(5, TimeUnit.SECONDS)); Assert.assertEquals(0, client.getChannel(channelName).getSubscribers().size()); Assert.assertEquals(0, bayeux.getChannel(channelName).getSubscribers().size()); // Now allow the subscription, we should be able to subscribe to the same channel. allowed.set(true); final CountDownLatch succeededSubscription = new CountDownLatch(1); subscriptionCallback = new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { if (message.isSuccessful()) { succeededSubscription.countDown(); } } }; client.getChannel(channelName).subscribe(messageCallback, subscriptionCallback); Assert.assertTrue(succeededSubscription.await(5, TimeUnit.SECONDS)); Assert.assertEquals(1, client.getChannel(channelName).getSubscribers().size()); Assert.assertEquals(1, bayeux.getChannel(channelName).getSubscribers().size()); // Make sure the message can be received. bayeux.getChannel(channelName).publish(null, "data"); Assert.assertTrue(messageLatch.await(5, TimeUnit.SECONDS)); disconnectBayeuxClient(client); } }
/* ### * IP: GHIDRA * * 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 ghidra.framework.store.remote; import java.io.*; import db.buffers.*; import ghidra.framework.client.RepositoryAdapter; import ghidra.framework.remote.RepositoryItem; import ghidra.framework.store.DatabaseItem; import ghidra.framework.store.local.ItemSerializer; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitor; /** * <code>RemoteDatabaseItem</code> provides a FolderItem implementation * for a remote database. This item wraps an underlying versioned database * which corresponds to a repository item. */ public class RemoteDatabaseItem extends RemoteFolderItem implements DatabaseItem { /** * Construct a FolderItem for an existing repository database item. * @param repository repository which contains item * @param item repository item */ RemoteDatabaseItem(RepositoryAdapter repository, RepositoryItem item) { super(repository, item); } @Override public long length() throws IOException { return repository.getLength(parentPath, itemName); } @Override int getItemType() { return RepositoryItem.DATABASE; } @Override public boolean canRecover() { return false; } @Override public ManagedBufferFileAdapter open(int version, int minChangeDataVer) throws IOException { return repository.openDatabase(parentPath, itemName, version, minChangeDataVer); } @Override public ManagedBufferFileAdapter open(int version) throws IOException { return repository.openDatabase(parentPath, itemName, version, -1); } @Override public ManagedBufferFileAdapter open() throws IOException { return repository.openDatabase(parentPath, itemName, LATEST_VERSION, -1); } @Override public ManagedBufferFileAdapter openForUpdate(long checkoutId) throws IOException { return repository.openDatabase(parentPath, itemName, checkoutId); } @Override public void updateCheckoutVersion(long checkoutId, int checkoutVersion, String user) throws IOException { repository.updateCheckoutVersion(parentPath, itemName, checkoutId, checkoutVersion); } /* * @see ghidra.framework.store.FolderItem#hasCheckouts() */ @Override public boolean hasCheckouts() throws IOException { return repository.hasCheckouts(parentPath, itemName); } @Override public boolean isCheckinActive() throws IOException { return repository.isCheckinActive(parentPath, itemName); } @Override public void output(File outputFile, int version, TaskMonitor monitor) throws IOException, CancelledException { BufferFile bf = repository.openDatabase(parentPath, itemName, version, -1); try { File tmpFile = File.createTempFile("ghidra", LocalBufferFile.TEMP_FILE_EXT); tmpFile.delete(); BufferFile tmpBf = new LocalBufferFile(tmpFile, bf.getBufferSize()); try { LocalBufferFile.copyFile(bf, tmpBf, null, monitor); tmpBf.close(); InputStream itemIn = new FileInputStream(tmpFile); try { ItemSerializer.outputItem(getName(), getContentType(), DATABASE_FILE_TYPE, tmpFile.length(), itemIn, outputFile, monitor); } finally { try { itemIn.close(); } catch (IOException e) { } } } finally { tmpBf.close(); tmpFile.delete(); } } finally { bf.close(); } } }
//snippet-sourcedescription:[MonitorInstance.java demonstrates how to toggle detailed monitoring for an EC2 instance.] //snippet-keyword:[Java] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon EC2] //snippet-service:[ec2] //snippet-sourcetype:[full-example] //snippet-sourcedate:[] //snippet-sourceauthor:[AWS] /* * Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package aws.example.ec2; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.MonitorInstancesRequest; import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest; import com.amazonaws.services.ec2.model.DryRunResult; import com.amazonaws.services.ec2.model.DryRunSupportedRequest; /** * Toggles detailed monitoring for an EC2 instance */ public class MonitorInstance { public static void monitorInstance(String instance_id) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DryRunSupportedRequest<MonitorInstancesRequest> dry_request = () -> { MonitorInstancesRequest request = new MonitorInstancesRequest() .withInstanceIds(instance_id); return request.getDryRunRequest(); }; DryRunResult dry_response = ec2.dryRun(dry_request); if (!dry_response.isSuccessful()) { System.out.printf( "Failed dry run to enable monitoring on instance %s", instance_id); throw dry_response.getDryRunResponse(); } MonitorInstancesRequest request = new MonitorInstancesRequest() .withInstanceIds(instance_id); ec2.monitorInstances(request); System.out.printf( "Successfully enabled monitoring for instance %s", instance_id); } public static void unmonitorInstance(String instance_id) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DryRunSupportedRequest<UnmonitorInstancesRequest> dry_request = () -> { UnmonitorInstancesRequest request = new UnmonitorInstancesRequest() .withInstanceIds(instance_id); return request.getDryRunRequest(); }; DryRunResult dry_response = ec2.dryRun(dry_request); if (!dry_response.isSuccessful()) { System.out.printf( "Failed dry run to disable monitoring on instance %s", instance_id); throw dry_response.getDryRunResponse(); } UnmonitorInstancesRequest request = new UnmonitorInstancesRequest() .withInstanceIds(instance_id); ec2.unmonitorInstances(request); System.out.printf( "Successfully disabled monitoring for instance %s", instance_id); } public static void main(String[] args) { final String USAGE = "To run this example, supply an instance id and a monitoring " + "status\n" + "Ex: MonitorInstance <instance-id> <true|false>\n"; if (args.length != 2) { System.out.println(USAGE); System.exit(1); } String instance_id = args[0]; boolean monitor = Boolean.valueOf(args[1]); if (monitor) { monitorInstance(instance_id); } else { unmonitorInstance(instance_id); } } }
/* * Licensed to ObjectStyle LLC under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ObjectStyle LLC licenses * this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.bootique.test.junit; import io.bootique.BQCoreModule; import io.bootique.BQModuleOverrideBuilder; import io.bootique.BQModuleProvider; import io.bootique.Bootique; import io.bootique.di.BQModule; import io.bootique.log.BootLogger; import java.util.Collection; import java.util.HashMap; import java.util.Map; // parameterization is needed to enable covariant return types in subclasses public abstract class BQTestRuntimeBuilder<T extends BQTestRuntimeBuilder<T>> { protected Bootique bootique; protected Map<String, String> properties; /** * Properties are used to make test stack independent from a shell environment. * It allows us be sure that all the vars are controlled within the test and there are no outside influences. * <p> * The properties take part on {@link io.bootique.env.Environment} provision in {@link BQCoreModule}. */ private static final String EXCLUDE_SYSTEM_VARIABLES = "bq.core.excludeSystemVariables"; private static final String EXCLUDE_SYSTEM_PROPERTIES = "bq.core.excludeSystemProperties"; protected BQTestRuntimeBuilder(String[] args) { //exclude system variables and properties by setting the properties final HashMap<String, String> properties = new HashMap<>(); properties.put(EXCLUDE_SYSTEM_PROPERTIES, "true"); properties.put(EXCLUDE_SYSTEM_VARIABLES, "true"); this.properties = properties; this.bootique = Bootique.app(args).moduleProvider(createPropertiesProvider()); } protected BQModuleProvider createPropertiesProvider() { return new BQModuleProvider() { @Override public BQModule module() { return binder -> BQCoreModule.extend(binder).setProperties(properties); } @Override public String name() { return "BQTestRuntimeBuilder:properties"; } }; } /** * Appends extra values to the test CLI arguments. * * @param args extra args to pass to Bootique. * @return this instance of test runtime builder. */ public T args(String... args) { bootique.args(args); return (T) this; } /** * Appends extra values to the test CLI arguments. * * @param args extra args to pass to Bootique. * @return this instance of test runtime builder. */ public T args(Collection<String> args) { bootique.args(args); return (T) this; } /** * Instructs Bootique to load any modules available on classpath that expose {@link io.bootique.BQModuleProvider} * provider. Auto-loaded modules will be used in default configuration. Factories within modules will of course be * configured dynamically from YAML. * * @return this instance of test runtime builder. */ public T autoLoadModules() { bootique.autoLoadModules(); return (T) this; } /** * @param bootLogger custom BootLogger to use for a given runtime. * @return this instance of test runtime builder. */ public T bootLogger(BootLogger bootLogger) { bootique.bootLogger(bootLogger); return (T) this; } /** * @param moduleType custom Module class to add to Bootique DI runtime. * @return this instance of test runtime builder. * @see #autoLoadModules() */ public T module(Class<? extends BQModule> moduleType) { bootique.module(moduleType); return (T) this; } /** * Adds an array of Module types to the Bootique DI runtime. Each type will * be instantiated by Bootique and added to the DI container. * * @param moduleTypes custom Module classes to add to Bootique DI runtime. * @return this instance of test runtime builder. * @see #autoLoadModules() */ @SafeVarargs public final T modules(Class<? extends BQModule>... moduleTypes) { bootique.modules(moduleTypes); return (T) this; } /** * @param m a module to add to the test runtime. * @return this instance of test runtime builder. */ public T module(BQModule m) { bootique.module(m); return (T) this; } /** * Adds an array of Modules to the Bootique DI runtime. * * @param modules an array of modules to add to Bootiqie DI runtime. * @return this instance of test runtime builder. */ public T modules(BQModule... modules) { bootique.modules(modules); return (T) this; } /** * Adds a Module generated by the provider. Provider may optionally specify * that the Module overrides services in some other Module. * * @param moduleProvider a provider of Module and override spec. * @return this instance of test runtime builder. * @since 2.0 */ public T moduleProvider(BQModuleProvider moduleProvider) { bootique.moduleProvider(moduleProvider); return (T) this; } /** * Starts an API call chain to override an array of Modules. * * @param overriddenTypes an array of modules whose bindings should be overridden. * @return {@link BQModuleOverrideBuilder} object to specify a Module * overriding other modules. */ public BQModuleOverrideBuilder<T> override(Class<? extends BQModule>... overriddenTypes) { BQModuleOverrideBuilder<Bootique> subBuilder = bootique.override(overriddenTypes); return new BQModuleOverrideBuilder<T>() { @Override public T with(Class<? extends BQModule> moduleType) { subBuilder.with(moduleType); return (T) BQTestRuntimeBuilder.this; } @Override public T with(BQModule module) { subBuilder.with(module); return (T) BQTestRuntimeBuilder.this; } }; } public T property(String key, String value) { properties.put(key, value); return (T) this; } }
// // Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802 // Consulte <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem. // Gerado em: 2017.03.09 às 01:53:29 PM BRT // package br.gov.esocial.schema.evt.evttabrubrica.v02_02_00; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * Identificação de evento de cadastro/tabelas * * <p>Classe Java de TIdeCadastro complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="TIdeCadastro"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="tpAmb"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}byte"> * &lt;pattern value="\d"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="procEmi"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}byte"> * &lt;pattern value="\d"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="verProc"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="1"/> * &lt;maxLength value="20"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TIdeCadastro", propOrder = { "tpAmb", "procEmi", "verProc" }) public class TIdeCadastro { protected byte tpAmb; protected byte procEmi; @XmlElement(required = true) protected String verProc; /** * Obtém o valor da propriedade tpAmb. * */ public byte getTpAmb() { return tpAmb; } /** * Define o valor da propriedade tpAmb. * */ public void setTpAmb(byte value) { this.tpAmb = value; } /** * Obtém o valor da propriedade procEmi. * */ public byte getProcEmi() { return procEmi; } /** * Define o valor da propriedade procEmi. * */ public void setProcEmi(byte value) { this.procEmi = value; } /** * Obtém o valor da propriedade verProc. * * @return * possible object is * {@link String } * */ public String getVerProc() { return verProc; } /** * Define o valor da propriedade verProc. * * @param value * allowed object is * {@link String } * */ public void setVerProc(String value) { this.verProc = value; } }