text
stringlengths
7
1.01M
/* * Copyright (c) 2015-2018 Rocket Partners, LLC * https://github.com/inversion-api * * 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.inversion.rql; import java.util.ArrayList; import java.util.List; public class Group<T extends Group, P extends Query> extends Builder<T, P> { public Group(P query) { super(query); withFunctions("group"); } public List<String> getGroupBy() { List<String> groups = new ArrayList<>(); for (Term group : findAll("group")) { for (Term term : group.getTerms()) { if (term.isLeaf()) groups.add(term.getToken()); } } return groups; } public T withGroupBy(String... properties) { Term group = find("group"); if (group != null) { for (String property : properties) { group.withTerm(Term.term(group, property)); } } else { withTerm("group", (Object[]) properties); } return r(); } }
package faisal.com.reptophonebook; public class Item { private int id; private String name; private String number; public Item() { } public Item(int id, String name, String number) { this.id = id; this.name = name; this.number = number; } public Item(String name, String number) { this.name = name; this.number = number; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } @Override public String toString() { return "Item{" + "id=" + id + ", name='" + name + '\'' + ", number='" + number + '\'' + '}'; } }
package com.github.dolphinai.cqrsframework.common.event.impl; import org.springframework.context.ApplicationContext; import org.springframework.context.event.ApplicationContextEvent; /** */ public final class WrappedEvent extends ApplicationContextEvent { private final Object event; public WrappedEvent(final ApplicationContext source, final Object eventObject) { super(source); this.event = eventObject; } public Object getEvent() { return event; } }
// // Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.8-b130911.1802 // Vedere <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine. // Generato il: 2015.12.01 alle 07:40:41 AM CET // package it.cnr.icar.biograph.models.uniprot; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java per anonymous complex type. * * <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://uniprot.org/uniprot}entry" maxOccurs="unbounded"/> * &lt;element ref="{http://uniprot.org/uniprot}copyright" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "entry", "copyright" }) @XmlRootElement(name = "uniprot") public class Uniprot { @XmlElement(required = true) protected List<Entry> entry; protected String copyright; /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Entry } * * */ public List<Entry> getEntry() { if (entry == null) { entry = new ArrayList<Entry>(); } return this.entry; } /** * Recupera il valore della proprietà copyright. * * @return * possible object is * {@link String } * */ public String getCopyright() { return copyright; } /** * Imposta il valore della proprietà copyright. * * @param value * allowed object is * {@link String } * */ public void setCopyright(String value) { this.copyright = value; } }
package ru.betterend.blocks; import java.util.Random; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.block.BlockState; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.minecraft.world.BlockView; import net.minecraft.world.World; import ru.betterend.blocks.basis.BlockDoublePlant; import ru.betterend.blocks.basis.BlockPlant; import ru.betterend.registry.EndBlocks; import ru.betterend.util.BlocksHelper; public class BlockUmbrellaMoss extends BlockPlant { public BlockUmbrellaMoss() { super(11); } @Override protected boolean isTerrain(BlockState state) { return state.getBlock() == EndBlocks.END_MOSS || state.getBlock() == EndBlocks.END_MYCELIUM; } @Environment(EnvType.CLIENT) public boolean hasEmissiveLighting(BlockView world, BlockPos pos) { return true; } @Environment(EnvType.CLIENT) public float getAmbientOcclusionLightLevel(BlockView world, BlockPos pos) { return 1F; } @Override public boolean canGrow(World world, Random random, BlockPos pos, BlockState state) { return world.isAir(pos.up()); } @Override public void grow(ServerWorld world, Random random, BlockPos pos, BlockState state) { int rot = world.random.nextInt(4); BlockState bs = EndBlocks.UMBRELLA_MOSS_TALL.getDefaultState().with(BlockDoublePlant.ROTATION, rot); BlocksHelper.setWithoutUpdate(world, pos, bs); BlocksHelper.setWithoutUpdate(world, pos.up(), bs.with(BlockDoublePlant.TOP, true)); } }
// Template Source: BaseEntityRequestBuilder.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.AndroidWorkProfileNineWorkEasConfiguration; import java.util.Arrays; import java.util.EnumSet; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Android Work Profile Nine Work Eas Configuration Request Builder. */ public class AndroidWorkProfileNineWorkEasConfigurationRequestBuilder extends BaseRequestBuilder implements IAndroidWorkProfileNineWorkEasConfigurationRequestBuilder { /** * The request builder for the AndroidWorkProfileNineWorkEasConfiguration * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public AndroidWorkProfileNineWorkEasConfigurationRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the IAndroidWorkProfileNineWorkEasConfigurationRequest instance */ public IAndroidWorkProfileNineWorkEasConfigurationRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for this request * @return the IAndroidWorkProfileNineWorkEasConfigurationRequest instance */ public IAndroidWorkProfileNineWorkEasConfigurationRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new com.microsoft.graph.requests.extensions.AndroidWorkProfileNineWorkEasConfigurationRequest(getRequestUrl(), getClient(), requestOptions); } public IDeviceConfigurationAssignmentCollectionRequestBuilder assignments() { return new DeviceConfigurationAssignmentCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("assignments"), getClient(), null); } public IDeviceConfigurationAssignmentRequestBuilder assignments(final String id) { return new DeviceConfigurationAssignmentRequestBuilder(getRequestUrlWithAdditionalSegment("assignments") + "/" + id, getClient(), null); } public ISettingStateDeviceSummaryCollectionRequestBuilder deviceSettingStateSummaries() { return new SettingStateDeviceSummaryCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("deviceSettingStateSummaries"), getClient(), null); } public ISettingStateDeviceSummaryRequestBuilder deviceSettingStateSummaries(final String id) { return new SettingStateDeviceSummaryRequestBuilder(getRequestUrlWithAdditionalSegment("deviceSettingStateSummaries") + "/" + id, getClient(), null); } public IDeviceConfigurationDeviceStatusCollectionRequestBuilder deviceStatuses() { return new DeviceConfigurationDeviceStatusCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("deviceStatuses"), getClient(), null); } public IDeviceConfigurationDeviceStatusRequestBuilder deviceStatuses(final String id) { return new DeviceConfigurationDeviceStatusRequestBuilder(getRequestUrlWithAdditionalSegment("deviceStatuses") + "/" + id, getClient(), null); } /** * Gets the request builder for DeviceConfigurationDeviceOverview * * @return the IDeviceConfigurationDeviceOverviewRequestBuilder instance */ public IDeviceConfigurationDeviceOverviewRequestBuilder deviceStatusOverview() { return new DeviceConfigurationDeviceOverviewRequestBuilder(getRequestUrlWithAdditionalSegment("deviceStatusOverview"), getClient(), null); } public IDeviceConfigurationGroupAssignmentCollectionRequestBuilder groupAssignments() { return new DeviceConfigurationGroupAssignmentCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("groupAssignments"), getClient(), null); } public IDeviceConfigurationGroupAssignmentRequestBuilder groupAssignments(final String id) { return new DeviceConfigurationGroupAssignmentRequestBuilder(getRequestUrlWithAdditionalSegment("groupAssignments") + "/" + id, getClient(), null); } public IDeviceConfigurationUserStatusCollectionRequestBuilder userStatuses() { return new DeviceConfigurationUserStatusCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("userStatuses"), getClient(), null); } public IDeviceConfigurationUserStatusRequestBuilder userStatuses(final String id) { return new DeviceConfigurationUserStatusRequestBuilder(getRequestUrlWithAdditionalSegment("userStatuses") + "/" + id, getClient(), null); } /** * Gets the request builder for DeviceConfigurationUserOverview * * @return the IDeviceConfigurationUserOverviewRequestBuilder instance */ public IDeviceConfigurationUserOverviewRequestBuilder userStatusOverview() { return new DeviceConfigurationUserOverviewRequestBuilder(getRequestUrlWithAdditionalSegment("userStatusOverview"), getClient(), null); } /** * Gets the request builder for AndroidWorkProfileCertificateProfileBase * * @return the IAndroidWorkProfileCertificateProfileBaseWithReferenceRequestBuilder instance */ public IAndroidWorkProfileCertificateProfileBaseWithReferenceRequestBuilder identityCertificate() { return new AndroidWorkProfileCertificateProfileBaseWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("identityCertificate"), getClient(), null); } }
/** * 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.impl; import static io.gravitee.repository.management.model.Audit.AuditProperties.USER; import static io.gravitee.rest.api.model.permissions.RolePermissionAction.UPDATE; import static io.gravitee.rest.api.service.common.JWTHelper.ACTION.*; import static io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER; import static io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER; import static io.gravitee.rest.api.service.notification.NotificationParamsBuilder.*; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.apache.commons.lang3.StringUtils.isBlank; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.ReadContext; import io.gravitee.common.data.domain.MetadataPage; import io.gravitee.common.data.domain.Page; import io.gravitee.common.util.Maps; import io.gravitee.el.TemplateEngine; import io.gravitee.el.spel.function.json.JsonPathFunction; import io.gravitee.repository.exceptions.TechnicalException; import io.gravitee.repository.management.api.MembershipRepository; import io.gravitee.repository.management.api.UserRepository; import io.gravitee.repository.management.api.search.UserCriteria; import io.gravitee.repository.management.api.search.builder.PageableBuilder; import io.gravitee.repository.management.model.Membership; import io.gravitee.repository.management.model.User; import io.gravitee.repository.management.model.UserStatus; import io.gravitee.rest.api.model.*; import io.gravitee.rest.api.model.application.ApplicationSettings; import io.gravitee.rest.api.model.application.SimpleApplicationSettings; import io.gravitee.rest.api.model.audit.AuditEntity; import io.gravitee.rest.api.model.audit.AuditQuery; import io.gravitee.rest.api.model.common.Pageable; import io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity; import io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity; import io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity; import io.gravitee.rest.api.model.parameters.Key; import io.gravitee.rest.api.model.parameters.ParameterReferenceType; import io.gravitee.rest.api.model.permissions.RolePermission; import io.gravitee.rest.api.model.permissions.RolePermissionAction; import io.gravitee.rest.api.model.permissions.RoleScope; import io.gravitee.rest.api.service.*; import io.gravitee.rest.api.service.builder.EmailNotificationBuilder; import io.gravitee.rest.api.service.common.GraviteeContext; import io.gravitee.rest.api.service.common.JWTHelper.ACTION; import io.gravitee.rest.api.service.common.JWTHelper.Claims; import io.gravitee.rest.api.service.common.UuidString; import io.gravitee.rest.api.service.configuration.identity.IdentityProviderService; import io.gravitee.rest.api.service.exceptions.*; import io.gravitee.rest.api.service.impl.search.SearchResult; import io.gravitee.rest.api.service.notification.NotificationParamsBuilder; import io.gravitee.rest.api.service.notification.PortalHook; import io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils; import io.gravitee.rest.api.service.search.SearchEngineService; import io.gravitee.rest.api.service.search.query.Query; import io.gravitee.rest.api.service.search.query.QueryBuilder; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.stream.Collectors; import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author Nicolas GERAUD (nicolas.geraud at graviteesource.com) * @author Azize Elamrani (azize.elamrani at graviteesource.com) * @author GraviteeSource Team */ @Component public class UserServiceImpl extends AbstractService implements UserService, InitializingBean { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); /** A default source used for user registration.*/ private static final String IDP_SOURCE_GRAVITEE = "gravitee"; private static final String TEMPLATE_ENGINE_PROFILE_ATTRIBUTE = "profile"; // Dirty hack: only used to force class loading static { try { LOGGER.trace( "Loading class to initialize properly JsonPath Cache provider: {}", Class.forName(JsonPathFunction.class.getName()) ); } catch (ClassNotFoundException ignored) { LOGGER.trace("Loading class to initialize properly JsonPath Cache provider : fail"); } } @Autowired private UserRepository userRepository; @Autowired private ConfigurableEnvironment environment; @Autowired private EmailService emailService; @Autowired private ApplicationService applicationService; @Autowired private RoleService roleService; @Autowired private MembershipService membershipService; @Autowired private MembershipRepository membershipRepository; @Autowired private PermissionService permissionService; @Autowired private AuditService auditService; @Autowired private NotifierService notifierService; @Autowired private ApiService apiService; @Autowired private ParameterService parameterService; @Autowired private SearchEngineService searchEngineService; @Autowired private InvitationService invitationService; @Autowired private PortalNotificationService portalNotificationService; @Autowired private PortalNotificationConfigService portalNotificationConfigService; @Autowired private GenericNotificationConfigService genericNotificationConfigService; @Autowired private GroupService groupService; @Autowired private OrganizationService organizationService; @Autowired private NewsletterService newsletterService; @Autowired private PasswordValidator passwordValidator; @Autowired private TokenService tokenService; @Autowired private EnvironmentService environmentService; @Autowired private IdentityProviderService identityProviderService; @Autowired private UserMetadataService userMetadataService; @Value("${user.login.defaultApplication:true}") private boolean defaultApplicationForFirstConnection; @Value("${user.anonymize-on-delete.enabled:false}") private boolean anonymizeOnDelete; private List<String> portalWhitelist; private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); @Override public void afterPropertiesSet() { int i = 0; portalWhitelist = new ArrayList<>(); String whitelistUrl; while ((whitelistUrl = environment.getProperty("portal.whitelist[" + i + "]")) != null) { portalWhitelist.add(whitelistUrl); i++; } } @Override public UserEntity connect(String userId) { try { LOGGER.debug("Connection of {}", userId); Optional<User> checkUser = userRepository.findById(userId); if (!checkUser.isPresent()) { throw new UserNotFoundException(userId); } User user = checkUser.get(); User previousUser = new User(user); // First connection: create default application for user & notify if (user.getLastConnectionAt() == null && user.getFirstConnectionAt() == null) { notifierService.trigger(PortalHook.USER_FIRST_LOGIN, new NotificationParamsBuilder().user(convert(user, false)).build()); user.setFirstConnectionAt(new Date()); if (defaultApplicationForFirstConnection) { LOGGER.debug("Create a default application for {}", userId); NewApplicationEntity defaultApp = new NewApplicationEntity(); defaultApp.setName("Default application"); defaultApp.setDescription("My default application"); // To preserve backward compatibility, ensure that we have at least default settings for simple application type ApplicationSettings settings = new ApplicationSettings(); SimpleApplicationSettings simpleAppSettings = new SimpleApplicationSettings(); settings.setApp(simpleAppSettings); defaultApp.setSettings(settings); try { environmentService .findByUser(GraviteeContext.getCurrentOrganization(), userId) .forEach(env -> applicationService.create(env.getId(), defaultApp, userId)); } catch (IllegalStateException ex) { //do not fail to create a user even if we are not able to create its default app LOGGER.warn("Not able to create default app for user {}", userId); } } } // Set date fields user.setLastConnectionAt(new Date()); if (user.getFirstConnectionAt() == null) { user.setFirstConnectionAt(user.getLastConnectionAt()); } user.setUpdatedAt(user.getLastConnectionAt()); user.setLoginCount(user.getLoginCount() + 1); User updatedUser = userRepository.update(user); auditService.createOrganizationAuditLog( GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, userId), User.AuditEvent.USER_CONNECTED, user.getUpdatedAt(), previousUser, user ); final UserEntity userEntity = convert(updatedUser, true); searchEngineService.index(userEntity, false); return userEntity; } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to connect {}", userId, ex); throw new TechnicalManagementException("An error occurs while trying to connect " + userId, ex); } } @Override public UserEntity findById(String id, boolean defaultValue) { return GraviteeContext .getCurrentUsers() .computeIfAbsent( id, k -> { try { LOGGER.debug("Find user by ID: {}", k); Optional<User> optionalUser = userRepository.findById(k); if (optionalUser.isPresent()) { return convert(optionalUser.get(), false, userMetadataService.findAllByUserId(k)); } if (defaultValue) { UserEntity unknownUser = new UserEntity(); unknownUser.setId(k); unknownUser.setFirstname("Unknown user"); return unknownUser; } //should never happen throw new UserNotFoundException(k); } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to find user using its ID {}", k, ex); throw new TechnicalManagementException("An error occurs while trying to find user using its ID " + k, ex); } } ); } @Override public Optional<UserEntity> findByEmail(String email) { try { LOGGER.debug("Find user by Email: {}", email); Optional<User> optionalUser = userRepository.findByEmail(email, GraviteeContext.getCurrentOrganization()); return optionalUser.map(user -> convert(optionalUser.get(), false)); } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to find user using its email", ex); throw new TechnicalManagementException("An error occurs while trying to find user using its email", ex); } } @Override public UserEntity findByIdWithRoles(String id) { try { LOGGER.debug("Find user by ID: {}", id); Optional<User> optionalUser = userRepository.findById(id); if (optionalUser.isPresent()) { UserEntity userEntity = convert(optionalUser.get(), true, userMetadataService.findAllByUserId(id)); populateUserFlags(Collections.singletonList(userEntity)); return userEntity; } //should never happen throw new UserNotFoundException(id); } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to find user using its ID {}", id, ex); throw new TechnicalManagementException("An error occurs while trying to find user using its ID " + id, ex); } } @Override public UserEntity findBySource(String source, String sourceId, boolean loadRoles) { try { LOGGER.debug("Find user by source[{}] user[{}]", source, sourceId); Optional<User> optionalUser = userRepository.findBySource(source, sourceId, GraviteeContext.getCurrentOrganization()); if (optionalUser.isPresent()) { return convert(optionalUser.get(), loadRoles); } throw new UserNotFoundException(sourceId); } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to find user using source[{}], user[{}]", source, sourceId, ex); throw new TechnicalManagementException("An error occurs while trying to find user using source " + source + ':' + sourceId, ex); } } @Override public Set<UserEntity> findByIds(Collection<String> ids) { return this.findByIds(ids, true); } @Override public Set<UserEntity> findByIds(Collection<String> ids, boolean withUserMetadata) { try { LOGGER.debug("Find users by ID: {}", ids); Set<User> users = userRepository.findByIds(ids); if (!users.isEmpty()) { return users .stream() .map( u -> this.convert( u, false, withUserMetadata ? userMetadataService.findAllByUserId(u.getId()) : Collections.emptyList() ) ) .collect(toSet()); } Optional<String> idsAsString = ids.stream().reduce((a, b) -> a + '/' + b); if (idsAsString.isPresent()) { throw new UserNotFoundException(idsAsString.get()); } else { throw new UserNotFoundException("?"); } } catch (TechnicalException ex) { Optional<String> idsAsString = ids.stream().reduce((a, b) -> a + '/' + b); LOGGER.error("An error occurs while trying to find users using their ID {}", idsAsString, ex); throw new TechnicalManagementException("An error occurs while trying to find users using their ID " + idsAsString, ex); } } private void checkUserRegistrationEnabled(GraviteeContext.ReferenceContext currentContext) { boolean userCreationEnabled; if (currentContext.getReferenceType().equals(GraviteeContext.ReferenceContextType.ORGANIZATION)) { userCreationEnabled = parameterService.findAsBoolean( Key.CONSOLE_USERCREATION_ENABLED, currentContext.getReferenceId(), ParameterReferenceType.ORGANIZATION ); } else { userCreationEnabled = parameterService.findAsBoolean( Key.PORTAL_USERCREATION_ENABLED, currentContext.getReferenceId(), ParameterReferenceType.ENVIRONMENT ); } if (!userCreationEnabled) { throw new UserRegistrationUnavailableException(); } } /** * Allows to complete the creation of a user which is pre-created. * @param registerUserEntity a valid token and a password * @return the user */ @Override public UserEntity finalizeRegistration(final RegisterUserEntity registerUserEntity) { try { DecodedJWT jwt = getDecodedJWT(registerUserEntity.getToken()); final String action = jwt.getClaim(Claims.ACTION).asString(); if (RESET_PASSWORD.name().equals(action)) { throw new UserStateConflictException("Reset password forbidden on this resource"); } if (USER_REGISTRATION.name().equals(action)) { checkUserRegistrationEnabled(GraviteeContext.getCurrentContext()); } else if (GROUP_INVITATION.name().equals(action)) { // check invitations final String email = jwt.getClaim(Claims.EMAIL).asString(); final List<InvitationEntity> invitations = invitationService.findAll(); final List<InvitationEntity> userInvitations = invitations .stream() .filter(invitation -> invitation.getEmail().equals(email)) .collect(toList()); if (userInvitations.isEmpty()) { throw new IllegalStateException("Invitation has been canceled"); } } // check password here to avoid user creation if password is invalid if (registerUserEntity.getPassword() != null) { if (!passwordValidator.validate(registerUserEntity.getPassword())) { throw new PasswordFormatInvalidException(); } } final Object subject = jwt.getSubject(); User user; if (subject == null) { final NewExternalUserEntity externalUser = new NewExternalUserEntity(); final String email = jwt.getClaim(Claims.EMAIL).asString(); externalUser.setSource(IDP_SOURCE_GRAVITEE); externalUser.setSourceId(email); externalUser.setFirstname(registerUserEntity.getFirstname()); externalUser.setLastname(registerUserEntity.getLastname()); externalUser.setEmail(email); user = convert(create(externalUser, true)); user.setOrganizationId(GraviteeContext.getCurrentOrganization()); } else { final String username = subject.toString(); LOGGER.debug("Create an internal user {}", username); Optional<User> checkUser = userRepository.findById(username); user = checkUser.orElseThrow(() -> new UserNotFoundException(username)); if (StringUtils.isNotBlank(user.getPassword())) { throw new UserAlreadyFinalizedException(GraviteeContext.getCurrentOrganization()); } } if (GROUP_INVITATION.name().equals(action)) { // check invitations final String email = user.getEmail(); final String userId = user.getId(); final List<InvitationEntity> invitations = invitationService.findAll(); invitations .stream() .filter(invitation -> invitation.getEmail().equals(email)) .forEach( invitation -> { invitationService.addMember( invitation.getReferenceType().name(), invitation.getReferenceId(), userId, invitation.getApiRole(), invitation.getApplicationRole() ); invitationService.delete(invitation.getId(), invitation.getReferenceId()); } ); } // Set date fields user.setUpdatedAt(new Date()); // Encrypt password if internal user encryptPassword(user, registerUserEntity.getPassword()); user = userRepository.update(user); auditService.createOrganizationAuditLog( GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, user.getId()), User.AuditEvent.USER_CREATED, user.getUpdatedAt(), null, user ); // Do not send back the password user.setPassword(null); final UserEntity userEntity = convert(user, true); searchEngineService.index(userEntity, false); return userEntity; } catch (AbstractManagementException ex) { throw ex; } catch (Exception ex) { LOGGER.error("An error occurs while trying to create an internal user with the token {}", registerUserEntity.getToken(), ex); throw new TechnicalManagementException(ex.getMessage(), ex); } } @Override public UserEntity finalizeResetPassword(ResetPasswordUserEntity registerUserEntity) { try { DecodedJWT jwt = getDecodedJWT(registerUserEntity.getToken()); final String action = jwt.getClaim(Claims.ACTION).asString(); if (!RESET_PASSWORD.name().equals(action)) { throw new UserStateConflictException("Invalid action on reset password resource"); } final Object subject = jwt.getSubject(); User user; if (subject == null) { throw new UserNotFoundException("Subject missing from JWT token"); } else { final String username = subject.toString(); LOGGER.debug("Find user {} to update password", username); Optional<User> checkUser = userRepository.findById(username); user = checkUser.orElseThrow(() -> new UserNotFoundException(username)); } // Set date fields user.setUpdatedAt(new Date()); // Encrypt password if internal user encryptPassword(user, registerUserEntity.getPassword()); user = userRepository.update(user); auditService.createOrganizationAuditLog( GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, user.getId()), User.AuditEvent.PASSWORD_CHANGED, user.getUpdatedAt(), null, null ); // Do not send back the password user.setPassword(null); return convert(user, true); } catch (AbstractManagementException ex) { throw ex; } catch (Exception ex) { LOGGER.error( "An error occurs while trying to change password of an internal user with the token {}", registerUserEntity.getToken(), ex ); throw new TechnicalManagementException(ex.getMessage(), ex); } } private void encryptPassword(User user, String password) { if (password != null) { if (passwordValidator.validate(password)) { user.setPassword(passwordEncoder.encode(password)); } else { throw new PasswordFormatInvalidException(); } } } private DecodedJWT getDecodedJWT(String token) { final String jwtSecret = environment.getProperty("jwt.secret"); if (jwtSecret == null || jwtSecret.isEmpty()) { throw new IllegalStateException("JWT secret is mandatory"); } Algorithm algorithm = Algorithm.HMAC256(jwtSecret); JWTVerifier verifier = JWT.require(algorithm).withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).build(); return verifier.verify(token); } @Override public PictureEntity getPicture(String id) { UserEntity user = findById(id); if (user.getPicture() != null) { String picture = user.getPicture(); if (picture.matches("^(http|https)://.*$")) { return new UrlPictureEntity(picture); } else { try { InlinePictureEntity imageEntity = new InlinePictureEntity(); String[] parts = picture.split(";", 2); imageEntity.setType(parts[0].split(":")[1]); String base64Content = picture.split(",", 2)[1]; imageEntity.setContent(DatatypeConverter.parseBase64Binary(base64Content)); return imageEntity; } catch (Exception ex) { LOGGER.warn("Unable to get user picture for id[{}]", id); } } } // Return empty image InlinePictureEntity imageEntity = new InlinePictureEntity(); imageEntity.setType("image/png"); return imageEntity; } /** * Allows to create a user. * @param newExternalUserEntity * @return */ @Override public UserEntity create(NewExternalUserEntity newExternalUserEntity, boolean addDefaultRole) { return create(newExternalUserEntity, addDefaultRole, true); } private UserEntity create(NewExternalUserEntity newExternalUserEntity, boolean addDefaultRole, boolean autoRegistrationEnabled) { try { /* TODO: getCurrentEnvironnemenet and call database to fetch the corresponding organization OR add parameters in methods Because, this method is called by portal and console. And in portal, we don't have a "current organization" in path. */ String organizationId = GraviteeContext.getCurrentOrganization(); // First we check that organization exist this.organizationService.findById(organizationId); LOGGER.debug("Create an external user {}", newExternalUserEntity); Optional<User> checkUser = userRepository.findBySource( newExternalUserEntity.getSource(), newExternalUserEntity.getSourceId(), organizationId ); if (checkUser.isPresent()) { throw new UserAlreadyExistsException( newExternalUserEntity.getSource(), newExternalUserEntity.getSourceId(), organizationId ); } User user = convert(newExternalUserEntity); user.setId(UuidString.generateRandom()); user.setOrganizationId(organizationId); user.setStatus(autoRegistrationEnabled ? UserStatus.ACTIVE : UserStatus.PENDING); // Set date fields user.setCreatedAt(new Date()); user.setUpdatedAt(user.getCreatedAt()); User createdUser = userRepository.create(user); auditService.createOrganizationAuditLog( GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, user.getId()), User.AuditEvent.USER_CREATED, user.getCreatedAt(), null, user ); List<UserMetadataEntity> metadata = new ArrayList<>(); if (newExternalUserEntity.getCustomFields() != null) { for (Map.Entry<String, Object> entry : newExternalUserEntity.getCustomFields().entrySet()) { NewUserMetadataEntity metadataEntity = new NewUserMetadataEntity(); metadataEntity.setName(entry.getKey()); metadataEntity.setUserId(createdUser.getId()); metadataEntity.setFormat(MetadataFormat.STRING); metadataEntity.setValue(String.valueOf(entry.getValue())); metadata.add(userMetadataService.create(metadataEntity)); } } if (addDefaultRole) { addDefaultMembership(createdUser); } final UserEntity userEntity = convert(createdUser, true, metadata); searchEngineService.index(userEntity, false); return userEntity; } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to create an external user {}", newExternalUserEntity, ex); throw new TechnicalManagementException("An error occurs while trying to create an external user" + newExternalUserEntity, ex); } } private void addDefaultMembership(User user) { RoleScope[] scopes = { RoleScope.ORGANIZATION, RoleScope.ENVIRONMENT }; List<RoleEntity> defaultRoleByScopes = roleService.findDefaultRoleByScopes(scopes); if (defaultRoleByScopes == null || defaultRoleByScopes.isEmpty()) { throw new DefaultRoleNotFoundException(scopes); } for (RoleEntity defaultRoleByScope : defaultRoleByScopes) { switch (defaultRoleByScope.getScope()) { case ORGANIZATION: membershipService.addRoleToMemberOnReference( GraviteeContext.getCurrentOrganization(), GraviteeContext.getCurrentEnvironment(), new MembershipService.MembershipReference( MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization() ), new MembershipService.MembershipMember(user.getId(), null, MembershipMemberType.USER), new MembershipService.MembershipRole(RoleScope.ORGANIZATION, defaultRoleByScope.getName()) ); break; case ENVIRONMENT: membershipService.addRoleToMemberOnReference( GraviteeContext.getCurrentOrganization(), GraviteeContext.getCurrentEnvironment(), new MembershipService.MembershipReference( MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironmentOrDefault() ), new MembershipService.MembershipMember(user.getId(), null, MembershipMemberType.USER), new MembershipService.MembershipRole(RoleScope.ENVIRONMENT, defaultRoleByScope.getName()) ); break; default: break; } } } @Override public UserEntity register(final NewExternalUserEntity newExternalUserEntity) { return register(newExternalUserEntity, null); } @Override public UserEntity register(final NewExternalUserEntity newExternalUserEntity, final String confirmationPageUrl) { final GraviteeContext.ReferenceContext currentContext = GraviteeContext.getCurrentContext(); if (confirmationPageUrl != null) { UrlSanitizerUtils.checkAllowed(confirmationPageUrl, portalWhitelist, true); } checkUserRegistrationEnabled(currentContext); boolean autoRegistrationEnabled = isAutoRegistrationEnabled(currentContext); return createAndSendEmail(newExternalUserEntity, USER_REGISTRATION, confirmationPageUrl, autoRegistrationEnabled, false); } private boolean isAutoRegistrationEnabled(GraviteeContext.ReferenceContext currentContext) { if (currentContext.getReferenceType().equals(GraviteeContext.ReferenceContextType.ORGANIZATION)) { return parameterService.findAsBoolean( Key.CONSOLE_USERCREATION_AUTOMATICVALIDATION_ENABLED, currentContext.getReferenceId(), ParameterReferenceType.ORGANIZATION ); } return parameterService.findAsBoolean( Key.PORTAL_USERCREATION_AUTOMATICVALIDATION_ENABLED, currentContext.getReferenceId(), ParameterReferenceType.ENVIRONMENT ); } @Override public UserEntity create(final NewPreRegisterUserEntity newPreRegisterUserEntity) { return createAndSendEmail(newPreRegisterUserEntity, USER_CREATION, null, true, newPreRegisterUserEntity.isService()); } /** * Allows to create an user and send an email notification to finalize its creation. */ private UserEntity createAndSendEmail( final NewExternalUserEntity newExternalUserEntity, final ACTION action, final String confirmationPageUrl, final boolean autoRegistrationEnabled, final boolean isServiceUser ) { if ( (!isServiceUser || StringUtils.isNotEmpty(newExternalUserEntity.getEmail())) && !EmailValidator.isValid(newExternalUserEntity.getEmail()) ) { throw new EmailFormatInvalidException(newExternalUserEntity.getEmail()); } String organizationId = GraviteeContext.getCurrentOrganization(); if (isBlank(newExternalUserEntity.getSource())) { newExternalUserEntity.setSource(IDP_SOURCE_GRAVITEE); } else if (!IDP_SOURCE_GRAVITEE.equals(newExternalUserEntity.getSource())) { // check if IDP exists identityProviderService.findById(newExternalUserEntity.getSource()); } if (isBlank(newExternalUserEntity.getSourceId())) { newExternalUserEntity.setSourceId(isServiceUser ? newExternalUserEntity.getLastname() : newExternalUserEntity.getEmail()); } final Optional<User> optionalUser; try { optionalUser = userRepository.findBySource(newExternalUserEntity.getSource(), newExternalUserEntity.getSourceId(), organizationId); if (optionalUser.isPresent()) { throw new UserAlreadyExistsException( newExternalUserEntity.getSource(), newExternalUserEntity.getSourceId(), organizationId ); } } catch (final TechnicalException e) { LOGGER.error( "An error occurs while trying to create user {} / {}", newExternalUserEntity.getSource(), newExternalUserEntity.getSourceId(), e ); throw new TechnicalManagementException(e.getMessage(), e); } final UserEntity userEntity = create(newExternalUserEntity, true, autoRegistrationEnabled); if (!isServiceUser) { if (IDP_SOURCE_GRAVITEE.equals(newExternalUserEntity.getSource())) { final Map<String, Object> params = getTokenRegistrationParams(userEntity, REGISTRATION_PATH, action, confirmationPageUrl); emailService.sendAsyncEmailNotification( new EmailNotificationBuilder() .to(userEntity.getEmail()) .template(EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_USER_REGISTRATION) .params(params) .param("registrationAction", USER_REGISTRATION.equals(action) ? "registration" : "creation") .build(), GraviteeContext.getCurrentContext() ); if (autoRegistrationEnabled) { notifierService.trigger( ACTION.USER_REGISTRATION.equals(action) ? PortalHook.USER_REGISTERED : PortalHook.USER_CREATED, params ); } else { notifierService.trigger(PortalHook.USER_REGISTRATION_REQUEST, params); } } } if (!isServiceUser && newExternalUserEntity.getNewsletter() != null && newExternalUserEntity.getNewsletter()) { newsletterService.subscribe(newExternalUserEntity.getEmail()); } return userEntity; } @Override public UserEntity processRegistration(String userId, boolean accepted) { UserEntity userToProcess = findById(userId); UserEntity processedUser = this.changeUserStatus(userId, accepted ? UserStatus.ACTIVE : UserStatus.REJECTED); final Map<String, Object> params = new NotificationParamsBuilder().user(processedUser).build(); emailService.sendAsyncEmailNotification( new EmailNotificationBuilder() .to(userToProcess.getEmail()) .template(EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_USER_REGISTRATION_REQUEST_PROCESSED) .params(params) .param("registrationStatus", accepted ? "accepted" : "rejected") .build(), GraviteeContext.getCurrentContext() ); auditService.createEnvironmentAuditLog( GraviteeContext.getCurrentEnvironment(), Collections.singletonMap(USER, processedUser.getId()), accepted ? User.AuditEvent.USER_CONFIRMED : User.AuditEvent.USER_REJECTED, processedUser.getUpdatedAt(), userToProcess, processedUser ); return processedUser; } private UserEntity changeUserStatus(String userId, UserStatus newStatus) { try { Optional<User> optionalUser = this.userRepository.findById(userId); if (optionalUser.isPresent()) { final User user = optionalUser.get(); user.setStatus(newStatus); user.setUpdatedAt(new Date()); if (newStatus == UserStatus.REJECTED) { //so a new registration can be requested with the same email user.setSourceId(newStatus.name().toLowerCase() + "-" + user.getSourceId()); } return convert(this.userRepository.update(user), true); } throw new UserNotFoundException(userId); } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to validate user registration {}", userId, ex); throw new TechnicalManagementException("An error occurs while trying to create an external user" + userId, ex); } } @Override public Map<String, Object> getTokenRegistrationParams(final UserEntity userEntity, final String managementUri, final ACTION action) { return getTokenRegistrationParams(userEntity, managementUri, action, null); } @Override public Map<String, Object> getTokenRegistrationParams( final UserEntity userEntity, final String managementUri, final ACTION action, final String targetPageUrl ) { // generate a JWT to store user's information and for security purpose final String jwtSecret = environment.getProperty("jwt.secret"); if (jwtSecret == null || jwtSecret.isEmpty()) { throw new IllegalStateException("JWT secret is mandatory"); } Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret")); Date issueAt = new Date(); Instant expireAt = issueAt .toInstant() .plus( Duration.ofSeconds( environment.getProperty("user.creation.token.expire-after", Integer.class, DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) ) ); final String token = JWT .create() .withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)) .withIssuedAt(issueAt) .withExpiresAt(Date.from(expireAt)) .withSubject(userEntity.getId()) .withClaim(Claims.EMAIL, userEntity.getEmail()) .withClaim(Claims.FIRSTNAME, userEntity.getFirstname()) .withClaim(Claims.LASTNAME, userEntity.getLastname()) .withClaim(Claims.ACTION, action.name()) .sign(algorithm); String managementURL = parameterService.find(Key.MANAGEMENT_URL, ParameterReferenceType.ORGANIZATION); String userURL = ""; if (!StringUtils.isEmpty(managementURL)) { if (managementURL.endsWith("/")) { managementURL = managementURL.substring(0, managementURL.length() - 1); } userURL = managementURL + "/#!/settings/users/" + userEntity.getId(); } String registrationUrl = ""; if (targetPageUrl != null && !targetPageUrl.isEmpty()) { registrationUrl += targetPageUrl; if (!targetPageUrl.endsWith("/")) { registrationUrl += "/"; } registrationUrl += token; } else if (!StringUtils.isEmpty(managementURL)) { registrationUrl = managementURL + managementUri + token; } else { // This value is used as a fallback when no Management URL has been configured by the platform admin. registrationUrl = DEFAULT_MANAGEMENT_URL + managementUri + token; LOGGER.warn( "An email will be sent with a default '" + managementUri.substring(4, managementUri.indexOf('/', 4)) + "' link. You may want to change this default configuration of the 'Management URL' in the Settings." ); } // send a confirm email with the token return new NotificationParamsBuilder().user(userEntity).token(token).registrationUrl(registrationUrl).userUrl(userURL).build(); } @Override public UserEntity update(String id, UpdateUserEntity updateUserEntity) { return this.update(id, updateUserEntity, updateUserEntity.getEmail()); } @Override public UserEntity update(String id, UpdateUserEntity updateUserEntity, String newsletterEmail) { try { LOGGER.debug("Updating {}", updateUserEntity); Optional<User> checkUser = userRepository.findById(id); if (!checkUser.isPresent()) { throw new UserNotFoundException(id); } User user = checkUser.get(); User previousUser = new User(user); // Set date fields user.setUpdatedAt(new Date()); // Set variant fields if (updateUserEntity.getPicture() != null) { user.setPicture(updateUserEntity.getPicture()); } if (updateUserEntity.getFirstname() != null) { user.setFirstname(updateUserEntity.getFirstname()); } if (updateUserEntity.getLastname() != null) { user.setLastname(updateUserEntity.getLastname()); } if (updateUserEntity.getEmail() != null && !updateUserEntity.getEmail().equals(user.getEmail())) { if (isInternalUser(user)) { // sourceId can be updated only for user registered into the Gravitee Repository // in that case, check if the email is available before update sourceId final Optional<User> optionalUser = userRepository.findBySource( user.getSource(), updateUserEntity.getEmail(), user.getOrganizationId() ); if (optionalUser.isPresent()) { throw new UserAlreadyExistsException(user.getSource(), updateUserEntity.getEmail(), user.getOrganizationId()); } user.setSourceId(updateUserEntity.getEmail()); } user.setEmail(updateUserEntity.getEmail()); } if (updateUserEntity.getStatus() != null) { user.setStatus(UserStatus.valueOf(updateUserEntity.getStatus())); } if (updateUserEntity.isNewsletter() != null) { user.setNewsletterSubscribed(updateUserEntity.isNewsletter()); if (updateUserEntity.isNewsletter() && newsletterEmail != null) { newsletterService.subscribe(newsletterEmail); } } User updatedUser = userRepository.update(user); auditService.createOrganizationAuditLog( GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, user.getId()), User.AuditEvent.USER_UPDATED, user.getUpdatedAt(), previousUser, user ); List<UserMetadataEntity> updatedMetadata = new ArrayList<>(); if (updateUserEntity.getCustomFields() != null && !updateUserEntity.getCustomFields().isEmpty()) { List<UserMetadataEntity> metadata = userMetadataService.findAllByUserId(user.getId()); for (Map.Entry<String, Object> entry : updateUserEntity.getCustomFields().entrySet()) { Optional<UserMetadataEntity> existingMeta = metadata .stream() .filter(meta -> meta.getKey().equals(entry.getKey())) .findFirst(); if (existingMeta.isPresent()) { UserMetadataEntity meta = existingMeta.get(); UpdateUserMetadataEntity metadataEntity = new UpdateUserMetadataEntity(); metadataEntity.setName(meta.getName()); metadataEntity.setKey(meta.getKey()); metadataEntity.setValue(String.valueOf(entry.getValue())); metadataEntity.setUserId(meta.getUserId()); metadataEntity.setFormat(meta.getFormat()); updatedMetadata.add(userMetadataService.update(metadataEntity)); } else { // some additional fields may have been added after the user registration NewUserMetadataEntity metadataEntity = new NewUserMetadataEntity(); metadataEntity.setName(entry.getKey()); metadataEntity.setValue(String.valueOf(entry.getValue())); metadataEntity.setUserId(user.getId()); metadataEntity.setFormat(MetadataFormat.STRING); updatedMetadata.add(userMetadataService.create(metadataEntity)); } } } return convert(updatedUser, true, updatedMetadata); } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to update {}", updateUserEntity, ex); throw new TechnicalManagementException("An error occurs while trying update " + updateUserEntity, ex); } } @Override public Page<UserEntity> search(String query, Pageable pageable) { LOGGER.debug("search users"); if (query == null || query.isEmpty()) { return search( new UserCriteria.Builder().statuses(UserStatus.ACTIVE, UserStatus.PENDING, UserStatus.REJECTED).build(), pageable ); } // UserDocumentTransformation remove domain from email address for security reasons // remove it during search phase to provide results String sanitizedQuery = query.indexOf('@') > 0 ? query.substring(0, query.indexOf('@')) : query; Query<UserEntity> userQuery = QueryBuilder.create(UserEntity.class).setQuery(sanitizedQuery).setPage(pageable).build(); SearchResult results = searchEngineService.search(userQuery); if (results.hasResults()) { List<UserEntity> users = new ArrayList<>((findByIds(results.getDocuments()))); populateUserFlags(users); return new Page<>(users, pageable.getPageNumber(), pageable.getPageSize(), results.getHits()); } return new Page<>(Collections.emptyList(), 1, 0, 0); } private void populateUserFlags(final List<UserEntity> users) { RoleEntity apiPORole = roleService.findPrimaryOwnerRoleByOrganization(GraviteeContext.getCurrentOrganization(), RoleScope.API); RoleEntity applicationPORole = roleService.findPrimaryOwnerRoleByOrganization( GraviteeContext.getCurrentOrganization(), RoleScope.APPLICATION ); users.forEach( user -> { final boolean apiPO = !membershipService .getMembershipsByMemberAndReferenceAndRole( MembershipMemberType.USER, user.getId(), MembershipReferenceType.API, apiPORole.getId() ) .isEmpty(); final boolean appPO = !membershipService .getMembershipsByMemberAndReferenceAndRole( MembershipMemberType.USER, user.getId(), MembershipReferenceType.APPLICATION, applicationPORole.getId() ) .isEmpty(); user.setPrimaryOwner(apiPO || appPO); user.setNbActiveTokens(tokenService.findByUser(user.getId()).size()); } ); } @Override public Page<UserEntity> search(UserCriteria criteria, Pageable pageable) { try { LOGGER.debug("search users"); UserCriteria.Builder builder = new UserCriteria.Builder() .organizationId(GraviteeContext.getCurrentOrganization()) .statuses(criteria.getStatuses()); if (criteria.hasNoStatus()) { builder.noStatus(); } UserCriteria newCriteria = builder.build(); Page<User> users = userRepository.search( newCriteria, new PageableBuilder().pageNumber(pageable.getPageNumber() - 1).pageSize(pageable.getPageSize()).build() ); List<UserEntity> entities = users.getContent().stream().map(u -> convert(u, false)).collect(toList()); populateUserFlags(entities); return new Page<>(entities, users.getPageNumber() + 1, (int) users.getPageElements(), users.getTotalElements()); } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to search users", ex); throw new TechnicalManagementException("An error occurs while trying to search users", ex); } } @Override public void delete(String id) { try { // If the users is PO of apps or apis, throw an exception long apiCount = apiService .findByUser(id, null, false) .stream() .filter(entity -> entity.getPrimaryOwner().getId().equals(id)) .count(); long applicationCount = applicationService .findByUser(GraviteeContext.getCurrentOrganization(), GraviteeContext.getCurrentEnvironment(), id) .stream() .filter(app -> app.getPrimaryOwner() != null) .filter(app -> app.getPrimaryOwner().getId().equals(id)) .count(); if (apiCount > 0 || applicationCount > 0) { throw new StillPrimaryOwnerException(apiCount, applicationCount); } Optional<User> optionalUser = userRepository.findById(id); if (!optionalUser.isPresent()) { throw new UserNotFoundException(id); } membershipService.removeMemberMemberships(MembershipMemberType.USER, id); User user = optionalUser.get(); //remove notifications portalNotificationService.deleteAll(user.getId()); portalNotificationConfigService.deleteByUser(user.getId()); genericNotificationConfigService.deleteByUser(user); //remove tokens tokenService.revokeByUser(user.getId()); // change user datas user.setSourceId("deleted-" + user.getSourceId()); user.setStatus(UserStatus.ARCHIVED); user.setUpdatedAt(new Date()); if (anonymizeOnDelete) { User anonym = new User(); anonym.setId(user.getId()); anonym.setCreatedAt(user.getCreatedAt()); anonym.setUpdatedAt(user.getUpdatedAt()); anonym.setStatus(user.getStatus()); anonym.setSource(user.getSource()); anonym.setLastConnectionAt(user.getLastConnectionAt()); anonym.setSourceId("deleted-" + user.getId()); anonym.setFirstname("Unknown"); anonym.setLastname(""); anonym.setLoginCount(user.getLoginCount()); user = anonym; } userRepository.update(user); final UserEntity userEntity = convert(optionalUser.get(), false); searchEngineService.delete(userEntity); } catch (TechnicalException ex) { LOGGER.error("An error occurs while trying to delete user", ex); throw new TechnicalManagementException("An error occurs while trying to delete user", ex); } } @Override public void resetPassword(final String id) { this.resetPassword(id, null); } @Override public UserEntity resetPasswordFromSourceId(String sourceId, String resetPageUrl) { if (sourceId.startsWith("deleted")) { throw new UserNotActiveException(sourceId); } UrlSanitizerUtils.checkAllowed(resetPageUrl, portalWhitelist, true); UserEntity foundUser = this.findBySource(IDP_SOURCE_GRAVITEE, sourceId, false); if ("ACTIVE".equals(foundUser.getStatus())) { this.resetPassword(foundUser.getId(), resetPageUrl); return foundUser; } else { throw new UserNotActiveException(foundUser.getSourceId()); } } private boolean isInternalUser(User user) { return IDP_SOURCE_GRAVITEE.equals(user.getSource()); } private void resetPassword(final String id, final String resetPageUrl) { try { LOGGER.debug("Resetting password of user id {}", id); Optional<User> optionalUser = userRepository.findById(id); if (!optionalUser.isPresent()) { throw new UserNotFoundException(id); } final User user = optionalUser.get(); if (!isInternalUser(user)) { throw new UserNotInternallyManagedException(id); } // do not update password to null anymore to avoid DoS attack on a user account. // use the audit events to throttle the number of resetPassword for a given userid // see: https://github.com/gravitee-io/issues/issues/4410 // do not perform this check if the request comes from an authenticated user (ie. admin or someone with right permission) if (!isAuthenticated() || !canResetPassword()) { AuditQuery query = new AuditQuery(); query.setEvents(Arrays.asList(User.AuditEvent.PASSWORD_RESET.name())); query.setFrom(Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli()); query.setPage(1); query.setSize(100); MetadataPage<AuditEntity> events = auditService.search(query); if (events != null) { if (events.getContent().size() == 100) { LOGGER.warn("More than 100 reset password received in less than 1 hour", user.getId()); } Optional<AuditEntity> optReset = events .getContent() .stream() .filter(evt -> user.getId().equals(evt.getProperties().get(USER.name()))) .findFirst(); if (optReset.isPresent()) { LOGGER.warn("Multiple reset password received for user '{}' in less than 1 hour", user.getId()); throw new PasswordAlreadyResetException(); } } } final Map<String, Object> params = getTokenRegistrationParams( convert(user, false), RESET_PASSWORD_PATH, RESET_PASSWORD, resetPageUrl ); notifierService.trigger(PortalHook.PASSWORD_RESET, params); auditService.createOrganizationAuditLog( GraviteeContext.getCurrentOrganization(), Collections.singletonMap(USER, user.getId()), User.AuditEvent.PASSWORD_RESET, new Date(), null, null ); emailService.sendAsyncEmailNotification( new EmailNotificationBuilder() .to(user.getEmail()) .template(EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_USER_PASSWORD_RESET) .params(params) .build(), GraviteeContext.getCurrentContext() ); } catch (TechnicalException ex) { final String message = "An error occurs while trying to reset password for user " + id; LOGGER.error(message, ex); throw new TechnicalManagementException(message, ex); } } protected boolean canResetPassword() { if (isAdmin()) { return true; } return permissionService.hasPermission( RolePermission.ORGANIZATION_USERS, GraviteeContext.getCurrentOrganization(), new RolePermissionAction[] { UPDATE } ); } private User convert(NewExternalUserEntity newExternalUserEntity) { if (newExternalUserEntity == null) { return null; } User user = new User(); user.setEmail(newExternalUserEntity.getEmail()); user.setFirstname(newExternalUserEntity.getFirstname()); user.setLastname(newExternalUserEntity.getLastname()); user.setSource(newExternalUserEntity.getSource()); user.setSourceId(newExternalUserEntity.getSourceId()); user.setStatus(UserStatus.ACTIVE); user.setPicture(newExternalUserEntity.getPicture()); user.setNewsletterSubscribed(newExternalUserEntity.getNewsletter()); return user; } private User convert(UserEntity userEntity) { if (userEntity == null) { return null; } User user = new User(); user.setId(userEntity.getId()); user.setEmail(userEntity.getEmail()); user.setFirstname(userEntity.getFirstname()); user.setLastname(userEntity.getLastname()); user.setSource(userEntity.getSource()); user.setSourceId(userEntity.getSourceId()); if (userEntity.getStatus() != null) { user.setStatus(UserStatus.valueOf(userEntity.getStatus())); } return user; } private UserEntity convert(User user, boolean loadRoles) { return convert(user, loadRoles, Collections.emptyList()); } private UserEntity convert(User user, boolean loadRoles, List<UserMetadataEntity> customUserFields) { if (user == null) { return null; } UserEntity userEntity = new UserEntity(); final String userId = user.getId(); userEntity.setId(userId); userEntity.setSource(user.getSource()); userEntity.setSourceId(user.getSourceId()); userEntity.setEmail(user.getEmail()); userEntity.setFirstname(user.getFirstname()); userEntity.setLastname(user.getLastname()); userEntity.setPassword(user.getPassword()); userEntity.setCreatedAt(user.getCreatedAt()); userEntity.setUpdatedAt(user.getUpdatedAt()); userEntity.setLastConnectionAt(user.getLastConnectionAt()); userEntity.setFirstConnectionAt(user.getFirstConnectionAt()); userEntity.setPicture(user.getPicture()); userEntity.setReferenceType(GraviteeContext.ReferenceContextType.ORGANIZATION.name()); userEntity.setReferenceId(user.getOrganizationId()); if (user.getStatus() != null) { userEntity.setStatus(user.getStatus().name()); } if (loadRoles) { Set<UserRoleEntity> roles = new HashSet<>(); Set<RoleEntity> roleEntities = membershipService.getRoles( MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userId ); if (!roleEntities.isEmpty()) { roleEntities.forEach(roleEntity -> roles.add(convert(roleEntity))); } this.environmentService.findByOrganization(GraviteeContext.getCurrentOrganization()) .stream() .flatMap( env -> membershipService .getRoles(MembershipReferenceType.ENVIRONMENT, env.getId(), MembershipMemberType.USER, userId) .stream() ) .filter(Objects::nonNull) .forEach(roleEntity -> roles.add(convert(roleEntity))); userEntity.setRoles(roles); Map<String, Set<UserRoleEntity>> envRolesMap = new HashMap<>(); this.environmentService.findByOrganization(GraviteeContext.getCurrentOrganization()) .forEach( env -> { Set<UserRoleEntity> envRoles = new HashSet<>(); Set<RoleEntity> envRoleEntities = membershipService.getRoles( MembershipReferenceType.ENVIRONMENT, env.getId(), MembershipMemberType.USER, userId ); if (!envRoleEntities.isEmpty()) { envRoleEntities.forEach(roleEntity -> envRoles.add(convert(roleEntity))); } envRolesMap.put(env.getId(), envRoles); } ); userEntity.setEnvRoles(envRolesMap); } userEntity.setLoginCount(user.getLoginCount()); userEntity.setNewsletterSubscribed(user.getNewsletterSubscribed()); if (customUserFields != null && !customUserFields.isEmpty()) { Maps.MapBuilder builder = Maps.builder(); for (UserMetadataEntity meta : customUserFields) { builder.put(meta.getKey(), meta.getValue()); } userEntity.setCustomFields(builder.build()); } return userEntity; } private UserRoleEntity convert(RoleEntity roleEntity) { if (roleEntity == null) { return null; } UserRoleEntity userRoleEntity = new UserRoleEntity(); userRoleEntity.setId(roleEntity.getId()); userRoleEntity.setScope(roleEntity.getScope()); userRoleEntity.setName(roleEntity.getName()); userRoleEntity.setPermissions(roleEntity.getPermissions()); return userRoleEntity; } @Override public UserEntity createOrUpdateUserFromSocialIdentityProvider(SocialIdentityProviderEntity socialProvider, String userInfo) { HashMap<String, String> attrs = getUserProfileAttrs(socialProvider.getUserProfileMapping(), userInfo); String email = attrs.get(SocialIdentityProviderEntity.UserProfile.EMAIL); if (email == null && socialProvider.isEmailRequired()) { throw new EmailRequiredException(attrs.get(SocialIdentityProviderEntity.UserProfile.ID)); } // Compute group and role mappings // This is done BEFORE updating or creating the user account to ensure this one is properly created with correct // information (ie. mappings) Set<GroupEntity> userGroups = computeUserGroupsFromProfile(email, socialProvider.getGroupMappings(), userInfo); Set<RoleEntity> userOrganizationRoles = new HashSet<>(); Map<String, Set<RoleEntity>> userEnvironmentRoles = new HashMap<>(); this.computeRolesToAddUser(email, socialProvider.getRoleMappings(), userInfo, userOrganizationRoles, userEnvironmentRoles); UserEntity user = null; boolean created = false; try { user = refreshExistingUser(socialProvider, attrs, email); } catch (UserNotFoundException unfe) { created = true; user = createNewExternalUser(socialProvider, userInfo, attrs, email); } // Memberships must be refresh only when it is a user creation context or mappings should be synced during // later authentication List<MembershipService.Membership> groupMemberships = refreshUserGroups(user.getId(), socialProvider.getId(), userGroups); List<MembershipService.Membership> roleOrganizationMemberships = refreshUserOrganizationRoles( user.getId(), socialProvider.getId(), userOrganizationRoles ); List<MembershipService.Membership> roleEnvironmentMemberships = refreshUserEnvironmentRoles( user.getId(), socialProvider.getId(), userEnvironmentRoles ); if (created || socialProvider.isSyncMappings()) { final boolean hasGroupMapping = socialProvider.getGroupMappings() != null && !socialProvider.getGroupMappings().isEmpty(); refreshUserMemberships(user.getId(), socialProvider.getId(), groupMemberships, hasGroupMapping, MembershipReferenceType.GROUP); final boolean hasRoleMapping = socialProvider.getRoleMappings() != null && !socialProvider.getRoleMappings().isEmpty(); refreshUserMemberships( user.getId(), socialProvider.getId(), roleOrganizationMemberships, hasRoleMapping, MembershipReferenceType.ORGANIZATION ); refreshUserMemberships( user.getId(), socialProvider.getId(), roleEnvironmentMemberships, hasRoleMapping, MembershipReferenceType.ENVIRONMENT ); } return user; } private HashMap<String, String> getUserProfileAttrs(Map<String, String> userProfileMapping, String userInfo) { TemplateEngine templateEngine = TemplateEngine.templateEngine(); templateEngine.getTemplateContext().setVariable(TEMPLATE_ENGINE_PROFILE_ATTRIBUTE, userInfo); ReadContext userInfoPath = JsonPath.parse(userInfo); HashMap<String, String> map = new HashMap<>(userProfileMapping.size()); for (Map.Entry<String, String> entry : userProfileMapping.entrySet()) { String field = entry.getKey(); String mapping = entry.getValue(); if (mapping != null) { try { if (mapping.contains("{#")) { map.put(field, templateEngine.getValue(mapping, String.class)); } else { map.put(field, userInfoPath.read(mapping, String.class)); } } catch (Exception e) { LOGGER.error("Using mapping: \"{}\", no fields are located in {}", mapping, userInfo); } } } return map; } private UserEntity createNewExternalUser( final SocialIdentityProviderEntity socialProvider, final String userInfo, HashMap<String, String> attrs, String email ) { final NewExternalUserEntity newUser = new NewExternalUserEntity(); newUser.setEmail(email); newUser.setSource(socialProvider.getId()); if (attrs.get(SocialIdentityProviderEntity.UserProfile.ID) != null) { newUser.setSourceId(attrs.get(SocialIdentityProviderEntity.UserProfile.ID)); } if (attrs.get(SocialIdentityProviderEntity.UserProfile.LASTNAME) != null) { newUser.setLastname(attrs.get(SocialIdentityProviderEntity.UserProfile.LASTNAME)); } if (attrs.get(SocialIdentityProviderEntity.UserProfile.FIRSTNAME) != null) { newUser.setFirstname(attrs.get(SocialIdentityProviderEntity.UserProfile.FIRSTNAME)); } if (attrs.get(SocialIdentityProviderEntity.UserProfile.PICTURE) != null) { newUser.setPicture(attrs.get(SocialIdentityProviderEntity.UserProfile.PICTURE)); } return this.create(newUser, false); } private UserEntity refreshExistingUser(final SocialIdentityProviderEntity socialProvider, HashMap<String, String> attrs, String email) { String userId; UserEntity registeredUser = this.findBySource(socialProvider.getId(), attrs.get(SocialIdentityProviderEntity.UserProfile.ID), false); userId = registeredUser.getId(); // User refresh UpdateUserEntity user = new UpdateUserEntity(); if (attrs.get(SocialIdentityProviderEntity.UserProfile.LASTNAME) != null) { user.setLastname(attrs.get(SocialIdentityProviderEntity.UserProfile.LASTNAME)); } if (attrs.get(SocialIdentityProviderEntity.UserProfile.FIRSTNAME) != null) { user.setFirstname(attrs.get(SocialIdentityProviderEntity.UserProfile.FIRSTNAME)); } if (attrs.get(SocialIdentityProviderEntity.UserProfile.PICTURE) != null) { user.setPicture(attrs.get(SocialIdentityProviderEntity.UserProfile.PICTURE)); } user.setEmail(email); return this.update(userId, user); } @Override public void computeRolesToAddUser( String username, List<RoleMappingEntity> mappings, String userInfo, Set<RoleEntity> rolesToAddToOrganization, Map<String, Set<RoleEntity>> rolesToAddToEnvironments ) { if (mappings == null || mappings.isEmpty()) { // provide default roles in this case otherwise user will not have roles if the RoleMapping isn't provided and if the // option to refresh user profile on each connection is enabled roleService .findDefaultRoleByScopes(RoleScope.ENVIRONMENT, RoleScope.ORGANIZATION) .stream() .forEach( roleEntity -> { if (roleEntity.getScope().equals(RoleScope.ENVIRONMENT)) { Set<RoleEntity> envRoles = rolesToAddToEnvironments.get(GraviteeContext.getCurrentEnvironmentOrDefault()); if (envRoles == null) { envRoles = new HashSet<>(); rolesToAddToEnvironments.put(GraviteeContext.getCurrentEnvironmentOrDefault(), envRoles); } envRoles.add(roleEntity); } else if (roleEntity.getScope().equals(RoleScope.ORGANIZATION)) { rolesToAddToOrganization.add(roleEntity); } } ); } else { for (RoleMappingEntity mapping : mappings) { TemplateEngine templateEngine = TemplateEngine.templateEngine(); templateEngine.getTemplateContext().setVariable(TEMPLATE_ENGINE_PROFILE_ATTRIBUTE, userInfo); boolean match = templateEngine.getValue(mapping.getCondition(), boolean.class); trace(username, match, mapping.getCondition()); // Get roles if (match) { if (mapping.getEnvironments() != null) { try { mapping .getEnvironments() .forEach( (environmentName, environmentRoles) -> { Set<RoleEntity> envRoles = rolesToAddToEnvironments.computeIfAbsent( environmentName, k -> new HashSet<>() ); for (String environmentRoleName : environmentRoles) { roleService .findByScopeAndName(RoleScope.ENVIRONMENT, environmentRoleName) .ifPresent(envRoles::add); } } ); } catch (RoleNotFoundException rnfe) { LOGGER.error("Unable to create user, missing role in repository : {}", mapping.getEnvironments()); } } if (mapping.getOrganizations() != null) { try { mapping .getOrganizations() .forEach( org -> roleService.findByScopeAndName(RoleScope.ORGANIZATION, org).ifPresent(rolesToAddToOrganization::add) ); } catch (RoleNotFoundException rnfe) { LOGGER.error("Unable to create user, missing role in repository : {}", mapping.getOrganizations()); } } } } } } private void addRolesToUser( String userId, Collection<RoleEntity> rolesToAdd, MembershipReferenceType referenceType, String referenceId ) { // add roles to user for (RoleEntity roleEntity : rolesToAdd) { MembershipService.MembershipReference ref = null; if (referenceType != null && referenceId != null) { ref = new MembershipService.MembershipReference(referenceType, referenceId); } else if (roleEntity.getScope() == RoleScope.ORGANIZATION) { ref = new MembershipService.MembershipReference( MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization() ); } else { ref = new MembershipService.MembershipReference(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment()); } membershipService.addRoleToMemberOnReference( GraviteeContext.getCurrentOrganization(), GraviteeContext.getCurrentEnvironment(), ref, new MembershipService.MembershipMember(userId, null, MembershipMemberType.USER), new MembershipService.MembershipRole(RoleScope.valueOf(roleEntity.getScope().name()), roleEntity.getName()) ); } } private void trace(String userId, boolean match, String condition) { if (LOGGER.isDebugEnabled()) { if (match) { LOGGER.debug("the expression {} match {} on user's info ", condition, userId); } else { LOGGER.debug("the expression {} didn't match {} on user's info ", condition, userId); } } } /** * Calculate the list of groups to associate to a user according to its OIDC profile (ie. UserInfo) * * @param userId * @param mappings * @param userInfo * @return */ private Set<GroupEntity> computeUserGroupsFromProfile(String userId, List<GroupMappingEntity> mappings, String userInfo) { if (mappings == null || mappings.isEmpty()) { return Collections.emptySet(); } Set<GroupEntity> groups = new HashSet<>(); for (GroupMappingEntity mapping : mappings) { TemplateEngine templateEngine = TemplateEngine.templateEngine(); templateEngine.getTemplateContext().setVariable(TEMPLATE_ENGINE_PROFILE_ATTRIBUTE, userInfo); boolean match = templateEngine.getValue(mapping.getCondition(), boolean.class); trace(userId, match, mapping.getCondition()); // Get groups if (match) { for (String groupName : mapping.getGroups()) { try { groups.add(groupService.findById(GraviteeContext.getCurrentEnvironment(), groupName)); } catch (GroupNotFoundException gnfe) { LOGGER.warn("Unable to map user groups, missing group in repository: {}", groupName); } } } } return groups; } private List<MembershipService.Membership> refreshUserGroups( String userId, String identityProviderId, Collection<GroupEntity> userGroups ) { List<MembershipService.Membership> memberships = new ArrayList<>(); // Get the default group roles from system List<RoleEntity> roleEntities = roleService.findDefaultRoleByScopes(RoleScope.API, RoleScope.APPLICATION); // Add groups to user for (GroupEntity groupEntity : userGroups) { for (RoleEntity roleEntity : roleEntities) { String defaultRole = roleEntity.getName(); // If defined, get the override default role at the group level if (groupEntity.getRoles() != null) { String groupDefaultRole = groupEntity.getRoles().get(RoleScope.valueOf(roleEntity.getScope().name())); if (groupDefaultRole != null) { defaultRole = groupDefaultRole; } } MembershipService.Membership membership = new MembershipService.Membership( new MembershipService.MembershipReference(MembershipReferenceType.GROUP, groupEntity.getId()), new MembershipService.MembershipMember(userId, null, MembershipMemberType.USER), new MembershipService.MembershipRole(roleEntity.getScope(), defaultRole) ); membership.setSource(identityProviderId); memberships.add(membership); } } return memberships; } private List<MembershipService.Membership> refreshUserOrganizationRoles( String userId, String identityProviderId, Collection<RoleEntity> userOrganizationRoles ) { return userOrganizationRoles .stream() .map( roleEntity -> { MembershipService.Membership membership = new MembershipService.Membership( new MembershipService.MembershipReference( MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization() ), new MembershipService.MembershipMember(userId, null, MembershipMemberType.USER), new MembershipService.MembershipRole(RoleScope.valueOf(roleEntity.getScope().name()), roleEntity.getName()) ); membership.setSource(identityProviderId); return membership; } ) .collect(Collectors.toList()); } private List<MembershipService.Membership> refreshUserEnvironmentRoles( String userId, String identityProviderId, Map<String, Set<RoleEntity>> userRolesByEnvironment ) { List<MembershipService.Membership> result = new ArrayList<>(); userRolesByEnvironment.forEach( (environmentId, userRoles) -> result.addAll( userRoles .stream() .map( roleEntity -> { MembershipService.Membership membership = new MembershipService.Membership( new MembershipService.MembershipReference(MembershipReferenceType.ENVIRONMENT, environmentId), new MembershipService.MembershipMember(userId, null, MembershipMemberType.USER), new MembershipService.MembershipRole( RoleScope.valueOf(roleEntity.getScope().name()), roleEntity.getName() ) ); membership.setSource(identityProviderId); return membership; } ) .collect(Collectors.toList()) ) ); return result; } /** * Refresh user memberships. * * @param userId User identifier. * @param identityProviderId The identity provider used to authenticate the user. * @param memberships List of memberships to associate to the user * @param hasMapping If the social provider has a mapping for the given type * @param types The types of user memberships to manage */ private void refreshUserMemberships( String userId, String identityProviderId, List<MembershipService.Membership> memberships, boolean hasMapping, MembershipReferenceType... types ) { // Get existing memberships for a given type List<Membership> userMemberships = new ArrayList<>(); for (MembershipReferenceType type : types) { try { userMemberships.addAll( membershipRepository.findByMemberIdAndMemberTypeAndReferenceType( userId, io.gravitee.repository.management.model.MembershipMemberType.USER, io.gravitee.repository.management.model.MembershipReferenceType.valueOf(type.name()) ) ); } catch (TechnicalException e) { final String msg = "An error occurs while finding memberships for user " + userId; LOGGER.error(msg, e); throw new TechnicalManagementException(msg, e); } } List<Membership> overrideUserMemberships = new ArrayList<>(); // Delete existing memberships userMemberships.forEach( membership -> { // Consider only membership "created by" the identity provider if (identityProviderId.equals(membership.getSource())) { // if there is no mapping configured on the social idp, we do not remove / reset it if (hasMapping) { membershipService.deleteReferenceMemberBySource( GraviteeContext.getCurrentOrganization(), GraviteeContext.getCurrentEnvironment(), MembershipReferenceType.valueOf(membership.getReferenceType().name()), membership.getReferenceId(), MembershipMemberType.USER, userId, membership.getSource() ); } } else { overrideUserMemberships.add(membership); } } ); Map<MembershipService.MembershipReference, Map<MembershipService.MembershipMember, Map<String, Collection<MembershipService.MembershipRole>>>> groupedRoles = new HashMap<>(); memberships .stream() .filter(membership -> !containsMembership(overrideUserMemberships, membership)) .forEach( membership -> groupedRoles .computeIfAbsent(membership.getReference(), ignore -> new HashMap<>()) .computeIfAbsent(membership.getMember(), ignore -> new HashMap<>()) .computeIfAbsent(membership.getSource(), ignore -> new ArrayList<>()) .add(membership.getRole()) ); // Create updated memberships groupedRoles.forEach( (reference, memberMapping) -> memberMapping.forEach( (member, sourceMapping) -> sourceMapping.forEach( (source, roles) -> membershipService.updateRolesToMemberOnReferenceBySource( GraviteeContext.getCurrentOrganization(), GraviteeContext.getCurrentEnvironment(), reference, member, roles, source ) ) ) ); } private boolean containsMembership(List<Membership> overrideUserMemberships, MembershipService.Membership membership) { return overrideUserMemberships .stream() .anyMatch( membership1 -> { if (membership1.getReferenceId().equals(membership.getReference().getId())) { RoleEntity byId = roleService.findById(membership1.getRoleId()); return membership.getRole().getScope().equals(byId.getScope()); } return false; } ); } @Override public void updateUserRoles(String userId, MembershipReferenceType referenceType, String referenceId, List<String> roleIds) { // check if user exist this.findById(userId); MemberEntity userMember = membershipService.getUserMember( GraviteeContext.getCurrentEnvironment(), referenceType, referenceId, userId ); if (userMember != null) { userMember .getRoles() .forEach( role -> { if (!roleIds.contains(role.getId())) { membershipService.removeRole(referenceType, referenceId, MembershipMemberType.USER, userId, role.getId()); } else { roleIds.remove(role.getId()); } } ); } if (!roleIds.isEmpty()) { this.addRolesToUser( userId, roleIds .stream() .map(roleService::findById) .filter(role -> role.getScope().equals(RoleScope.valueOf(referenceType.name()))) .collect(toSet()), referenceType, referenceId ); } } }
package com.innoz.toolbox.io.database.validation; import com.innoz.toolbox.io.database.handler.Logbook; public class ValidateNegativeTravelTimes implements Validator { @Override public boolean validate(Logbook logbook){ logbook.getStages().stream().filter(stage -> stage.getStartTime() != null).filter(stage -> stage.getEndTime() != null).forEach(stage ->{ double startTime = Double.parseDouble(stage.getStartTime()); double endTime = Double.parseDouble(stage.getEndTime()); if(startTime > endTime) { logbook.setDelete(true); return; } }); return !logbook.isDelete(); } }
package com.inprogress.reactnativeyoutube; import android.app.FragmentManager; import android.os.Build; import android.os.Parcelable; import android.content.pm.ActivityInfo; import android.support.annotation.Nullable; import android.widget.FrameLayout; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.events.RCTEventEmitter; public class YouTubeView extends FrameLayout { private YouTubePlayerController mYouTubeController; private VideoFragment mVideoFragment; private boolean mHasSavedInstance = false; public YouTubeView(ReactContext context) { super(context); init(); } public ReactContext getReactContext() { return (ReactContext) getContext(); } public void init() { inflate(getContext(), R.layout.youtube_layout, this); mVideoFragment = VideoFragment.newInstance(this); mYouTubeController = new YouTubePlayerController(this); } @Nullable @Override protected Parcelable onSaveInstanceState() { mHasSavedInstance = true; return super.onSaveInstanceState(); } @Override protected void onAttachedToWindow() { if (!mHasSavedInstance) { FragmentManager fragmentManager = getReactContext().getCurrentActivity().getFragmentManager(); fragmentManager.beginTransaction().add(getId(), mVideoFragment).commit(); } super.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { if (getReactContext().getCurrentActivity() != null) { FragmentManager fragmentManager = getReactContext().getCurrentActivity().getFragmentManager(); // Code crashes with java.lang.IllegalStateException: Activity has been destroyed // if our activity has been destroyed when this runs if (mVideoFragment != null) { boolean isDestroyed = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { isDestroyed = getReactContext().getCurrentActivity().isDestroyed(); } if (!isDestroyed) { // https://stackoverflow.com/a/34508430/61072 fragmentManager.beginTransaction().remove(mVideoFragment).commitAllowingStateLoss(); } } getReactContext() .getCurrentActivity() .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } super.onDetachedFromWindow(); } public void seekTo(int second) { mYouTubeController.seekTo(second); } public int getCurrentTime() { return mYouTubeController.getCurrentTime(); } public int getDuration() { return mYouTubeController.getDuration(); } public void nextVideo() { mYouTubeController.nextVideo(); } public void previousVideo() { mYouTubeController.previousVideo(); } public void playVideoAt(int index) { mYouTubeController.playVideoAt(index); } public int getVideosIndex() { return mYouTubeController.getVideosIndex(); } public void onVideoFragmentResume() { mYouTubeController.onVideoFragmentResume(); } public void receivedError(String param) { WritableMap event = Arguments.createMap(); ReactContext reactContext = getReactContext(); event.putString("error", param); event.putInt("target", getId()); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "error", event); } public void playerViewDidBecomeReady() { WritableMap event = Arguments.createMap(); ReactContext reactContext = getReactContext(); event.putInt("target", getId()); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "ready", event); } public void didChangeToSeeking(int milliSeconds) { WritableMap event = Arguments.createMap(); event.putString("state", "seeking"); event.putInt("currentTime", milliSeconds / 1000); event.putInt("target", getId()); ReactContext reactContext = getReactContext(); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "state", event); } public void didChangeToState(String param) { WritableMap event = Arguments.createMap(); event.putString("state", param); event.putInt("target", getId()); ReactContext reactContext = getReactContext(); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "state", event); } public void didChangeToQuality(String param) { WritableMap event = Arguments.createMap(); event.putString("quality", param); event.putInt("target", getId()); ReactContext reactContext = getReactContext(); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "quality", event); } public void didChangeToFullscreen(boolean isFullscreen) { WritableMap event = Arguments.createMap(); ReactContext reactContext = getReactContext(); event.putBoolean("isFullscreen", isFullscreen); event.putInt("target", getId()); reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "fullscreen", event); } public void setApiKey(String apiKey) { try { mVideoFragment.initialize(apiKey, mYouTubeController); } catch (Exception e) { receivedError(e.getMessage()); } } public void setVideoId(String str) { mYouTubeController.setVideoId(str); } public void setVideoIds(ReadableArray arr) { mYouTubeController.setVideoIds(arr); } public void setPlaylistId(String str) { mYouTubeController.setPlaylistId(str); } public void setPlay(boolean bool) { mYouTubeController.setPlay(bool); } public void setLoop(boolean bool) { mYouTubeController.setLoop(bool); } public void setFullscreen(boolean bool) { mYouTubeController.setFullscreen(bool); } public void setControls(int nb) { mYouTubeController.setControls(nb); } public void setShowFullscreenButton(boolean bool) { mYouTubeController.setShowFullscreenButton(bool); } public void setResumePlay(boolean bool) { mYouTubeController.setResumePlay(bool); } }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rvai.miwok; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; public class FamilyActivity extends AppCompatActivity { /** Handles playback of all the sound files */ private MediaPlayer mMediaPlayer; /** Handles audio focus when playing a sound file */ private AudioManager mAudioManager; /** * This listener gets triggered when the {@link MediaPlayer} has completed * playing the audio file. */ private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { // Now that the sound file has finished playing, release the media player resources. releaseMediaPlayer(); } }; /** * This listener gets triggered whenever the audio focus changes * (i.e., we gain or lose audio focus because of another app or device). */ private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { // The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a // short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that // our app is allowed to continue playing sound but at a lower volume. We'll treat // both cases the same way because our app is playing short sound files. // Pause playback and reset player to the start of the file. That way, we can // play the word from the beginning when we resume playback. mMediaPlayer.pause(); mMediaPlayer.seekTo(0); } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { // The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback. mMediaPlayer.start(); } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { // The AUDIOFOCUS_LOSS case means we've lost audio focus and // Stop playback and clean up resources releaseMediaPlayer(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.word_list); // Create and setup the {@link AudioManager} to request audio focus mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // Create a list of words final ArrayList<Word> words = new ArrayList<Word>(); words.add(new Word("father", "әpә", R.drawable.family_father, R.raw.family_father)); words.add(new Word("mother", "әṭa", R.drawable.family_mother, R.raw.family_mother)); words.add(new Word("son", "angsi", R.drawable.family_son, R.raw.family_son)); words.add(new Word("daughter", "tune", R.drawable.family_daughter, R.raw.family_daughter)); words.add(new Word("older brother", "taachi", R.drawable.family_older_brother, R.raw.family_older_brother)); words.add(new Word("younger brother", "chalitti", R.drawable.family_younger_brother, R.raw.family_younger_brother)); words.add(new Word("older sister", "teṭe", R.drawable.family_older_sister, R.raw.family_older_sister)); words.add(new Word("younger sister", "kolliti", R.drawable.family_younger_sister, R.raw.family_younger_sister)); words.add(new Word("grandmother ", "ama", R.drawable.family_grandmother, R.raw.family_grandmother)); words.add(new Word("grandfather", "paapa", R.drawable.family_grandfather, R.raw.family_grandfather)); // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The // adapter knows how to create list items for each item in the list. WordAdapter adapter = new WordAdapter(this, words, R.color.category_family); // Find the {@link ListView} object in the view hierarchy of the {@link Activity}. // There should be a {@link ListView} with the view ID called list, which is declared in the // word_list.xml layout file. ListView listView = (ListView) findViewById(R.id.list); // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the // {@link ListView} will display list items for each {@link Word} in the list. listView.setAdapter(adapter); // Set a click listener to play the audio when the list item is clicked on listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { // Release the media player if it currently exists because we are about to // play a different sound file releaseMediaPlayer(); // Get the {@link Word} object at the given position the user clicked on Word word = words.get(position); // Request audio focus so in order to play the audio file. The app needs to play a // short audio file, so we will request audio focus with a short amount of time // with AUDIOFOCUS_GAIN_TRANSIENT. int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // We have audio focus now. // Create and setup the {@link MediaPlayer} for the audio resource associated // with the current word mMediaPlayer = MediaPlayer.create(FamilyActivity.this, word.getAudioResourceId()); // Start the audio file mMediaPlayer.start(); // Setup a listener on the media player, so that we can stop and release the // media player once the sound has finished playing. mMediaPlayer.setOnCompletionListener(mCompletionListener); } } }); } @Override protected void onStop() { super.onStop(); // When the activity is stopped, release the media player resources because we won't // be playing any more sounds. releaseMediaPlayer(); } /** * Clean up the media player by releasing its resources. */ private void releaseMediaPlayer() { // If the media player is not null, then it may be currently playing a sound. if (mMediaPlayer != null) { // Regardless of the current state of the media player, release its resources // because we no longer need it. mMediaPlayer.release(); // Set the media player back to null. For our code, we've decided that // setting the media player to null is an easy way to tell that the media player // is not configured to play an audio file at the moment. mMediaPlayer = null; // Regardless of whether or not we were granted audio focus, abandon it. This also // unregisters the AudioFocusChangeListener so we don't get anymore callbacks. mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener); } } }
package com.github.elribeiro.inventory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProductsApplication { public static void main(String[] args) { SpringApplication.run(ProductsApplication.class, args); } }
/* * Copyright (c) 2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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.mbed.example.data; import com.arm.mbed.restclient.entity.notification.EndpointDescription; /** * @author szymon */ public class EndpointMetadata { private final String name; private final String type; EndpointMetadata(String name, String type) { this.name = name; this.type = type; } public String getName() { return name; } public String getType() { return type; } public static EndpointMetadata from(EndpointDescription ep) { return new EndpointMetadata(ep.getName(), ep.getType()); } }
/*- * ============LICENSE_START======================================================= * ONAP : CCSDK.apps * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2018 IBM. * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.onap.ccsdk.apps.ms.neng.core.policy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a sequence object in the policy, as a POJO. */ public class PolicySequence { /** * The type of the policy sequence. */ public enum Type { ALPHA, NUMERIC } private long startValue; private long increment; private long length; private Long maxValue; private String maxValueString; private Type type = Type.NUMERIC; private String scope; private String key; private String value; private Long lastReleaseSeqNumTried; private Logger logger = LoggerFactory.getLogger(PolicySequence.class); public long getStartValue() { return startValue; } public void setStartValue(long startValue) { this.startValue = startValue; } public long getIncrement() { return increment; } public void setIncrement(long increment) { this.increment = increment; } public long getLength() { return length; } public void setLength(long length) { this.length = length; } /** * Generate and return the maximum value for the sequence. */ public long getMaxValue() { if (this.maxValue == null) { int base = 10; if (this.type == Type.ALPHA) { base = 36; } if (this.maxValueString != null) { try { this.maxValue = Long.valueOf(this.maxValueString, base); } catch (Exception e) { logger.error("Exception",e); this.maxValue = null; } } if (this.maxValue == null) { long mlength = this.length; if (mlength <= 0) { mlength = 3; } this.maxValue = (long) Math.pow(base, mlength) - 1; } } return maxValue; } public void setMaxValue(long maxValue) { this.maxValue = maxValue; } public String getMaxValueString() { return maxValueString; } public void setMaxValueString(String maxValueString) { this.maxValueString = maxValueString; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } /** * Sets the type. */ public void setType(String typeStr) { if ("numeric".equalsIgnoreCase(typeStr)) { setType(Type.NUMERIC); } else if ("alpha-numeric".equalsIgnoreCase(typeStr)) { setType(Type.ALPHA); } } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Long getLastReleaseSeqNumTried() { return lastReleaseSeqNumTried; } public void setLastReleaseSeqNumTried(Long lastReleaseSeqNumTried) { this.lastReleaseSeqNumTried = lastReleaseSeqNumTried; } }
/* * LingPipe v. 4.1.0 * Copyright (C) 2003-2011 Alias-i * * This program is licensed under the Alias-i Royalty Free License * Version 1 WITHOUT ANY WARRANTY, without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Alias-i * Royalty Free License Version 1 for more details. * * You should have received a copy of the Alias-i Royalty Free License * Version 1 along with this program; if not, visit * http://alias-i.com/lingpipe/licenses/lingpipe-license-1.txt or contact * Alias-i, Inc. at 181 North 11th Street, Suite 401, Brooklyn, NY 11211, * +1 (718) 290-9170. */ package com.aliasi.cluster; import com.aliasi.io.LogLevel; import com.aliasi.io.Reporter; import com.aliasi.io.Reporters; import com.aliasi.stats.Statistics; import com.aliasi.symbol.MapSymbolTable; import com.aliasi.util.FeatureExtractor; import com.aliasi.util.ObjectToDoubleMap; import com.aliasi.util.SmallSet; import java.util.*; // import com.aliasi.util.Arrays; /** * A <code>KMeansClusterer</code> provides an implementation of * k-means(++) clustering based on vectors constructed by feature * extractors. An instance fixes a specific value of <code>K</code>, the * number of clusters returned. Initialization may be either by * the traditional k-means random assignment, or by the k-means++ * initialization strategy. * * <p>This clustering class is defined so as to be able to cluster * arbitrary objects. These objects are converted to (sparse) vectors * using a feature extractor specified during construction. * * <p><b>Feature Parsing to Cluster Objects</b> * * <p>The elements being clustered are first converted into feature * d-dimensional vectors using a feature extractor. These feature * vectors are then evenly distributed among the clusters using random * assignment. Feature extractors may normalize their input in any * number of ways. Run time is dominated by the density of the object * vectors. * * <p><b>Centroids</b> * * <p>In k-means, each cluster is modeled by the centroid of the * feature vectors assigned to it. The centroid of a set of points is * just the mean of the points, computed by dimension: * * <blockquote><pre> * centroid({v[0],...,v[n-1]}) = (v[0] + ... + v[n-1]) / n</blockquote></pre> * * Thus centroids are thus located in the same vector space * as the objects, namely they are d-dimensional vectors. * The code represents centroids as dense vectors, and objects * as sparse vectors. * * <p><b>Euclidean Distance</b> * * <p>Feature vectors are always compared to cluster centroids * using squared Euclidean distance, defined by: * * <blockquote><pre> * distance(x,y)<sup>2</sup> =(x - y) * (x - y) * = <big><big>&Sigma;</big></big><sub><sub>i</sub></sub> (x[i] - y[i])<sup>2</sup>)</pre></blockquote> * * The centroid of a set of points is the point that minimizes the sum * of square distances from the points in that set to the set. * * <p><b>K-means</b> * * <p>The k-means algorithm then iteratively improves cluster * assignments. Each epoch consists of two stages, reassignment * and recomputing the means. * * <p><i>Cluster Assignment:</i> &nbsp; In each epoch, we assign each object * to the cluster represented by the closest centroid. Ties go to the * lowest indexed element. * * <p><i>Mean Recomputation:</i> &nbsp; At the end of each epoch, the * centroids are then recomputed as the means of points assigned to * the cluster. * * <p><i>Convergence:</i> &nbsp; If no objects change cluster during an * iteration, the algorithm has converged and the results will be returned. * We also consider the algorithm converged if the relative reduction * in error from epoch to epoch falls below a set threshold. Also, the * algorithm will return if the maximum number of epochs have been reached. * * * <p><b>K-means as Minimization</b> * * <p>K-means clustering may be viewed as an iterative approach to the * minimization of the average sauare distance between items and their * cluster centers, which is: * * <blockquote><pre> * Err(cs) = <big><big><big>&Sigma;</big></big></big><sub>c in cs</sub> <big><big><big>&Sigma;</big></big></big><sub>x in c</sub> distance(x,centroid(x))<sup>2</sup></pre></blockquote> * * where <code>cs</code> is the set of clusters and <code>centroid(x)</code> * is the centroid (mean or average) of the cluster containing x. * * <p><b>Convergence Guarantees</b> * * <p>K-means clustering is guaranteed to converge to a local mimium * of error because both steps of K-means reduce error. First, * assigning each object to its closest centroid minimizes error given * the centroids. Second, recalculating centroids as the means of * elements assigned to them minimizes errors given the clustering. * Given that error is bounded at zero, and changes are discrete, * k-means must eventually converge. While there are exponentially * many possible clusterings in theory, in practice k-means converges * very quickly. * * * <p><b>Local Minima and Multiple Runs</b> * * <p>Like the EM algorithm, k-means clustering is highly sensitive to * the initial assignment of elements. In practice, it is often * helpful to apply k-means clustering repeatedly to the same input * data, returning the clustering with minimum error. * * <p>At the start of each iteration, the error of the previous * assignment is reported (at convergence, this will be the final * error). * * <p>Multiple runs may be used to provide bootstrap estimates * of the relatedness of any two elements. Bootstrap estimates * work by subsampling the elements to cluster with replacement * and then running k-means on them. This is repeated multiple * times, and the percentage of runs in which two elements fall * in the same cluster forms the bootstrap estimate of the likelihood * that they are in the same cluster. * * * <p><b>Degenerate Solutions</b> * * <p>In some cases, the iterative approach taken by k-means leads to * a solution in which not every cluster is populated. This happens * during a step in which no feature vector is closest to a given * centroid. This is most likely to happen in highly skewed data in * high dimensional spaces. Sometimes, rerunning the clusterer with a * different initialization will find a solution with k clusters. * * * <p><b>Picking a good <code>K</code></b> * * <p>The number of clusters, k, may also be varied. In this case, * new k-means clustering instances must be created, as each uses * a fixed number of clusters. * * <p>By varying <code>k</code>, the maximum number of clusters, * the within-cluster scatter may be compared across different choices * of <code>k</code>. Typically, a value of <code>k</code> is chosen * at a knee of the within-cluster scatter scores. There are automatic * ways of performing this selection, though they are heuristically * rather than theoretically motivated. * * <p>In practice, it is technically possible, though unlikely, for * clusters to wind up with no elements in them. This implementation * will simply return fewer clusters than the maximum specified in * this case. * * * <p><b>K-Means++ Initialization</b> * * <p> K-means++ is a k-means algorithm that attempts to make a good * randomized choice of initial centers. This requires choosing a * diverse set of centers, but not overpopulating the initial set of * centers with outliers. <p>K-means++ has reasonable expected * performance bounds in theory, and quite good performance in * practice. * * <p>Suppose we have K clusters and a set X of size at least K. * K-means++ chooses a single point c[k] in X as each initial * centroid, using the following strategy: * * <blockquote><pre> * 1. Sample the first centroid c[1] randomly from X. * * 2. For k = 2 to K * * Sample the next centroid c[k] = x * with probability proportional to D(x)<sup><sup>2</sup></sup> * </pre></blockquote> * * where D(x) is the minimum distance to an existing centroid: * * <blockquote><pre> * D(x) = min<sub><sub>k' &lt; k</sub></sub> d(x,c[k'])</pre></blockquote> * * After initialization, k-means++ proceeds just as traditional * k-means clustering. * * <p>The good expected behavior form k-means++ arises from choosing * the next center in such a way that it's far away from existing * centers. Many nearby points in some sense pool their behavior, * because the chance that one will be picked is the sum of the chance * that each will be picked. Outliers are, by definition, points x * with high values of D(x) but which are not near other points. * * * <p><b>Relation to Gaussian Mixtures and Expectation/Maximization</b> * * <p>The k-means clustering algorithm is implicitly based on a * multi-dimensional Gaussian with independent dimensions with shared * means (the centroids) and equal variances. Estimates are carried * out by maximum likelihood; that is, no prior, or equivalently the * fully uninformative prior, is used. Where k-means differs from * standard expectation/maximization (EM) is that k-means reweights * the expectations so that the closest centroid gets an expectation * of 1.0 and all other centroids get an expectation of 0.0. This * approach has been called &quot;winner-take-all&quot; EM in the EM * literature. * * * <p><b>Implementation Notes</b> * * <p>The current implementation conserves some computations versus * the brute-force approach by (1) only computing vector products * in comparing two vectors, and (2) not recomputing distances if * we know the * * * <p><b>References</b> * * <ul> * <li> * MacQueen, J. B. 1967. Some Methods for classification and Analysis of Multivariate Observations. * <i> Proceedings of Fifth Berkeley Symposium on Mathematical Statistics and Probability</i>. * University of California Press. * * <li> * Andrew Moore's <a href="http://www.autonlab.org/tutorials/kmeans11.pdf">K-Means Tutorial</a> including most of the mathematics * </li> * * <li> * Matteo Matteucci's <a href="http://home.dei.polimi.it/matteucc/Clustering/tutorial_html/kmeans.html">K-Means Tutorial</a> including a very nice <a href="http://www.elet.polimi.it/upload/matteucc/Clustering/tutorial_html/AppletKM.html">interactive servlet demo</a> * </li> * * <li> * Hastie, T., R. Tibshirani and J.H. Friedman. 2001. <i>The * Elements of Statistical Learning</i>. Springer-Verlag. * </li> * * <li> * Wikipedia: <a href="http://en.wikipedia.org/wiki/K-means_algorithm">K-means Algorithm</a> * </li> * * <li> * Arthur, David and Sergei Vassilvitski (2007) <a href="http://www.stanford.edu/~darthur/kMeansPlusPlus.pdf">k-means++: The Advantages of Careful Seeding</a>. SODA 2007. * </li> * </ul> * * @author Bob Carpenter * @version 4.0.0 * @since LingPipe2.0 * @param <E> the type of objects being clustered */ public class KMeansClusterer<E> implements Clusterer<E> { final FeatureExtractor<E> mFeatureExtractor; final int mMaxNumClusters; final int mMaxEpochs; final boolean mKMeansPlusPlus; final double mMinRelativeImprovement; /** * Construct a k-means clusterer with the specified feature * extractor, number of clusters and limit on number of epochs * to run optimization. Initialization of each cluster is with * random shuffling of all elements into a cluster. * * <p>If the number of epochs is set to zero, the result * will be random balanced clusterings of the specified size. * * @param featureExtractor Feature extractor for this clusterer. * @param numClusters Number of clusters to return. * @param maxEpochs Maximum number of epochs during * optimization. * @throws IllegalArgumentException If the number of clusters is * less than 1, or if the maximum number of epochs is less * than 0. */ KMeansClusterer(FeatureExtractor<E> featureExtractor, int numClusters, int maxEpochs) { this(featureExtractor,numClusters,maxEpochs, false,0.0); } /** * Construct a k-means clusterer with the specified feature * extractor, number of clusters, minimum improvement per cluster, * using either traditional or k-means++ initialization. * * <p>If the kMeansPlusPlus flag is set to {@code true}, the * k-means++ initialization strategy is used. If it is set to * false, initialization of each cluster will be handled by a * random shuffling of all elements into a cluster. * * <p>If the number of epochs is set to zero, the result will be a * random balanced clusterings of the specified size. * * @param featureExtractor Feature extractor for this clusterer. * @param numClusters Number of clusters to return. * @param maxEpochs Maximum number of epochs during * @param kMeansPlusPlus Set to {@code true} to use k-means++ * initialization. optimization. * @param minImprovement Minimum relative improvement in squared * distance scatter to keep going to the next epoch. * @throws IllegalArgumentException If the number of clusters is * less than 1, if the maximum number of epochs is less than 0, or * if the minimum improvement is not a finite, non-negative number. */ public KMeansClusterer(FeatureExtractor<E> featureExtractor, int numClusters, int maxEpochs, boolean kMeansPlusPlus, double minImprovement) { if (numClusters < 1) { String msg = "Number of clusters must be positive." + " Found numClusters=" + numClusters; throw new IllegalArgumentException(msg); } if (maxEpochs < 0) { String msg = "Number of epochs must be non-negative." + " Found maxEpochs=" + maxEpochs; throw new IllegalArgumentException(msg); } if (minImprovement < 0.0 || Double.isNaN(minImprovement)) { String msg = "Mimium improvement must be non-negative." + " Found minImprovement=" + minImprovement; throw new IllegalArgumentException(msg); } mFeatureExtractor = featureExtractor; mMaxNumClusters = numClusters; mMaxEpochs = maxEpochs; mKMeansPlusPlus = kMeansPlusPlus; mMinRelativeImprovement = minImprovement; } /** * Returns the feature extractor for this clusterer. * * @return The feature extractor for this clusterer. */ public FeatureExtractor<E> featureExtractor() { return mFeatureExtractor; } /** * Returns the maximum number of clusters this clusterer will * return. This is the &quot;<code>k</code>&quot; in * &quot;k-means&quot;. * * <p>Clustering fewer elements will result in fewer clusters. * * @return The number of clusters this clusterer will return. */ public int numClusters() { return mMaxNumClusters; } /** * Returns the maximum number of epochs for this clusterer. * * @return The maximum number of epochs. */ public int maxEpochs() { return mMaxEpochs; } /** * Return a k-means clustering of the specified set of elements * using a freshly generated random number generator without * intermediate reporting. The feature extractor, maximum number of * epochs, number of clusters, and minimum relative improvement, * and whether to use k-means++ initialization are defined in the * class. * * <p>This is just a utility method implementing the * {@link Clusterer} interface. A call to * {@code cluster(elementSet)} produces the same result * as {@code cluster(elementSet,new Random(),null)}. * * <p>See the class documentation above for more information. * * @param elementSet Set of elements to cluster. * @return Clustering of the specified elements. */ public Set<Set<E>> cluster(Set<? extends E> elementSet) { return cluster(elementSet,new Random(),null); } /** * Return the k-means clustering for the specified set of * elements, using the specified random number generator, sending * progress reports to the specified reporter. The feature * extractor, maximum number of epochs, number of clusters, and * minimum relative improvement, and whether to use k-means++ * initialization are defined in the class. * * <p>The reason this is a separate method is that typical * implementations of {@link Random} are not thread safe, * and rarely should reports from different clustering runs * be interleaved to a reporter. * * <p>Using a fixed random number generator (e.g. by using the * same seed for {@link Random}) will result in the same * resulting clustering, which can be useful for replicating * tests. * * <p>See the class documentation above for more information. * * @param elementSet Set of elements to cluster * @param random Random number generator * @param reporter Reporter to which progress reports are sent, * or {@code null} if no reporting is required. */ public Set<Set<E>> cluster(Set<? extends E> elementSet, Random random, Reporter reporter) { if (reporter == null) reporter = Reporters.silent(); final int numElements = elementSet.size(); final int numClusters = mMaxNumClusters; reporter.report(LogLevel.INFO, "#Elements=" + numElements); reporter.report(LogLevel.INFO, "#Clusters=" + numClusters); if (numElements <= numClusters) { reporter.report(LogLevel.INFO, "Returning trivial clustering due to #elements < #clusters"); return trivialClustering(elementSet); } @SuppressWarnings("unchecked") final E[] elements = (E[]) elementSet.toArray(new Object[0]); reporter.report(LogLevel.DEBUG,"Converting inputs to sparse vectors"); final int[][] featuress = new int[numElements][]; final double[][] valss = new double[numElements][]; final double[] eltSqLengths = new double[numElements]; MapSymbolTable symTab = toVectors(elements,featuress,valss,eltSqLengths); int numDims = symTab.numSymbols(); reporter.report(LogLevel.INFO,"#Dimensions=" + numDims); final double[][] centroidss = new double[numClusters][numDims]; final int[] closestCenters = new int[numElements]; final double[] sqDistToCenters = new double[numElements]; if (true) { reporter.report(LogLevel.INFO,"K-Means++ Initialization"); kmeansPlusPlusInit(featuress,valss,eltSqLengths, closestCenters, centroidss, random); } else { reporter.report(LogLevel.INFO,"K-Means Random Initialization"); randomInit(featuress,valss, closestCenters, centroidss, random); } return kMeansEpochs(elements,eltSqLengths, centroidss, featuress,valss, sqDistToCenters,closestCenters, mMaxEpochs,reporter); } /** * Returns the minimum reduction in relative error required to * continue to the next epoch during clustering. * * @return The minimum improvement per epoch. */ public double minRelativeImprovement() { return mMinRelativeImprovement; } /** * Recluster the specified initial clustering, adding in the * unclustered elements, reporting progress to the specified * reporter. The number of clusters is set by the size of the * initial clustering as measured by the number of non-empty * clusters it contains. This clusterer's maximum number of epochs and minimum * improvement will be used. * * @param initialClustering Initialization of clustering. * @param unclusteredElements Elements that have not been clustered. * @param reporter Reporter to which to send progress reports, * or {@code null} for no reporting. * @throws IllegalArgumentException If there are empty clusters * in the clustering or if an element belongs to more than * one cluster. * @return The reclustering. */ public Set<Set<E>> recluster(Set<Set<E>> initialClustering, Set<E> unclusteredElements, Reporter reporter) { return recluster(initialClustering,unclusteredElements, mMaxEpochs,reporter); } /** * Recluster the specified clustering using up to the specified * number of k-means epochs with no reporting. * * <p>This method allows users to specify their own * initial clusterings, which are then reallocated using the * standard k-means algorithm. * * <p>The number of clusters produced will be the size of the * initial clustering, which may not match the number of clusters * defined in the constructor. * * @param clustering Clustering to recluster. * @param maxEpochs Maximum number of reclustering epochs. * @return New clustering of input elements. * @throws IllegalArgumentException If there are empty clusters * in the clustering or if an element belongs to more than * one cluster. */ Set<Set<E>> recluster(Set<Set<E>> clustering, int maxEpochs) { return recluster(clustering, SmallSet.<E>create(), maxEpochs, null); } private Set<Set<E>> recluster(Set<Set<E>> clustering, Set<E> unclusteredElements, int maxEpochs, Reporter reporter) { if (reporter == null) reporter = Reporters.silent(); reporter.report(LogLevel.INFO, "Reclustering"); int numClusters = clustering.size(); reporter.report(LogLevel.INFO, "# Clusters=" + numClusters); Set<E> elementSet = new HashSet<E>(); for (Set<E> cluster : clustering) { for (E e : cluster) { if (!elementSet.add(e)) { String msg = "An element must not be in two clusters." + " Found an element in two clusters." + " Element=" + e; throw new IllegalArgumentException(msg); } } } int numClusteredElements = elementSet.size(); for (E e : unclusteredElements) { if (!elementSet.add(e)) { String msg = "An element may not be in a cluster and unclustered." + " Found unclustered element in a cluster." + " Element=" + e; throw new IllegalArgumentException(msg); } } int numElements = elementSet.size(); reporter.report(LogLevel.INFO, "# Clustered Elements=" + numClusteredElements); reporter.report(LogLevel.INFO, "# Unclustered Elements=" + unclusteredElements.size()); reporter.report(LogLevel.INFO, "# Elements Total=" + numElements); @SuppressWarnings("unchecked") E[] elements = (E[]) new Object[numElements]; int i = 0; for (Set<E> cluster : clustering) for (E e : cluster) elements[i++] = e; for (E e : unclusteredElements) elements[i++] = e; reporter.report(LogLevel.DEBUG, "Converting to vectors"); // cut and paste from main clustering final int[][] featuress = new int[numElements][]; final double[][] valss = new double[numElements][]; final double[] eltSqLengths = new double[numElements]; MapSymbolTable symTab = toVectors(elements,featuress,valss,eltSqLengths); int numDims = symTab.numSymbols(); reporter.report(LogLevel.INFO,"#Dimensions=" + numDims); double[][] centroidss = new double[numClusters][numDims]; int[] closestCenters = new int[numElements]; i = 0; int k = 0; for (Set<E> cluster : clustering) { double[] centroidK = centroidss[k]; for (E e : cluster) { closestCenters[i] = k; increment(centroidK,featuress[i],valss[i]); ++i; } ++k; } double[] sqDistToCenters = new double[numElements]; Arrays.fill(sqDistToCenters,Double.POSITIVE_INFINITY); // reassign everyone for (k = 0; k < numClusters; ++k) { double[] centroidK = centroidss[k]; double centroidSqLength = selfProduct(centroidss[k]); for (i = 0; i < numElements; ++i) { double sqDistToCenter = centroidSqLength + eltSqLengths[i] - 2.0 * product(centroidK,featuress[i],valss[i]); if (sqDistToCenter < sqDistToCenters[i]) { sqDistToCenters[i] = sqDistToCenter; closestCenters[i] = k; } } } for (double[] centroid : centroidss) Arrays.fill(centroid,0.0); setCentroids(centroidss,featuress,valss,closestCenters); return kMeansEpochs(elements,eltSqLengths, centroidss, featuress,valss, sqDistToCenters,closestCenters, maxEpochs,reporter); } private Set<Set<E>> kMeansEpochs(E[] elements, double[] eltSqLengths, double[][] centroidss, int[][] featuress, double[][] valss, double[] sqDistToCenters, int[] closestCenters, int maxEpochs, Reporter reporter) { int numClusters = centroidss.length; int numDims = centroidss[0].length; int numElements = elements.length; final double[] centroidSqLengths = centroidSqLengths(centroidss); boolean[] lastCentroidChanges = createBooleanArray(numClusters,true); final int[] changedClusters = new int[numClusters]; final int[] counts = new int[numClusters]; double lastError = Double.POSITIVE_INFINITY; for (int epoch = 0; epoch < maxEpochs; ++epoch) { reporter.report(LogLevel.DEBUG,"Epoch=" + epoch); boolean atLeastOneClusterChanged = false; int numChangedClusters = setChangedClusters(changedClusters,lastCentroidChanges); reporter.report(LogLevel.DEBUG," #changed clusters=" + numChangedClusters); final boolean[] centroidChanges = createBooleanArray(numClusters,false); // *** multi-thread all of this loop; optimistic updates sets to true *** for (int i = 0; i < numElements; ++i) { final int[] featuresI = featuress[i]; final double[] valsI = valss[i]; final double eltSqLengthI = eltSqLengths[i]; double closestSqDistToCenter = lastCentroidChanges[closestCenters[i]] ? Double.POSITIVE_INFINITY : sqDistToCenters[i]; int bestCenter = -1; // set if beat unchanged ctr, or if ctr changed for (int kk = 0; kk < numChangedClusters; ++kk) { // cut and paste (below) int k = changedClusters[kk]; double sqDistToCenter = centroidSqLengths[k] + eltSqLengthI - 2.0 * product(centroidss[k],featuresI,valsI); if (sqDistToCenter < closestSqDistToCenter) { closestSqDistToCenter = sqDistToCenter; bestCenter = k; } } // leave unchanged if can't beat old (or infty if old's expired) if (bestCenter == -1) continue; // have to be worse than previous best, or skip unchanged clusts if (closestSqDistToCenter > sqDistToCenters[i]) { for (int kk = numChangedClusters; kk < numClusters; ++kk) { // cut and paste (above) int k = changedClusters[kk]; double sqDistToCenter = centroidSqLengths[k] + eltSqLengthI - 2.0 * product(centroidss[k],featuresI,valsI); if (sqDistToCenter < closestSqDistToCenter) { closestSqDistToCenter = sqDistToCenter; bestCenter = k; } } } // could change even if center id doesn't sqDistToCenters[i] = closestSqDistToCenter; if (bestCenter == closestCenters[i]) continue; atLeastOneClusterChanged = true; centroidChanges[bestCenter] = true; // to centroidChanges[closestCenters[i]] = true; // from closestCenters[i] = bestCenter; } double error = sum(sqDistToCenters)/numElements; reporter.report(LogLevel.DEBUG, " avg dist to center=" + error); if (!atLeastOneClusterChanged) { reporter.report(LogLevel.INFO,"Converged by no elements changing cluster."); break; } double relImprovement = relativeImprovement(lastError,error); if (relImprovement < mMinRelativeImprovement) { reporter.report(LogLevel.INFO, "Converged by relative improvement < threshold"); break; } Arrays.fill(counts,0); int numChangedElts = 0; for (int k = 0; k < numClusters; ++k) if (centroidChanges[k]) Arrays.fill(centroidss[k],0.0); for (int i = 0; i < numElements; ++i) { int closestCenterI = closestCenters[i]; if (centroidChanges[closestCenterI]) { increment(centroidss[closestCenterI], featuress[i],valss[i]); ++counts[closestCenterI]; ++numChangedElts; } } reporter.report(LogLevel.DEBUG, " #changed elts=" + numChangedElts); for (int k = 0; k < numClusters; ++k) { if (counts[k] > 0) { final double[] centroidK = centroidss[k]; double countD = (double) counts[k]; double sqLength = 0.0; for (int d = 0; d < numDims; ++d) { centroidK[d] /= countD; sqLength += centroidK[d] * centroidK[d]; } centroidSqLengths[k] = sqLength; } } lastCentroidChanges = centroidChanges; if (epoch == (maxEpochs-1)) { reporter.report(LogLevel.INFO, "Reached max epochs. Breaking without convergence."); } } reporter.report(LogLevel.DEBUG,"Constructing Result"); List<ObjectToDoubleMap<E>> scoreMapList = new ArrayList<ObjectToDoubleMap<E>>(numClusters); double[] totalScores = new double[numClusters]; for (int k = 0; k < numClusters; ++k) scoreMapList.add(new ObjectToDoubleMap<E>()); for (int i = 0; i < numElements; ++i) { scoreMapList.get(closestCenters[i]).set(elements[i], sqDistToCenters[i] == 0.0 ? -Double.MIN_VALUE : -sqDistToCenters[i]); totalScores[closestCenters[i]] -= sqDistToCenters[i]; } ObjectToDoubleMap<Set<E>> clusterScores = new ObjectToDoubleMap<Set<E>>(); for (int k = 0; k < numClusters; ++k) { ObjectToDoubleMap<E> clusterDistances = scoreMapList.get(k); if (clusterDistances.isEmpty()) continue; Set<E> cluster = new LinkedHashSet<E>(clusterDistances.keysOrderedByValueList()); clusterScores.set(cluster, totalScores[k] == 0.0 ? -Double.MIN_VALUE : totalScores[k]/cluster.size()); } Set<Set<E>> result = new LinkedHashSet<Set<E>>(clusterScores.keysOrderedByValueList()); return result; } static double relativeImprovement(double x, double y) { return Math.abs(2.0 * (x - y) /(Math.abs(x) + Math.abs(y))); } static int setChangedClusters(int[] clusterIndexes, boolean[] changed) { int numChanged = 0; int numNotChanged = clusterIndexes.length - 1; // really fancy: numNotChanged = changed.length-i-numChanged-1 for (int i = 0; i < changed.length; ++i) clusterIndexes[changed[i] ? numChanged++ : numNotChanged--] = i; return numChanged; } static boolean[] createBooleanArray(int length, boolean fillValue) { boolean[] result = new boolean[length]; if (fillValue) Arrays.fill(result,true); return result; } private MapSymbolTable toVectors(E[] elements, int[][] featuress, double[][] valss, double[] eltSqLengths) { MapSymbolTable symTab = new MapSymbolTable(); for (int i = 0; i < elements.length; ++i) { E e = elements[i]; Map<String,? extends Number> featureMap = mFeatureExtractor.features(e); featuress[i] = new int[featureMap.size()]; valss[i] = new double[featureMap.size()]; int j = 0; for (Map.Entry<String,? extends Number> entry : featureMap.entrySet()) { featuress[i][j] = symTab.getOrAddSymbol(entry.getKey()); valss[i][j] = entry.getValue().doubleValue(); ++j; } eltSqLengths[i] = selfProduct(valss[i]); } return symTab; } private Set<Set<E>> trivialClustering(Set<? extends E> elementSet) { Set<Set<E>> clustering = new HashSet<Set<E>>((3 * elementSet.size()) / 2); for (E elt : elementSet) { Set<E> cluster = SmallSet.<E>create(elt); clustering.add(cluster); } return clustering; } private void randomInit(int[][] featuress, double[][] valss, int[] closestCenters, double[][] centroidss, Random random) { int numClusters = centroidss.length; int numElements = featuress.length; int[] permutation = Statistics.permutation(numElements,random); int[] count = new int[numClusters]; for (int i = 0; i < numElements; ++i) closestCenters[i] = i % numClusters; setCentroids(centroidss,featuress,valss,closestCenters); } private void kmeansPlusPlusInit(int[][] featuress, double[][] valss, double[] eltSqLengths, int[] closestCenters, double[][] centroidss, Random random) { int numClusters = centroidss.length; int numElements = featuress.length; double[] sqDistToCenters = new double[numElements]; Arrays.fill(sqDistToCenters,Double.POSITIVE_INFINITY); for (int k = 0; k < numClusters; ++k) { final double[] centroidK = centroidss[k]; int centroidIndex = (k == 0) ? random.nextInt(numElements) : sampleNextCenter(sqDistToCenters,random); setCentroid(centroidK, featuress[centroidIndex],valss[centroidIndex]); double centroidSqLength = selfProduct(valss[centroidIndex]); for (int i = 0; i < numElements; ++i) { double sqDistToCenter = centroidSqLength + eltSqLengths[i] - 2.0 * product(centroidK,featuress[i],valss[i]); if (sqDistToCenter < sqDistToCenters[i]) { sqDistToCenters[i] = sqDistToCenter; closestCenters[i] = k; } } } for (double[] centroid : centroidss) Arrays.fill(centroid,0.0); // reset after previous use setCentroids(centroidss,featuress,valss,closestCenters); } private void setCentroids(double[][] centroidss, int[][] featuress, double[][] valss, int[] closestCenters) { int numClusters = centroidss.length; int numElements = featuress.length; final int[] count = new int[numClusters]; for (int i = 0; i < numElements; ++i) { increment(centroidss[closestCenters[i]], featuress[i],valss[i]); ++count[closestCenters[i]]; } for (int k = 0; k < numClusters; ++k) { double countK = count[k]; final double[] centroid = centroidss[k]; for (int d = 0; d < centroid.length; ++d) { centroid[d] = centroid[d] / countK; } } } private static int sampleNextCenter(double[] probRatios, Random random) { double samplePoint = random.nextDouble() * sum(probRatios); double total = 0.0; for (int i = 0; i < probRatios.length; ++i) { total += probRatios[i]; if (total >= samplePoint) return i; } return probRatios.length-1; // arith overrun } private static double[] centroidSqLengths(double[][] centroidss) { double[] result = new double[centroidss.length]; for (int i = 0; i < result.length; ++i) result[i] = selfProduct(centroidss[i]); return result; } private static double selfProduct(double[] xs) { double sum = 0.0; for (int i = 0; i < xs.length; ++i) sum += xs[i] * xs[i]; return sum; } private static double sum(double[] xs) { double sum = 0.0; for (int i = 0; i < xs.length; ++i) sum += xs[i]; return sum; } // x = (indexes,values); c=centroid; returns x*c private static double product(double[] centroid, int[] features, double[] values) { double sum = 0.0; for (int i = 0; i < features.length; ++i) sum += values[i] * centroid[features[i]]; return sum; } private static void setCentroid(double[] centroid, int[] indexes, double[] values) { for (int i = 0; i < indexes.length; ++i) centroid[indexes[i]] = values[i]; } private static void increment(double[] centroid, int[] indexes, double[] values) { for (int i = 0; i < indexes.length; ++i) centroid[indexes[i]] += values[i]; } }
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.subcommand; import com.google.cloud.bigquery.dwhassessment.extractiontool.db.SchemaFilter; import com.google.cloud.bigquery.dwhassessment.extractiontool.executor.ExtractExecutor; import com.google.common.collect.ImmutableList; import com.google.re2j.Pattern; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import java.util.Properties; import java.util.concurrent.Callable; import java.util.function.Supplier; import picocli.CommandLine.Command; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Option; import picocli.CommandLine.ParameterException; import picocli.CommandLine.Spec; /** Subclass for the extract action of the extraction tool. */ @Command(name = "td-extract", description = "Subcommand to extract from a Teradata data warehouse") public final class ExtractSubcommand implements Callable<Integer> { @Spec CommandSpec spec; private final Supplier<ExtractExecutor> executorSupplier; private final ExtractExecutor.Arguments.Builder argumentsBuilder = ExtractExecutor.Arguments.builder(); public ExtractSubcommand(Supplier<ExtractExecutor> executorSupplier) { this.executorSupplier = executorSupplier; } @Option( names = {"-h", "--help"}, usageHelp = true) private boolean help; @Option( names = "--db-address", required = true, description = { "JDBC address of the Teradata data warehouse.", "Example: jdbc:teradata://storage.my-animalclinic.example" }) private String dbAddress; @Option(names = "--db-user", description = "The user name for the database.") private String dbUserName = ""; @Option(names = "--db-password", description = "The password for the database.") private String dbPassword = ""; @Option( names = {"--output", "-o"}, required = true, description = "Output path to which to write the extracted information.") void setOutputPath(String pathString) { Path path = Paths.get(pathString); if (!Files.isDirectory(path)) { throw new ParameterException( spec.commandLine(), String.format("--output must specify a directory, but '%s' is not a directory.", path)); } argumentsBuilder.setOutputPath(path); } @Option( names = "--sql-scripts", split = ",\\s*", description = { "The list of scripts to execute.", "By default, all available scripts will be executed." }) void setSqlScripts(List<String> sqlScripts) { for (String sqlScript : sqlScripts) { if (sqlScript == null || "".equals(sqlScript)) { throw new ParameterException(spec.commandLine(), "SQL script names must not be blank."); } } argumentsBuilder.setSqlScripts(sqlScripts); } @Option( names = "--skip-sql-scripts", split = ",\\s*", description = { "The list of scripts to skip.", "By default, all available scripts will be executed." }) void setSkipSqlScripts(List<String> skipSqlScripts) { for (String skipSqlScript : skipSqlScripts) { if (skipSqlScript == null || "".equals(skipSqlScript)) { throw new ParameterException(spec.commandLine(), "SQL script names must not be blank."); } } argumentsBuilder.setSkipSqlScripts(skipSqlScripts); } @Option( names = "--schema-filter", description = { "The schema filter to apply when extracting schemas from the database.", "By default, all schemas will be extracted.", "Example:", " db:(abc|def),table:public_.*", " Only take schemas from tables in the database abc or def that have", " the prefix public_.", "Multiple filters can be defined by repeating the option. At least one", "filter has to match (i.e. OR logic)." }) void setSchemaFilters(List<SchemaFilter> schemaFilters) { if (schemaFilters == null | schemaFilters.isEmpty()) { argumentsBuilder.setSchemaFilters( ImmutableList.of( SchemaFilter.builder() .setTableName(Pattern.compile(".*")) .setDatabaseName(Pattern.compile(".*")) .build())); return; } argumentsBuilder.setSchemaFilters(schemaFilters); } private ExtractExecutor.Arguments getValidatedArguments() { try { DriverManager.getConnection(dbAddress, dbUserName, dbPassword); } catch (SQLException e) { throw new ParameterException( spec.commandLine(), String.format("Unable to connect to '%s': %s", dbAddress, e.getMessage()), e); } Properties connectionProperties = new Properties(); connectionProperties.put("user", dbUserName); connectionProperties.put("password", dbPassword); argumentsBuilder.setDbConnectionProperties(connectionProperties); argumentsBuilder.setDbConnectionAddress(dbAddress); ExtractExecutor.Arguments arguments = argumentsBuilder.build(); if (!arguments.sqlScripts().isEmpty() && !arguments.skipSqlScripts().isEmpty()) { throw new ParameterException( spec.commandLine(), "The options --sql-scripts and --skip-sql-scripts are mutually exclusive."); } return arguments; } @Override public Integer call() throws IOException, SQLException { return executorSupplier.get().run(getValidatedArguments()); } }
/* * 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.karaf.scr.examples.component; import java.util.Map; import org.apache.karaf.scr.examples.service.ExampleService; import org.osgi.service.log.LogService; import aQute.bnd.annotation.component.Activate; import aQute.bnd.annotation.component.Component; import aQute.bnd.annotation.component.ConfigurationPolicy; import aQute.bnd.annotation.component.Deactivate; import aQute.bnd.annotation.component.Reference; @Component(name = ManagedComponent.COMPONENT_NAME, configurationPolicy = ConfigurationPolicy.require) public class ManagedComponent { public static final String COMPONENT_NAME = "ManagedComponent"; public static final String COMPONENT_LABEL = "Example Managed Component"; private static final String COMPONENT_PROP_NAME = "name"; private static final String COMPONENT_PROP_SALUTATION = "salutation"; private LogService logService; private ExampleService exampleService; /** * Called when all of the SCR Components required dependencies have been * satisfied. */ @Activate public void activate(final Map<String, ?> properties) { logService.log(LogService.LOG_INFO, "Activating the " + COMPONENT_LABEL); exampleService.setName((String) properties.get(COMPONENT_PROP_NAME)); exampleService.setSalutation((String) properties.get(COMPONENT_PROP_SALUTATION)); exampleService.printGreetings(); } /** * Called when any of the SCR Components required dependencies become * unsatisfied. */ @Deactivate public void deactivate() { logService.log(LogService.LOG_INFO, "Deactivating the " + COMPONENT_LABEL); } @Reference public void setExampleService(final ExampleService exampleService) { this.exampleService = exampleService; } public void unsetExampleService(final ExampleService exampleService) { this.exampleService = null; } @Reference protected void setLogService(LogService logService) { this.logService = logService; } protected void unsetLogService(LogService logService) { this.logService = logService; } }
package com.slack.api.methods.request.files; import com.slack.api.methods.SlackApiRequest; import lombok.Builder; import lombok.Data; import java.util.List; /** * https://api.slack.com/methods/files.list */ @Data @Builder public class FilesListRequest implements SlackApiRequest { /** * Authentication token. Requires scope: `files:read` */ private String token; /** * Filter files created by a single user. */ private String user; /** * Filter files appearing in a specific channel, indicated by its ID. */ private String channel; /** * Filter files created after this timestamp (inclusive). */ private String tsFrom; /** * Filter files created before this timestamp (inclusive). */ private String tsTo; /** * Filter files by type:\n\n* `all` - All files * <p> * `spaces` - Posts\n* `snippets` - Snippets * `images` - Image files * `gdocs` - Google docs * `zips` - Zip files * `pdfs` - PDF files * <p> * You can pass multiple values in the types argument, like `types=spaces,snippets`. * The default value is `all`, which does not filter the list. */ private List<String> types; private Integer count; private Integer page; /** * https://api.slack.com/changelog/2019-03-wild-west-for-files-no-more * <p> * In order to gather information on tombstoned files in Free workspaces, * so that you can delete or revoke them, pass the show_files_hidden_by_limit parameter. * While the yielded files will still be redacted, * you'll gain the id of the files so that you can delete or revoke them. */ private boolean showFilesHiddenByLimit; /** * Required for org-wide apps. */ private String teamId; }
package com.bring.project.bring.common.model.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.domain.Sort; @Data @NoArgsConstructor @AllArgsConstructor public class AppPage { private int pageNo = 0; private int pageSize = 10; private String sortBy; private String sortDirection = Sort.Direction.DESC.name(); }
package com.blue_unicorn.android_auth_lib.ctap2.authenticator_api.data.webauthn; import com.google.gson.annotations.SerializedName; public class BasePublicKeyCredentialParameter implements PublicKeyCredentialParameter { @SerializedName("type") private String type; @SerializedName("alg") private int alg; public String getType() { return type; } public int getAlg() { return alg; } }
/* * Copyright 2010-2013 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.geo.model; import java.util.ArrayList; import java.util.List; import com.amazonaws.geo.GeoDataManagerConfiguration; public class GeohashRange { private long rangeMin; private long rangeMax; public GeohashRange(long range1, long range2) { this.rangeMin = Math.min(range1, range2); this.rangeMax = Math.max(range1, range2); } public boolean tryMerge(GeohashRange range) { if (range.getRangeMin() - this.rangeMax <= GeoDataManagerConfiguration.MERGE_THRESHOLD && range.getRangeMin() - this.rangeMax > 0) { this.rangeMax = range.getRangeMax(); return true; } if (this.rangeMin - range.getRangeMax() <= GeoDataManagerConfiguration.MERGE_THRESHOLD && this.rangeMin - range.getRangeMax() > 0) { this.rangeMin = range.getRangeMin(); return true; } return false; } public List<GeohashRange> trySplit(int hashKeyLength) { List<GeohashRange> result = new ArrayList<GeohashRange>(); long denominator = (long) Math.pow(10, GeoDataManagerConfiguration.GEOHASH_LENGTH - hashKeyLength); long minHashKey = (long) (rangeMin / denominator); long maxHashKey = (long) (rangeMax / denominator); if (minHashKey == maxHashKey) { result.add(this); } else { for (long l = minHashKey; l <= maxHashKey; l++) { result.add(new GeohashRange(l == minHashKey ? rangeMin : l * denominator, l == maxHashKey ? rangeMax : (l + 1) * denominator - 1)); } } return result; } public long getRangeMin() { return rangeMin; } public void setRangeMin(long rangeMin) { this.rangeMin = rangeMin; } public long getRangeMax() { return rangeMax; } public void setRangeMax(long rangeMax) { this.rangeMax = rangeMax; } }
package ru.pravvich.jdbc.actions; import ru.pravvich.jdbc.PropertiesLoader; import ru.pravvich.user.User; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Getter for all users from database. */ public class GetterAllUsers extends Action { /** * Default constructor for all actions with database. * * @param connection to database. * @param scripts which extract from properties file. */ public GetterAllUsers(Connection connection, PropertiesLoader scripts) { super(connection, scripts); } /** * Get all users which contains in database. * * @return */ public List<User> getAllUsers() { final List<User> users = new ArrayList<>(100); try (final PreparedStatement statement = connection.prepareStatement(scripts.get("get_all_users"))) { final ResultSet result = statement.executeQuery(); while (result.next()) { final User user = new User( result.getInt("id"), result.getString("username"), result.getString("login"), result.getString("password"), result.getString("email"), result.getTimestamp("create_date"), result.getString("access") ); users.add(user); } return users; } catch (SQLException e) { e.printStackTrace(); } return users; } }
/* * 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.felix.webconsole.internal.i18n; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.Properties; import java.util.ResourceBundle; import org.apache.commons.io.IOUtils; class ConsolePropertyResourceBundle extends ResourceBundle { private final Properties props; ConsolePropertyResourceBundle( final ResourceBundle parent, final URL source ) { setParent( parent ); props = new Properties(); if ( source != null ) { InputStream ins = null; try { ins = source.openStream(); props.load( ins ); } catch ( IOException ignore ) { /* ignore */ } finally { IOUtils.closeQuietly( ins ); } } } public Enumeration getKeys() { return new CombinedEnumeration( props.keys(), parent.getKeys() ); } protected Object handleGetObject( String key ) { return props.get( key ); } }
package com.stylefeng.guns.modular.system.model; import java.io.Serializable; import java.util.Date; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.activerecord.Model; import com.baomidou.mybatisplus.annotations.TableName; import java.io.Serializable; /** * <p> * * </p> * * @author stylefeng123 * @since 2019-02-18 */ @TableName("sys_file") public class File extends Model<File> { private static final long serialVersionUID = 1L; private Long id; @TableField("file_no") private String fileNo; @TableField("file_type") private String fileType; private String url; private String status; private String remarks; @TableField("create_time") private Date createTime; @TableField("modified_time") private Date modifiedTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFileNo() { return fileNo; } public void setFileNo(String fileNo) { this.fileNo = fileNo; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getModifiedTime() { return modifiedTime; } public void setModifiedTime(Date modifiedTime) { this.modifiedTime = modifiedTime; } @Override protected Serializable pkVal() { return this.id; } @Override public String toString() { return "File{" + "id=" + id + ", fileNo=" + fileNo + ", fileType=" + fileType + ", url=" + url + ", status=" + status + ", remarks=" + remarks + ", createTime=" + createTime + ", modifiedTime=" + modifiedTime + "}"; } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.dialer2.precall.impl; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.android.dialer2.callintent.CallIntentBuilder; import com.android.dialer2.common.Assert; import com.android.dialer2.common.LogUtil; import com.android.dialer2.logging.DialerImpression.Type; import com.android.dialer2.logging.Logger; import com.android.dialer2.precall.PreCallAction; import com.android.dialer2.precall.PreCallComponent; import com.android.dialer2.precall.PreCallCoordinator; import com.android.dialer2.telecom.TelecomUtil; import com.google.common.collect.ImmutableList; /** * Implements {@link PreCallCoordinator}. Listens to the life cycle of {@link PreCallActivity} to * save/restore states. */ public class PreCallCoordinatorImpl implements PreCallCoordinator { private static final String SAVED_STATE_CURRENT_ACTION = "current_action"; @NonNull private final Activity activity; private CallIntentBuilder builder; private ImmutableList<PreCallAction> actions; private int currentActionIndex = 0; private PreCallAction currentAction; private PendingAction pendingAction; private boolean aborted = false; PreCallCoordinatorImpl(@NonNull Activity activity) { this.activity = Assert.isNotNull(activity); } void onCreate(Intent intent, @Nullable Bundle savedInstanceState) { LogUtil.enterBlock("PreCallCoordinatorImpl.onCreate"); if (savedInstanceState != null) { currentActionIndex = savedInstanceState.getInt(SAVED_STATE_CURRENT_ACTION); builder = Assert.isNotNull(savedInstanceState.getParcelable(EXTRA_CALL_INTENT_BUILDER)); } else { builder = Assert.isNotNull(intent.getParcelableExtra(EXTRA_CALL_INTENT_BUILDER)); } } void onRestoreInstanceState(Bundle savedInstanceState) { currentActionIndex = savedInstanceState.getInt(SAVED_STATE_CURRENT_ACTION); builder = savedInstanceState.getParcelable(EXTRA_CALL_INTENT_BUILDER); } void onResume() { actions = PreCallComponent.get(activity).getPreCall().getActions(); runNextAction(); } void onPause() { if (currentAction != null) { currentAction.onDiscard(); } currentAction = null; pendingAction = null; } void onSaveInstanceState(Bundle outState) { outState.putInt(SAVED_STATE_CURRENT_ACTION, currentActionIndex); outState.putParcelable(EXTRA_CALL_INTENT_BUILDER, builder); } private void runNextAction() { LogUtil.enterBlock("PreCallCoordinatorImpl.runNextAction"); Assert.checkArgument(currentAction == null); if (currentActionIndex >= actions.size()) { TelecomUtil.placeCall(activity, builder.build()); activity.finish(); return; } LogUtil.i("PreCallCoordinatorImpl.runNextAction", "running " + actions.get(currentActionIndex)); currentAction = actions.get(currentActionIndex); actions.get(currentActionIndex).runWithUi(this); if (pendingAction == null) { onActionFinished(); } } private void onActionFinished() { LogUtil.enterBlock("PreCallCoordinatorImpl.onActionFinished"); Assert.isNotNull(currentAction); currentAction = null; currentActionIndex++; if (!aborted) { runNextAction(); } else { activity.finish(); } } @Override public void abortCall() { Assert.checkState(currentAction != null); aborted = true; Logger.get(getActivity()).logImpression(Type.PRECALL_CANCELED); } @NonNull @Override public CallIntentBuilder getBuilder() { return builder; } @NonNull @Override public Activity getActivity() { return activity; } @Override @NonNull public PendingAction startPendingAction() { Assert.isMainThread(); Assert.isNotNull(currentAction); Assert.checkArgument(pendingAction == null); pendingAction = new PendingActionImpl(); return pendingAction; } private class PendingActionImpl implements PendingAction { @Override public void finish() { Assert.checkArgument(pendingAction == this); pendingAction = null; onActionFinished(); } } }
package org.hl7.fhir.dstu3.model; /* Copyright (c) 2011+, HL7, Inc. 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 HL7 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 HOLDER 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. */ // Generated on Mon, Apr 17, 2017 17:38-0400 for FHIR v3.0.1 import java.util.*; import org.hl7.fhir.utilities.Utilities; import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.api.annotation.SearchParamDefinition; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.ChildOrder; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.Block; import org.hl7.fhir.instance.model.api.*; import org.hl7.fhir.exceptions.FHIRException; /** * A record of a request for a medication, substance or device used in the healthcare setting. */ @ResourceDef(name="SupplyRequest", profile="http://hl7.org/fhir/Profile/SupplyRequest") public class SupplyRequest extends DomainResource { public enum SupplyRequestStatus { /** * The request has been created but is not yet complete or ready for action */ DRAFT, /** * The request is ready to be acted upon */ ACTIVE, /** * The authorization/request to act has been temporarily withdrawn but is expected to resume in the future */ SUSPENDED, /** * The authorization/request to act has been terminated prior to the full completion of the intended actions. No further activity should occur. */ CANCELLED, /** * Activity against the request has been sufficiently completed to the satisfaction of the requester */ COMPLETED, /** * This electronic record should never have existed, though it is possible that real-world decisions were based on it. (If real-world activity has occurred, the status should be "cancelled" rather than "entered-in-error".) */ ENTEREDINERROR, /** * The authoring system does not know which of the status values currently applies for this request. Note: This concept is not to be used for "other" - one of the listed statuses is presumed to apply, it's just not known which one. */ UNKNOWN, /** * added to help the parsers with the generic types */ NULL; public static SupplyRequestStatus fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("draft".equals(codeString)) return DRAFT; if ("active".equals(codeString)) return ACTIVE; if ("suspended".equals(codeString)) return SUSPENDED; if ("cancelled".equals(codeString)) return CANCELLED; if ("completed".equals(codeString)) return COMPLETED; if ("entered-in-error".equals(codeString)) return ENTEREDINERROR; if ("unknown".equals(codeString)) return UNKNOWN; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown SupplyRequestStatus code '"+codeString+"'"); } public String toCode() { switch (this) { case DRAFT: return "draft"; case ACTIVE: return "active"; case SUSPENDED: return "suspended"; case CANCELLED: return "cancelled"; case COMPLETED: return "completed"; case ENTEREDINERROR: return "entered-in-error"; case UNKNOWN: return "unknown"; default: return "?"; } } public String getSystem() { switch (this) { case DRAFT: return "http://hl7.org/fhir/supplyrequest-status"; case ACTIVE: return "http://hl7.org/fhir/supplyrequest-status"; case SUSPENDED: return "http://hl7.org/fhir/supplyrequest-status"; case CANCELLED: return "http://hl7.org/fhir/supplyrequest-status"; case COMPLETED: return "http://hl7.org/fhir/supplyrequest-status"; case ENTEREDINERROR: return "http://hl7.org/fhir/supplyrequest-status"; case UNKNOWN: return "http://hl7.org/fhir/supplyrequest-status"; default: return "?"; } } public String getDefinition() { switch (this) { case DRAFT: return "The request has been created but is not yet complete or ready for action"; case ACTIVE: return "The request is ready to be acted upon"; case SUSPENDED: return "The authorization/request to act has been temporarily withdrawn but is expected to resume in the future"; case CANCELLED: return "The authorization/request to act has been terminated prior to the full completion of the intended actions. No further activity should occur."; case COMPLETED: return "Activity against the request has been sufficiently completed to the satisfaction of the requester"; case ENTEREDINERROR: return "This electronic record should never have existed, though it is possible that real-world decisions were based on it. (If real-world activity has occurred, the status should be \"cancelled\" rather than \"entered-in-error\".)"; case UNKNOWN: return "The authoring system does not know which of the status values currently applies for this request. Note: This concept is not to be used for \"other\" - one of the listed statuses is presumed to apply, it's just not known which one."; default: return "?"; } } public String getDisplay() { switch (this) { case DRAFT: return "Draft"; case ACTIVE: return "Active"; case SUSPENDED: return "Suspended"; case CANCELLED: return "Cancelled"; case COMPLETED: return "Completed"; case ENTEREDINERROR: return "Entered in Error"; case UNKNOWN: return "Unknown"; default: return "?"; } } } public static class SupplyRequestStatusEnumFactory implements EnumFactory<SupplyRequestStatus> { public SupplyRequestStatus fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("draft".equals(codeString)) return SupplyRequestStatus.DRAFT; if ("active".equals(codeString)) return SupplyRequestStatus.ACTIVE; if ("suspended".equals(codeString)) return SupplyRequestStatus.SUSPENDED; if ("cancelled".equals(codeString)) return SupplyRequestStatus.CANCELLED; if ("completed".equals(codeString)) return SupplyRequestStatus.COMPLETED; if ("entered-in-error".equals(codeString)) return SupplyRequestStatus.ENTEREDINERROR; if ("unknown".equals(codeString)) return SupplyRequestStatus.UNKNOWN; throw new IllegalArgumentException("Unknown SupplyRequestStatus code '"+codeString+"'"); } public Enumeration<SupplyRequestStatus> fromType(Base code) throws FHIRException { if (code == null) return null; if (code.isEmpty()) return new Enumeration<SupplyRequestStatus>(this); String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("draft".equals(codeString)) return new Enumeration<SupplyRequestStatus>(this, SupplyRequestStatus.DRAFT); if ("active".equals(codeString)) return new Enumeration<SupplyRequestStatus>(this, SupplyRequestStatus.ACTIVE); if ("suspended".equals(codeString)) return new Enumeration<SupplyRequestStatus>(this, SupplyRequestStatus.SUSPENDED); if ("cancelled".equals(codeString)) return new Enumeration<SupplyRequestStatus>(this, SupplyRequestStatus.CANCELLED); if ("completed".equals(codeString)) return new Enumeration<SupplyRequestStatus>(this, SupplyRequestStatus.COMPLETED); if ("entered-in-error".equals(codeString)) return new Enumeration<SupplyRequestStatus>(this, SupplyRequestStatus.ENTEREDINERROR); if ("unknown".equals(codeString)) return new Enumeration<SupplyRequestStatus>(this, SupplyRequestStatus.UNKNOWN); throw new FHIRException("Unknown SupplyRequestStatus code '"+codeString+"'"); } public String toCode(SupplyRequestStatus code) { if (code == SupplyRequestStatus.DRAFT) return "draft"; if (code == SupplyRequestStatus.ACTIVE) return "active"; if (code == SupplyRequestStatus.SUSPENDED) return "suspended"; if (code == SupplyRequestStatus.CANCELLED) return "cancelled"; if (code == SupplyRequestStatus.COMPLETED) return "completed"; if (code == SupplyRequestStatus.ENTEREDINERROR) return "entered-in-error"; if (code == SupplyRequestStatus.UNKNOWN) return "unknown"; return "?"; } public String toSystem(SupplyRequestStatus code) { return code.getSystem(); } } public enum RequestPriority { /** * The request has normal priority */ ROUTINE, /** * The request should be actioned promptly - higher priority than routine */ URGENT, /** * The request should be actioned as soon as possible - higher priority than urgent */ ASAP, /** * The request should be actioned immediately - highest possible priority. E.g. an emergency */ STAT, /** * added to help the parsers with the generic types */ NULL; public static RequestPriority fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("routine".equals(codeString)) return ROUTINE; if ("urgent".equals(codeString)) return URGENT; if ("asap".equals(codeString)) return ASAP; if ("stat".equals(codeString)) return STAT; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown RequestPriority code '"+codeString+"'"); } public String toCode() { switch (this) { case ROUTINE: return "routine"; case URGENT: return "urgent"; case ASAP: return "asap"; case STAT: return "stat"; default: return "?"; } } public String getSystem() { switch (this) { case ROUTINE: return "http://hl7.org/fhir/request-priority"; case URGENT: return "http://hl7.org/fhir/request-priority"; case ASAP: return "http://hl7.org/fhir/request-priority"; case STAT: return "http://hl7.org/fhir/request-priority"; default: return "?"; } } public String getDefinition() { switch (this) { case ROUTINE: return "The request has normal priority"; case URGENT: return "The request should be actioned promptly - higher priority than routine"; case ASAP: return "The request should be actioned as soon as possible - higher priority than urgent"; case STAT: return "The request should be actioned immediately - highest possible priority. E.g. an emergency"; default: return "?"; } } public String getDisplay() { switch (this) { case ROUTINE: return "Routine"; case URGENT: return "Urgent"; case ASAP: return "ASAP"; case STAT: return "STAT"; default: return "?"; } } } public static class RequestPriorityEnumFactory implements EnumFactory<RequestPriority> { public RequestPriority fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("routine".equals(codeString)) return RequestPriority.ROUTINE; if ("urgent".equals(codeString)) return RequestPriority.URGENT; if ("asap".equals(codeString)) return RequestPriority.ASAP; if ("stat".equals(codeString)) return RequestPriority.STAT; throw new IllegalArgumentException("Unknown RequestPriority code '"+codeString+"'"); } public Enumeration<RequestPriority> fromType(Base code) throws FHIRException { if (code == null) return null; if (code.isEmpty()) return new Enumeration<RequestPriority>(this); String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("routine".equals(codeString)) return new Enumeration<RequestPriority>(this, RequestPriority.ROUTINE); if ("urgent".equals(codeString)) return new Enumeration<RequestPriority>(this, RequestPriority.URGENT); if ("asap".equals(codeString)) return new Enumeration<RequestPriority>(this, RequestPriority.ASAP); if ("stat".equals(codeString)) return new Enumeration<RequestPriority>(this, RequestPriority.STAT); throw new FHIRException("Unknown RequestPriority code '"+codeString+"'"); } public String toCode(RequestPriority code) { if (code == RequestPriority.ROUTINE) return "routine"; if (code == RequestPriority.URGENT) return "urgent"; if (code == RequestPriority.ASAP) return "asap"; if (code == RequestPriority.STAT) return "stat"; return "?"; } public String toSystem(RequestPriority code) { return code.getSystem(); } } @Block() public static class SupplyRequestOrderedItemComponent extends BackboneElement implements IBaseBackboneElement { /** * The amount that is being ordered of the indicated item. */ @Child(name = "quantity", type = {Quantity.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="The requested amount of the item indicated", formalDefinition="The amount that is being ordered of the indicated item." ) protected Quantity quantity; /** * The item that is requested to be supplied. This is either a link to a resource representing the details of the item or a code that identifies the item from a known list. */ @Child(name = "item", type = {CodeableConcept.class, Medication.class, Substance.class, Device.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Medication, Substance, or Device requested to be supplied", formalDefinition="The item that is requested to be supplied. This is either a link to a resource representing the details of the item or a code that identifies the item from a known list." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/supply-item") protected Type item; private static final long serialVersionUID = 1628109307L; /** * Constructor */ public SupplyRequestOrderedItemComponent() { super(); } /** * Constructor */ public SupplyRequestOrderedItemComponent(Quantity quantity) { super(); this.quantity = quantity; } /** * @return {@link #quantity} (The amount that is being ordered of the indicated item.) */ public Quantity getQuantity() { if (this.quantity == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequestOrderedItemComponent.quantity"); else if (Configuration.doAutoCreate()) this.quantity = new Quantity(); // cc return this.quantity; } public boolean hasQuantity() { return this.quantity != null && !this.quantity.isEmpty(); } /** * @param value {@link #quantity} (The amount that is being ordered of the indicated item.) */ public SupplyRequestOrderedItemComponent setQuantity(Quantity value) { this.quantity = value; return this; } /** * @return {@link #item} (The item that is requested to be supplied. This is either a link to a resource representing the details of the item or a code that identifies the item from a known list.) */ public Type getItem() { return this.item; } /** * @return {@link #item} (The item that is requested to be supplied. This is either a link to a resource representing the details of the item or a code that identifies the item from a known list.) */ public CodeableConcept getItemCodeableConcept() throws FHIRException { if (!(this.item instanceof CodeableConcept)) throw new FHIRException("Type mismatch: the type CodeableConcept was expected, but "+this.item.getClass().getName()+" was encountered"); return (CodeableConcept) this.item; } public boolean hasItemCodeableConcept() { return this.item instanceof CodeableConcept; } /** * @return {@link #item} (The item that is requested to be supplied. This is either a link to a resource representing the details of the item or a code that identifies the item from a known list.) */ public Reference getItemReference() throws FHIRException { if (!(this.item instanceof Reference)) throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.item.getClass().getName()+" was encountered"); return (Reference) this.item; } public boolean hasItemReference() { return this.item instanceof Reference; } public boolean hasItem() { return this.item != null && !this.item.isEmpty(); } /** * @param value {@link #item} (The item that is requested to be supplied. This is either a link to a resource representing the details of the item or a code that identifies the item from a known list.) */ public SupplyRequestOrderedItemComponent setItem(Type value) { this.item = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("quantity", "Quantity", "The amount that is being ordered of the indicated item.", 0, java.lang.Integer.MAX_VALUE, quantity)); childrenList.add(new Property("item[x]", "CodeableConcept|Reference(Medication|Substance|Device)", "The item that is requested to be supplied. This is either a link to a resource representing the details of the item or a code that identifies the item from a known list.", 0, java.lang.Integer.MAX_VALUE, item)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1285004149: /*quantity*/ return this.quantity == null ? new Base[0] : new Base[] {this.quantity}; // Quantity case 3242771: /*item*/ return this.item == null ? new Base[0] : new Base[] {this.item}; // Type default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1285004149: // quantity this.quantity = castToQuantity(value); // Quantity return value; case 3242771: // item this.item = castToType(value); // Type return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("quantity")) { this.quantity = castToQuantity(value); // Quantity } else if (name.equals("item[x]")) { this.item = castToType(value); // Type } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1285004149: return getQuantity(); case 2116201613: return getItem(); case 3242771: return getItem(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case -1285004149: /*quantity*/ return new String[] {"Quantity"}; case 3242771: /*item*/ return new String[] {"CodeableConcept", "Reference"}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("quantity")) { this.quantity = new Quantity(); return this.quantity; } else if (name.equals("itemCodeableConcept")) { this.item = new CodeableConcept(); return this.item; } else if (name.equals("itemReference")) { this.item = new Reference(); return this.item; } else return super.addChild(name); } public SupplyRequestOrderedItemComponent copy() { SupplyRequestOrderedItemComponent dst = new SupplyRequestOrderedItemComponent(); copyValues(dst); dst.quantity = quantity == null ? null : quantity.copy(); dst.item = item == null ? null : item.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof SupplyRequestOrderedItemComponent)) return false; SupplyRequestOrderedItemComponent o = (SupplyRequestOrderedItemComponent) other; return compareDeep(quantity, o.quantity, true) && compareDeep(item, o.item, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof SupplyRequestOrderedItemComponent)) return false; SupplyRequestOrderedItemComponent o = (SupplyRequestOrderedItemComponent) other; return true; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(quantity, item); } public String fhirType() { return "SupplyRequest.orderedItem"; } } @Block() public static class SupplyRequestRequesterComponent extends BackboneElement implements IBaseBackboneElement { /** * The device, practitioner, etc. who initiated the request. */ @Child(name = "agent", type = {Practitioner.class, Organization.class, Patient.class, RelatedPerson.class, Device.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Individual making the request", formalDefinition="The device, practitioner, etc. who initiated the request." ) protected Reference agent; /** * The actual object that is the target of the reference (The device, practitioner, etc. who initiated the request.) */ protected Resource agentTarget; /** * The organization the device or practitioner was acting on behalf of. */ @Child(name = "onBehalfOf", type = {Organization.class}, order=2, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Organization agent is acting for", formalDefinition="The organization the device or practitioner was acting on behalf of." ) protected Reference onBehalfOf; /** * The actual object that is the target of the reference (The organization the device or practitioner was acting on behalf of.) */ protected Organization onBehalfOfTarget; private static final long serialVersionUID = -71453027L; /** * Constructor */ public SupplyRequestRequesterComponent() { super(); } /** * Constructor */ public SupplyRequestRequesterComponent(Reference agent) { super(); this.agent = agent; } /** * @return {@link #agent} (The device, practitioner, etc. who initiated the request.) */ public Reference getAgent() { if (this.agent == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequestRequesterComponent.agent"); else if (Configuration.doAutoCreate()) this.agent = new Reference(); // cc return this.agent; } public boolean hasAgent() { return this.agent != null && !this.agent.isEmpty(); } /** * @param value {@link #agent} (The device, practitioner, etc. who initiated the request.) */ public SupplyRequestRequesterComponent setAgent(Reference value) { this.agent = value; return this; } /** * @return {@link #agent} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The device, practitioner, etc. who initiated the request.) */ public Resource getAgentTarget() { return this.agentTarget; } /** * @param value {@link #agent} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The device, practitioner, etc. who initiated the request.) */ public SupplyRequestRequesterComponent setAgentTarget(Resource value) { this.agentTarget = value; return this; } /** * @return {@link #onBehalfOf} (The organization the device or practitioner was acting on behalf of.) */ public Reference getOnBehalfOf() { if (this.onBehalfOf == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequestRequesterComponent.onBehalfOf"); else if (Configuration.doAutoCreate()) this.onBehalfOf = new Reference(); // cc return this.onBehalfOf; } public boolean hasOnBehalfOf() { return this.onBehalfOf != null && !this.onBehalfOf.isEmpty(); } /** * @param value {@link #onBehalfOf} (The organization the device or practitioner was acting on behalf of.) */ public SupplyRequestRequesterComponent setOnBehalfOf(Reference value) { this.onBehalfOf = value; return this; } /** * @return {@link #onBehalfOf} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The organization the device or practitioner was acting on behalf of.) */ public Organization getOnBehalfOfTarget() { if (this.onBehalfOfTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequestRequesterComponent.onBehalfOf"); else if (Configuration.doAutoCreate()) this.onBehalfOfTarget = new Organization(); // aa return this.onBehalfOfTarget; } /** * @param value {@link #onBehalfOf} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The organization the device or practitioner was acting on behalf of.) */ public SupplyRequestRequesterComponent setOnBehalfOfTarget(Organization value) { this.onBehalfOfTarget = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("agent", "Reference(Practitioner|Organization|Patient|RelatedPerson|Device)", "The device, practitioner, etc. who initiated the request.", 0, java.lang.Integer.MAX_VALUE, agent)); childrenList.add(new Property("onBehalfOf", "Reference(Organization)", "The organization the device or practitioner was acting on behalf of.", 0, java.lang.Integer.MAX_VALUE, onBehalfOf)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case 92750597: /*agent*/ return this.agent == null ? new Base[0] : new Base[] {this.agent}; // Reference case -14402964: /*onBehalfOf*/ return this.onBehalfOf == null ? new Base[0] : new Base[] {this.onBehalfOf}; // Reference default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case 92750597: // agent this.agent = castToReference(value); // Reference return value; case -14402964: // onBehalfOf this.onBehalfOf = castToReference(value); // Reference return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("agent")) { this.agent = castToReference(value); // Reference } else if (name.equals("onBehalfOf")) { this.onBehalfOf = castToReference(value); // Reference } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case 92750597: return getAgent(); case -14402964: return getOnBehalfOf(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case 92750597: /*agent*/ return new String[] {"Reference"}; case -14402964: /*onBehalfOf*/ return new String[] {"Reference"}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("agent")) { this.agent = new Reference(); return this.agent; } else if (name.equals("onBehalfOf")) { this.onBehalfOf = new Reference(); return this.onBehalfOf; } else return super.addChild(name); } public SupplyRequestRequesterComponent copy() { SupplyRequestRequesterComponent dst = new SupplyRequestRequesterComponent(); copyValues(dst); dst.agent = agent == null ? null : agent.copy(); dst.onBehalfOf = onBehalfOf == null ? null : onBehalfOf.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof SupplyRequestRequesterComponent)) return false; SupplyRequestRequesterComponent o = (SupplyRequestRequesterComponent) other; return compareDeep(agent, o.agent, true) && compareDeep(onBehalfOf, o.onBehalfOf, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof SupplyRequestRequesterComponent)) return false; SupplyRequestRequesterComponent o = (SupplyRequestRequesterComponent) other; return true; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(agent, onBehalfOf); } public String fhirType() { return "SupplyRequest.requester"; } } /** * Unique identifier for this supply request. */ @Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Unique identifier", formalDefinition="Unique identifier for this supply request." ) protected Identifier identifier; /** * Status of the supply request. */ @Child(name = "status", type = {CodeType.class}, order=1, min=0, max=1, modifier=true, summary=true) @Description(shortDefinition="draft | active | suspended +", formalDefinition="Status of the supply request." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/supplyrequest-status") protected Enumeration<SupplyRequestStatus> status; /** * Category of supply, e.g. central, non-stock, etc. This is used to support work flows associated with the supply process. */ @Child(name = "category", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="The kind of supply (central, non-stock, etc.)", formalDefinition="Category of supply, e.g. central, non-stock, etc. This is used to support work flows associated with the supply process." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/supplyrequest-kind") protected CodeableConcept category; /** * Indicates how quickly this SupplyRequest should be addressed with respect to other requests. */ @Child(name = "priority", type = {CodeType.class}, order=3, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="routine | urgent | asap | stat", formalDefinition="Indicates how quickly this SupplyRequest should be addressed with respect to other requests." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/request-priority") protected Enumeration<RequestPriority> priority; /** * The item being requested. */ @Child(name = "orderedItem", type = {}, order=4, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="The item being requested", formalDefinition="The item being requested." ) protected SupplyRequestOrderedItemComponent orderedItem; /** * When the request should be fulfilled. */ @Child(name = "occurrence", type = {DateTimeType.class, Period.class, Timing.class}, order=5, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="When the request should be fulfilled", formalDefinition="When the request should be fulfilled." ) protected Type occurrence; /** * When the request was made. */ @Child(name = "authoredOn", type = {DateTimeType.class}, order=6, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="When the request was made", formalDefinition="When the request was made." ) protected DateTimeType authoredOn; /** * The individual who initiated the request and has responsibility for its activation. */ @Child(name = "requester", type = {}, order=7, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Who/what is requesting service", formalDefinition="The individual who initiated the request and has responsibility for its activation." ) protected SupplyRequestRequesterComponent requester; /** * Who is intended to fulfill the request. */ @Child(name = "supplier", type = {Organization.class}, order=8, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Who is intended to fulfill the request", formalDefinition="Who is intended to fulfill the request." ) protected List<Reference> supplier; /** * The actual objects that are the target of the reference (Who is intended to fulfill the request.) */ protected List<Organization> supplierTarget; /** * Why the supply item was requested. */ @Child(name = "reason", type = {CodeableConcept.class, Reference.class}, order=9, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Why the supply item was requested", formalDefinition="Why the supply item was requested." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/supplyrequest-reason") protected Type reason; /** * Where the supply is expected to come from. */ @Child(name = "deliverFrom", type = {Organization.class, Location.class}, order=10, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="The origin of the supply", formalDefinition="Where the supply is expected to come from." ) protected Reference deliverFrom; /** * The actual object that is the target of the reference (Where the supply is expected to come from.) */ protected Resource deliverFromTarget; /** * Where the supply is destined to go. */ @Child(name = "deliverTo", type = {Organization.class, Location.class, Patient.class}, order=11, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="The destination of the supply", formalDefinition="Where the supply is destined to go." ) protected Reference deliverTo; /** * The actual object that is the target of the reference (Where the supply is destined to go.) */ protected Resource deliverToTarget; private static final long serialVersionUID = 43957782L; /** * Constructor */ public SupplyRequest() { super(); } /** * @return {@link #identifier} (Unique identifier for this supply request.) */ public Identifier getIdentifier() { if (this.identifier == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.identifier"); else if (Configuration.doAutoCreate()) this.identifier = new Identifier(); // cc return this.identifier; } public boolean hasIdentifier() { return this.identifier != null && !this.identifier.isEmpty(); } /** * @param value {@link #identifier} (Unique identifier for this supply request.) */ public SupplyRequest setIdentifier(Identifier value) { this.identifier = value; return this; } /** * @return {@link #status} (Status of the supply request.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public Enumeration<SupplyRequestStatus> getStatusElement() { if (this.status == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.status"); else if (Configuration.doAutoCreate()) this.status = new Enumeration<SupplyRequestStatus>(new SupplyRequestStatusEnumFactory()); // bb return this.status; } public boolean hasStatusElement() { return this.status != null && !this.status.isEmpty(); } public boolean hasStatus() { return this.status != null && !this.status.isEmpty(); } /** * @param value {@link #status} (Status of the supply request.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value */ public SupplyRequest setStatusElement(Enumeration<SupplyRequestStatus> value) { this.status = value; return this; } /** * @return Status of the supply request. */ public SupplyRequestStatus getStatus() { return this.status == null ? null : this.status.getValue(); } /** * @param value Status of the supply request. */ public SupplyRequest setStatus(SupplyRequestStatus value) { if (value == null) this.status = null; else { if (this.status == null) this.status = new Enumeration<SupplyRequestStatus>(new SupplyRequestStatusEnumFactory()); this.status.setValue(value); } return this; } /** * @return {@link #category} (Category of supply, e.g. central, non-stock, etc. This is used to support work flows associated with the supply process.) */ public CodeableConcept getCategory() { if (this.category == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.category"); else if (Configuration.doAutoCreate()) this.category = new CodeableConcept(); // cc return this.category; } public boolean hasCategory() { return this.category != null && !this.category.isEmpty(); } /** * @param value {@link #category} (Category of supply, e.g. central, non-stock, etc. This is used to support work flows associated with the supply process.) */ public SupplyRequest setCategory(CodeableConcept value) { this.category = value; return this; } /** * @return {@link #priority} (Indicates how quickly this SupplyRequest should be addressed with respect to other requests.). This is the underlying object with id, value and extensions. The accessor "getPriority" gives direct access to the value */ public Enumeration<RequestPriority> getPriorityElement() { if (this.priority == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.priority"); else if (Configuration.doAutoCreate()) this.priority = new Enumeration<RequestPriority>(new RequestPriorityEnumFactory()); // bb return this.priority; } public boolean hasPriorityElement() { return this.priority != null && !this.priority.isEmpty(); } public boolean hasPriority() { return this.priority != null && !this.priority.isEmpty(); } /** * @param value {@link #priority} (Indicates how quickly this SupplyRequest should be addressed with respect to other requests.). This is the underlying object with id, value and extensions. The accessor "getPriority" gives direct access to the value */ public SupplyRequest setPriorityElement(Enumeration<RequestPriority> value) { this.priority = value; return this; } /** * @return Indicates how quickly this SupplyRequest should be addressed with respect to other requests. */ public RequestPriority getPriority() { return this.priority == null ? null : this.priority.getValue(); } /** * @param value Indicates how quickly this SupplyRequest should be addressed with respect to other requests. */ public SupplyRequest setPriority(RequestPriority value) { if (value == null) this.priority = null; else { if (this.priority == null) this.priority = new Enumeration<RequestPriority>(new RequestPriorityEnumFactory()); this.priority.setValue(value); } return this; } /** * @return {@link #orderedItem} (The item being requested.) */ public SupplyRequestOrderedItemComponent getOrderedItem() { if (this.orderedItem == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.orderedItem"); else if (Configuration.doAutoCreate()) this.orderedItem = new SupplyRequestOrderedItemComponent(); // cc return this.orderedItem; } public boolean hasOrderedItem() { return this.orderedItem != null && !this.orderedItem.isEmpty(); } /** * @param value {@link #orderedItem} (The item being requested.) */ public SupplyRequest setOrderedItem(SupplyRequestOrderedItemComponent value) { this.orderedItem = value; return this; } /** * @return {@link #occurrence} (When the request should be fulfilled.) */ public Type getOccurrence() { return this.occurrence; } /** * @return {@link #occurrence} (When the request should be fulfilled.) */ public DateTimeType getOccurrenceDateTimeType() throws FHIRException { if (!(this.occurrence instanceof DateTimeType)) throw new FHIRException("Type mismatch: the type DateTimeType was expected, but "+this.occurrence.getClass().getName()+" was encountered"); return (DateTimeType) this.occurrence; } public boolean hasOccurrenceDateTimeType() { return this.occurrence instanceof DateTimeType; } /** * @return {@link #occurrence} (When the request should be fulfilled.) */ public Period getOccurrencePeriod() throws FHIRException { if (!(this.occurrence instanceof Period)) throw new FHIRException("Type mismatch: the type Period was expected, but "+this.occurrence.getClass().getName()+" was encountered"); return (Period) this.occurrence; } public boolean hasOccurrencePeriod() { return this.occurrence instanceof Period; } /** * @return {@link #occurrence} (When the request should be fulfilled.) */ public Timing getOccurrenceTiming() throws FHIRException { if (!(this.occurrence instanceof Timing)) throw new FHIRException("Type mismatch: the type Timing was expected, but "+this.occurrence.getClass().getName()+" was encountered"); return (Timing) this.occurrence; } public boolean hasOccurrenceTiming() { return this.occurrence instanceof Timing; } public boolean hasOccurrence() { return this.occurrence != null && !this.occurrence.isEmpty(); } /** * @param value {@link #occurrence} (When the request should be fulfilled.) */ public SupplyRequest setOccurrence(Type value) { this.occurrence = value; return this; } /** * @return {@link #authoredOn} (When the request was made.). This is the underlying object with id, value and extensions. The accessor "getAuthoredOn" gives direct access to the value */ public DateTimeType getAuthoredOnElement() { if (this.authoredOn == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.authoredOn"); else if (Configuration.doAutoCreate()) this.authoredOn = new DateTimeType(); // bb return this.authoredOn; } public boolean hasAuthoredOnElement() { return this.authoredOn != null && !this.authoredOn.isEmpty(); } public boolean hasAuthoredOn() { return this.authoredOn != null && !this.authoredOn.isEmpty(); } /** * @param value {@link #authoredOn} (When the request was made.). This is the underlying object with id, value and extensions. The accessor "getAuthoredOn" gives direct access to the value */ public SupplyRequest setAuthoredOnElement(DateTimeType value) { this.authoredOn = value; return this; } /** * @return When the request was made. */ public Date getAuthoredOn() { return this.authoredOn == null ? null : this.authoredOn.getValue(); } /** * @param value When the request was made. */ public SupplyRequest setAuthoredOn(Date value) { if (value == null) this.authoredOn = null; else { if (this.authoredOn == null) this.authoredOn = new DateTimeType(); this.authoredOn.setValue(value); } return this; } /** * @return {@link #requester} (The individual who initiated the request and has responsibility for its activation.) */ public SupplyRequestRequesterComponent getRequester() { if (this.requester == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.requester"); else if (Configuration.doAutoCreate()) this.requester = new SupplyRequestRequesterComponent(); // cc return this.requester; } public boolean hasRequester() { return this.requester != null && !this.requester.isEmpty(); } /** * @param value {@link #requester} (The individual who initiated the request and has responsibility for its activation.) */ public SupplyRequest setRequester(SupplyRequestRequesterComponent value) { this.requester = value; return this; } /** * @return {@link #supplier} (Who is intended to fulfill the request.) */ public List<Reference> getSupplier() { if (this.supplier == null) this.supplier = new ArrayList<Reference>(); return this.supplier; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public SupplyRequest setSupplier(List<Reference> theSupplier) { this.supplier = theSupplier; return this; } public boolean hasSupplier() { if (this.supplier == null) return false; for (Reference item : this.supplier) if (!item.isEmpty()) return true; return false; } public Reference addSupplier() { //3 Reference t = new Reference(); if (this.supplier == null) this.supplier = new ArrayList<Reference>(); this.supplier.add(t); return t; } public SupplyRequest addSupplier(Reference t) { //3 if (t == null) return this; if (this.supplier == null) this.supplier = new ArrayList<Reference>(); this.supplier.add(t); return this; } /** * @return The first repetition of repeating field {@link #supplier}, creating it if it does not already exist */ public Reference getSupplierFirstRep() { if (getSupplier().isEmpty()) { addSupplier(); } return getSupplier().get(0); } /** * @deprecated Use Reference#setResource(IBaseResource) instead */ @Deprecated public List<Organization> getSupplierTarget() { if (this.supplierTarget == null) this.supplierTarget = new ArrayList<Organization>(); return this.supplierTarget; } /** * @deprecated Use Reference#setResource(IBaseResource) instead */ @Deprecated public Organization addSupplierTarget() { Organization r = new Organization(); if (this.supplierTarget == null) this.supplierTarget = new ArrayList<Organization>(); this.supplierTarget.add(r); return r; } /** * @return {@link #reason} (Why the supply item was requested.) */ public Type getReason() { return this.reason; } /** * @return {@link #reason} (Why the supply item was requested.) */ public CodeableConcept getReasonCodeableConcept() throws FHIRException { if (!(this.reason instanceof CodeableConcept)) throw new FHIRException("Type mismatch: the type CodeableConcept was expected, but "+this.reason.getClass().getName()+" was encountered"); return (CodeableConcept) this.reason; } public boolean hasReasonCodeableConcept() { return this.reason instanceof CodeableConcept; } /** * @return {@link #reason} (Why the supply item was requested.) */ public Reference getReasonReference() throws FHIRException { if (!(this.reason instanceof Reference)) throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.reason.getClass().getName()+" was encountered"); return (Reference) this.reason; } public boolean hasReasonReference() { return this.reason instanceof Reference; } public boolean hasReason() { return this.reason != null && !this.reason.isEmpty(); } /** * @param value {@link #reason} (Why the supply item was requested.) */ public SupplyRequest setReason(Type value) { this.reason = value; return this; } /** * @return {@link #deliverFrom} (Where the supply is expected to come from.) */ public Reference getDeliverFrom() { if (this.deliverFrom == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.deliverFrom"); else if (Configuration.doAutoCreate()) this.deliverFrom = new Reference(); // cc return this.deliverFrom; } public boolean hasDeliverFrom() { return this.deliverFrom != null && !this.deliverFrom.isEmpty(); } /** * @param value {@link #deliverFrom} (Where the supply is expected to come from.) */ public SupplyRequest setDeliverFrom(Reference value) { this.deliverFrom = value; return this; } /** * @return {@link #deliverFrom} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Where the supply is expected to come from.) */ public Resource getDeliverFromTarget() { return this.deliverFromTarget; } /** * @param value {@link #deliverFrom} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Where the supply is expected to come from.) */ public SupplyRequest setDeliverFromTarget(Resource value) { this.deliverFromTarget = value; return this; } /** * @return {@link #deliverTo} (Where the supply is destined to go.) */ public Reference getDeliverTo() { if (this.deliverTo == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create SupplyRequest.deliverTo"); else if (Configuration.doAutoCreate()) this.deliverTo = new Reference(); // cc return this.deliverTo; } public boolean hasDeliverTo() { return this.deliverTo != null && !this.deliverTo.isEmpty(); } /** * @param value {@link #deliverTo} (Where the supply is destined to go.) */ public SupplyRequest setDeliverTo(Reference value) { this.deliverTo = value; return this; } /** * @return {@link #deliverTo} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Where the supply is destined to go.) */ public Resource getDeliverToTarget() { return this.deliverToTarget; } /** * @param value {@link #deliverTo} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Where the supply is destined to go.) */ public SupplyRequest setDeliverToTarget(Resource value) { this.deliverToTarget = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "Identifier", "Unique identifier for this supply request.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("status", "code", "Status of the supply request.", 0, java.lang.Integer.MAX_VALUE, status)); childrenList.add(new Property("category", "CodeableConcept", "Category of supply, e.g. central, non-stock, etc. This is used to support work flows associated with the supply process.", 0, java.lang.Integer.MAX_VALUE, category)); childrenList.add(new Property("priority", "code", "Indicates how quickly this SupplyRequest should be addressed with respect to other requests.", 0, java.lang.Integer.MAX_VALUE, priority)); childrenList.add(new Property("orderedItem", "", "The item being requested.", 0, java.lang.Integer.MAX_VALUE, orderedItem)); childrenList.add(new Property("occurrence[x]", "dateTime|Period|Timing", "When the request should be fulfilled.", 0, java.lang.Integer.MAX_VALUE, occurrence)); childrenList.add(new Property("authoredOn", "dateTime", "When the request was made.", 0, java.lang.Integer.MAX_VALUE, authoredOn)); childrenList.add(new Property("requester", "", "The individual who initiated the request and has responsibility for its activation.", 0, java.lang.Integer.MAX_VALUE, requester)); childrenList.add(new Property("supplier", "Reference(Organization)", "Who is intended to fulfill the request.", 0, java.lang.Integer.MAX_VALUE, supplier)); childrenList.add(new Property("reason[x]", "CodeableConcept|Reference(Any)", "Why the supply item was requested.", 0, java.lang.Integer.MAX_VALUE, reason)); childrenList.add(new Property("deliverFrom", "Reference(Organization|Location)", "Where the supply is expected to come from.", 0, java.lang.Integer.MAX_VALUE, deliverFrom)); childrenList.add(new Property("deliverTo", "Reference(Organization|Location|Patient)", "Where the supply is destined to go.", 0, java.lang.Integer.MAX_VALUE, deliverTo)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : new Base[] {this.identifier}; // Identifier case -892481550: /*status*/ return this.status == null ? new Base[0] : new Base[] {this.status}; // Enumeration<SupplyRequestStatus> case 50511102: /*category*/ return this.category == null ? new Base[0] : new Base[] {this.category}; // CodeableConcept case -1165461084: /*priority*/ return this.priority == null ? new Base[0] : new Base[] {this.priority}; // Enumeration<RequestPriority> case 2129914144: /*orderedItem*/ return this.orderedItem == null ? new Base[0] : new Base[] {this.orderedItem}; // SupplyRequestOrderedItemComponent case 1687874001: /*occurrence*/ return this.occurrence == null ? new Base[0] : new Base[] {this.occurrence}; // Type case -1500852503: /*authoredOn*/ return this.authoredOn == null ? new Base[0] : new Base[] {this.authoredOn}; // DateTimeType case 693933948: /*requester*/ return this.requester == null ? new Base[0] : new Base[] {this.requester}; // SupplyRequestRequesterComponent case -1663305268: /*supplier*/ return this.supplier == null ? new Base[0] : this.supplier.toArray(new Base[this.supplier.size()]); // Reference case -934964668: /*reason*/ return this.reason == null ? new Base[0] : new Base[] {this.reason}; // Type case -949323153: /*deliverFrom*/ return this.deliverFrom == null ? new Base[0] : new Base[] {this.deliverFrom}; // Reference case -242327936: /*deliverTo*/ return this.deliverTo == null ? new Base[0] : new Base[] {this.deliverTo}; // Reference default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1618432855: // identifier this.identifier = castToIdentifier(value); // Identifier return value; case -892481550: // status value = new SupplyRequestStatusEnumFactory().fromType(castToCode(value)); this.status = (Enumeration) value; // Enumeration<SupplyRequestStatus> return value; case 50511102: // category this.category = castToCodeableConcept(value); // CodeableConcept return value; case -1165461084: // priority value = new RequestPriorityEnumFactory().fromType(castToCode(value)); this.priority = (Enumeration) value; // Enumeration<RequestPriority> return value; case 2129914144: // orderedItem this.orderedItem = (SupplyRequestOrderedItemComponent) value; // SupplyRequestOrderedItemComponent return value; case 1687874001: // occurrence this.occurrence = castToType(value); // Type return value; case -1500852503: // authoredOn this.authoredOn = castToDateTime(value); // DateTimeType return value; case 693933948: // requester this.requester = (SupplyRequestRequesterComponent) value; // SupplyRequestRequesterComponent return value; case -1663305268: // supplier this.getSupplier().add(castToReference(value)); // Reference return value; case -934964668: // reason this.reason = castToType(value); // Type return value; case -949323153: // deliverFrom this.deliverFrom = castToReference(value); // Reference return value; case -242327936: // deliverTo this.deliverTo = castToReference(value); // Reference return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("identifier")) { this.identifier = castToIdentifier(value); // Identifier } else if (name.equals("status")) { value = new SupplyRequestStatusEnumFactory().fromType(castToCode(value)); this.status = (Enumeration) value; // Enumeration<SupplyRequestStatus> } else if (name.equals("category")) { this.category = castToCodeableConcept(value); // CodeableConcept } else if (name.equals("priority")) { value = new RequestPriorityEnumFactory().fromType(castToCode(value)); this.priority = (Enumeration) value; // Enumeration<RequestPriority> } else if (name.equals("orderedItem")) { this.orderedItem = (SupplyRequestOrderedItemComponent) value; // SupplyRequestOrderedItemComponent } else if (name.equals("occurrence[x]")) { this.occurrence = castToType(value); // Type } else if (name.equals("authoredOn")) { this.authoredOn = castToDateTime(value); // DateTimeType } else if (name.equals("requester")) { this.requester = (SupplyRequestRequesterComponent) value; // SupplyRequestRequesterComponent } else if (name.equals("supplier")) { this.getSupplier().add(castToReference(value)); } else if (name.equals("reason[x]")) { this.reason = castToType(value); // Type } else if (name.equals("deliverFrom")) { this.deliverFrom = castToReference(value); // Reference } else if (name.equals("deliverTo")) { this.deliverTo = castToReference(value); // Reference } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: return getIdentifier(); case -892481550: return getStatusElement(); case 50511102: return getCategory(); case -1165461084: return getPriorityElement(); case 2129914144: return getOrderedItem(); case -2022646513: return getOccurrence(); case 1687874001: return getOccurrence(); case -1500852503: return getAuthoredOnElement(); case 693933948: return getRequester(); case -1663305268: return addSupplier(); case -669418564: return getReason(); case -934964668: return getReason(); case -949323153: return getDeliverFrom(); case -242327936: return getDeliverTo(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return new String[] {"Identifier"}; case -892481550: /*status*/ return new String[] {"code"}; case 50511102: /*category*/ return new String[] {"CodeableConcept"}; case -1165461084: /*priority*/ return new String[] {"code"}; case 2129914144: /*orderedItem*/ return new String[] {}; case 1687874001: /*occurrence*/ return new String[] {"dateTime", "Period", "Timing"}; case -1500852503: /*authoredOn*/ return new String[] {"dateTime"}; case 693933948: /*requester*/ return new String[] {}; case -1663305268: /*supplier*/ return new String[] {"Reference"}; case -934964668: /*reason*/ return new String[] {"CodeableConcept", "Reference"}; case -949323153: /*deliverFrom*/ return new String[] {"Reference"}; case -242327936: /*deliverTo*/ return new String[] {"Reference"}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("identifier")) { this.identifier = new Identifier(); return this.identifier; } else if (name.equals("status")) { throw new FHIRException("Cannot call addChild on a primitive type SupplyRequest.status"); } else if (name.equals("category")) { this.category = new CodeableConcept(); return this.category; } else if (name.equals("priority")) { throw new FHIRException("Cannot call addChild on a primitive type SupplyRequest.priority"); } else if (name.equals("orderedItem")) { this.orderedItem = new SupplyRequestOrderedItemComponent(); return this.orderedItem; } else if (name.equals("occurrenceDateTime")) { this.occurrence = new DateTimeType(); return this.occurrence; } else if (name.equals("occurrencePeriod")) { this.occurrence = new Period(); return this.occurrence; } else if (name.equals("occurrenceTiming")) { this.occurrence = new Timing(); return this.occurrence; } else if (name.equals("authoredOn")) { throw new FHIRException("Cannot call addChild on a primitive type SupplyRequest.authoredOn"); } else if (name.equals("requester")) { this.requester = new SupplyRequestRequesterComponent(); return this.requester; } else if (name.equals("supplier")) { return addSupplier(); } else if (name.equals("reasonCodeableConcept")) { this.reason = new CodeableConcept(); return this.reason; } else if (name.equals("reasonReference")) { this.reason = new Reference(); return this.reason; } else if (name.equals("deliverFrom")) { this.deliverFrom = new Reference(); return this.deliverFrom; } else if (name.equals("deliverTo")) { this.deliverTo = new Reference(); return this.deliverTo; } else return super.addChild(name); } public String fhirType() { return "SupplyRequest"; } public SupplyRequest copy() { SupplyRequest dst = new SupplyRequest(); copyValues(dst); dst.identifier = identifier == null ? null : identifier.copy(); dst.status = status == null ? null : status.copy(); dst.category = category == null ? null : category.copy(); dst.priority = priority == null ? null : priority.copy(); dst.orderedItem = orderedItem == null ? null : orderedItem.copy(); dst.occurrence = occurrence == null ? null : occurrence.copy(); dst.authoredOn = authoredOn == null ? null : authoredOn.copy(); dst.requester = requester == null ? null : requester.copy(); if (supplier != null) { dst.supplier = new ArrayList<Reference>(); for (Reference i : supplier) dst.supplier.add(i.copy()); }; dst.reason = reason == null ? null : reason.copy(); dst.deliverFrom = deliverFrom == null ? null : deliverFrom.copy(); dst.deliverTo = deliverTo == null ? null : deliverTo.copy(); return dst; } protected SupplyRequest typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof SupplyRequest)) return false; SupplyRequest o = (SupplyRequest) other; return compareDeep(identifier, o.identifier, true) && compareDeep(status, o.status, true) && compareDeep(category, o.category, true) && compareDeep(priority, o.priority, true) && compareDeep(orderedItem, o.orderedItem, true) && compareDeep(occurrence, o.occurrence, true) && compareDeep(authoredOn, o.authoredOn, true) && compareDeep(requester, o.requester, true) && compareDeep(supplier, o.supplier, true) && compareDeep(reason, o.reason, true) && compareDeep(deliverFrom, o.deliverFrom, true) && compareDeep(deliverTo, o.deliverTo, true) ; } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof SupplyRequest)) return false; SupplyRequest o = (SupplyRequest) other; return compareValues(status, o.status, true) && compareValues(priority, o.priority, true) && compareValues(authoredOn, o.authoredOn, true) ; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, status, category , priority, orderedItem, occurrence, authoredOn, requester, supplier, reason, deliverFrom , deliverTo); } @Override public ResourceType getResourceType() { return ResourceType.SupplyRequest; } /** * Search parameter: <b>requester</b> * <p> * Description: <b>Individual making the request</b><br> * Type: <b>reference</b><br> * Path: <b>SupplyRequest.requester.agent</b><br> * </p> */ @SearchParamDefinition(name="requester", path="SupplyRequest.requester.agent", description="Individual making the request", type="reference", providesMembershipIn={ @ca.uhn.fhir.model.api.annotation.Compartment(name="Device"), @ca.uhn.fhir.model.api.annotation.Compartment(name="Patient"), @ca.uhn.fhir.model.api.annotation.Compartment(name="Practitioner"), @ca.uhn.fhir.model.api.annotation.Compartment(name="RelatedPerson") }, target={Device.class, Organization.class, Patient.class, Practitioner.class, RelatedPerson.class } ) public static final String SP_REQUESTER = "requester"; /** * <b>Fluent Client</b> search parameter constant for <b>requester</b> * <p> * Description: <b>Individual making the request</b><br> * Type: <b>reference</b><br> * Path: <b>SupplyRequest.requester.agent</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam REQUESTER = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_REQUESTER); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>SupplyRequest:requester</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_REQUESTER = new ca.uhn.fhir.model.api.Include("SupplyRequest:requester").toLocked(); /** * Search parameter: <b>date</b> * <p> * Description: <b>When the request was made</b><br> * Type: <b>date</b><br> * Path: <b>SupplyRequest.authoredOn</b><br> * </p> */ @SearchParamDefinition(name="date", path="SupplyRequest.authoredOn", description="When the request was made", type="date" ) public static final String SP_DATE = "date"; /** * <b>Fluent Client</b> search parameter constant for <b>date</b> * <p> * Description: <b>When the request was made</b><br> * Type: <b>date</b><br> * Path: <b>SupplyRequest.authoredOn</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.DateClientParam DATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_DATE); /** * Search parameter: <b>identifier</b> * <p> * Description: <b>Unique identifier</b><br> * Type: <b>token</b><br> * Path: <b>SupplyRequest.identifier</b><br> * </p> */ @SearchParamDefinition(name="identifier", path="SupplyRequest.identifier", description="Unique identifier", type="token" ) public static final String SP_IDENTIFIER = "identifier"; /** * <b>Fluent Client</b> search parameter constant for <b>identifier</b> * <p> * Description: <b>Unique identifier</b><br> * Type: <b>token</b><br> * Path: <b>SupplyRequest.identifier</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER); /** * Search parameter: <b>supplier</b> * <p> * Description: <b>Who is intended to fulfill the request</b><br> * Type: <b>reference</b><br> * Path: <b>SupplyRequest.supplier</b><br> * </p> */ @SearchParamDefinition(name="supplier", path="SupplyRequest.supplier", description="Who is intended to fulfill the request", type="reference", target={Organization.class } ) public static final String SP_SUPPLIER = "supplier"; /** * <b>Fluent Client</b> search parameter constant for <b>supplier</b> * <p> * Description: <b>Who is intended to fulfill the request</b><br> * Type: <b>reference</b><br> * Path: <b>SupplyRequest.supplier</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam SUPPLIER = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_SUPPLIER); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>SupplyRequest:supplier</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_SUPPLIER = new ca.uhn.fhir.model.api.Include("SupplyRequest:supplier").toLocked(); /** * Search parameter: <b>category</b> * <p> * Description: <b>The kind of supply (central, non-stock, etc.)</b><br> * Type: <b>token</b><br> * Path: <b>SupplyRequest.category</b><br> * </p> */ @SearchParamDefinition(name="category", path="SupplyRequest.category", description="The kind of supply (central, non-stock, etc.)", type="token" ) public static final String SP_CATEGORY = "category"; /** * <b>Fluent Client</b> search parameter constant for <b>category</b> * <p> * Description: <b>The kind of supply (central, non-stock, etc.)</b><br> * Type: <b>token</b><br> * Path: <b>SupplyRequest.category</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam CATEGORY = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_CATEGORY); /** * Search parameter: <b>status</b> * <p> * Description: <b>draft | active | suspended +</b><br> * Type: <b>token</b><br> * Path: <b>SupplyRequest.status</b><br> * </p> */ @SearchParamDefinition(name="status", path="SupplyRequest.status", description="draft | active | suspended +", type="token" ) public static final String SP_STATUS = "status"; /** * <b>Fluent Client</b> search parameter constant for <b>status</b> * <p> * Description: <b>draft | active | suspended +</b><br> * Type: <b>token</b><br> * Path: <b>SupplyRequest.status</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam STATUS = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_STATUS); }
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.extensions; import android.content.Context; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.OptIn; import androidx.annotation.RestrictTo; import androidx.camera.core.Camera; import androidx.camera.core.CameraFilter; import androidx.camera.core.CameraInfo; import androidx.camera.core.CameraSelector; import androidx.camera.core.ExperimentalCameraFilter; import androidx.camera.core.UseCase; import androidx.camera.core.impl.CameraFilters; import androidx.camera.core.internal.CameraUseCaseAdapter; import androidx.camera.extensions.impl.AutoImageCaptureExtenderImpl; import androidx.camera.extensions.impl.AutoPreviewExtenderImpl; import androidx.camera.extensions.impl.BeautyImageCaptureExtenderImpl; import androidx.camera.extensions.impl.BeautyPreviewExtenderImpl; import androidx.camera.extensions.impl.BokehImageCaptureExtenderImpl; import androidx.camera.extensions.impl.BokehPreviewExtenderImpl; import androidx.camera.extensions.impl.HdrImageCaptureExtenderImpl; import androidx.camera.extensions.impl.HdrPreviewExtenderImpl; import androidx.camera.extensions.impl.NightImageCaptureExtenderImpl; import androidx.camera.extensions.impl.NightPreviewExtenderImpl; import androidx.camera.extensions.internal.ExtensionsUseCaseConfigFactory; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.LinkedHashSet; import java.util.List; /** * A class for querying and controlling the extensions that are enable for individual * {@link Camera} instances. * * <p> The typical usages is to check whether or not a Camera and/or the {@link UseCase} * combinations support the extension by using {@link #isExtensionAvailable(Camera, int)} and * {@link #checkUseCases(Camera, List, int)}. Then after it has been determined that the * extension can be enable then a {@link #setExtension(Camera, int)} call can be used to set the * specified extension on the camera. * * <p> When the Camera has been set to a particular extension it might require the camera to * restart which can cause the preview to temporarily stop. Once the extension has been enable * for a Camera instance then it will stay in that extension mode until the extension has been * disabled. Setting extension modes is separate for each camera instance. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class Extensions { private static final String TAG = "Extensions"; /** Normal mode without any specific effect applied. */ public static final int EXTENSION_MODE_NONE = 0; /** Bokeh mode that is often applied as portrait mode for people pictures. */ public static final int EXTENSION_MODE_BOKEH = 1; /** * HDR mode that may get source pictures with different AE settings to generate a best * result. */ public static final int EXTENSION_MODE_HDR = 2; /** * Night mode is used for taking better still capture images under low-light situations, * typically at night time. */ public static final int EXTENSION_MODE_NIGHT = 3; /** * Beauty mode is used for taking still capture images that incorporate facial changes * like skin tone, geometry, or retouching. */ public static final int EXTENSION_MODE_BEAUTY = 4; /** * Auto mode is used for taking still capture images that automatically adjust to the * surrounding scenery. */ public static final int EXTENSION_MODE_AUTO = 5; private final Context mContext; /** * The different extension modes that a {@link Camera} can be configured for. * * <p>Not all devices and camera support the different extension modes. To query whether or * not a specific Camera supports an extension mode use * {@link Extensions#isExtensionAvailable(Camera, int)}. * * @hide */ @IntDef({EXTENSION_MODE_NONE, EXTENSION_MODE_BOKEH, EXTENSION_MODE_HDR, EXTENSION_MODE_NIGHT, EXTENSION_MODE_BEAUTY, EXTENSION_MODE_AUTO}) @Retention(RetentionPolicy.SOURCE) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public @interface ExtensionMode { } Extensions(@NonNull Context context) { mContext = context; } /** * Sets the specified extension mode for the Camera. * * To return to a non-extensions mode Camera set the extension mode as NONE. * For full list of extensions see Extension Modes * * @param camera The camera that the UseCases are attached to * @param mode The extension mode to set. Setting this to EXTENSION_NONE will * remove the current extension and will always succeed. * @throws IllegalArgumentException if the specified extension mode can not be set on the * Camera. This can happen if the extension is not supported * on this camera. This might also * because the combination of UseCases attached to the * Camera. Use {@link * #checkUseCases(Camera, List, int)} to verify that the * Camera can support the list of * UseCases for the extension. */ @OptIn(markerClass = ExperimentalCameraFilter.class) public void setExtension(@NonNull Camera camera, @ExtensionMode int mode) { if (!isExtensionAvailable(camera, mode)) { throw new IllegalArgumentException("Extension mode not supported on camera: " + mode); } CameraSelector cameraSelector = new CameraSelector.Builder().addCameraFilter(getFilter(mode)).build(); Camera extensionCamera = cameraSelector.select(new LinkedHashSet<>(camera.getCameraInternals())); CameraInfo extensionsCameraInfo = extensionCamera.getCameraInfo(); ExtensionsUseCaseConfigFactory factory = new ExtensionsUseCaseConfigFactory(mode, extensionsCameraInfo, mContext); // Set the Camera ExtensionsConfig extensionsConfig = new ExtensionsConfig.Builder() .setExtensionMode(mode) .setCameraFilter(getFilter(mode)) .setUseCaseConfigFactory(factory) .build(); // Set the config on the camera try { camera.setExtendedConfig(extensionsConfig); } catch (CameraUseCaseAdapter.CameraException e) { throw new IllegalArgumentException("Camera unable to support the extension with the " + "attached UseCases. " + e); } } /** * Returns the extension mode that is currently set on the camera. */ public @ExtensionMode int getExtension(@NonNull Camera camera) { Object extensionsConfigObject = camera.getExtendedConfig(); if (extensionsConfigObject instanceof ExtensionsConfig) { ExtensionsConfig extensionsConfig = (ExtensionsConfig) extensionsConfigObject; return extensionsConfig.getExtensionMode(); } return EXTENSION_MODE_NONE; } /** * Returns true if the particular extension mode is available for the specified * Camera. * * <p> This check is independent of the {@link UseCase} which are currently attached to the * {@link Camera}. To check whether the Camera can support the attached UseCases use {@link * #checkUseCases(Camera, List, int)}. * * @param camera The Camera to check if it supports the extension. * @param mode The extension mode to check */ @OptIn(markerClass = ExperimentalCameraFilter.class) public boolean isExtensionAvailable(@NonNull Camera camera, @ExtensionMode int mode) { CameraSelector cameraSelector = new CameraSelector.Builder().addCameraFilter(getFilter(mode)).build(); // Extension is available for the camera if it contains a CameraInternal which supports // the extension try { cameraSelector.select(new LinkedHashSet<>(camera.getCameraInternals())); } catch (IllegalArgumentException e) { return false; } return true; } @OptIn(markerClass = ExperimentalCameraFilter.class) private CameraFilter getFilter(@ExtensionMode int mode) { CameraFilter filter; try { switch (mode) { case EXTENSION_MODE_BOKEH: filter = new ExtensionCameraFilter(new BokehPreviewExtenderImpl(), new BokehImageCaptureExtenderImpl()); break; case EXTENSION_MODE_HDR: filter = new ExtensionCameraFilter(new HdrPreviewExtenderImpl(), new HdrImageCaptureExtenderImpl()); break; case EXTENSION_MODE_NIGHT: filter = new ExtensionCameraFilter(new NightPreviewExtenderImpl(), new NightImageCaptureExtenderImpl()); break; case EXTENSION_MODE_BEAUTY: filter = new ExtensionCameraFilter(new BeautyPreviewExtenderImpl(), new BeautyImageCaptureExtenderImpl()); break; case EXTENSION_MODE_AUTO: filter = new ExtensionCameraFilter(new AutoPreviewExtenderImpl(), new AutoImageCaptureExtenderImpl()); break; case EXTENSION_MODE_NONE: default: filter = CameraFilters.ANY; } } catch (NoClassDefFoundError e) { filter = CameraFilters.NONE; } return filter; } /** * Checks if the list of UseCases attached to the Camera can support the * extension. * * If the list of UseCases exceeds the capacity of Surfaces for the Camera then * it returns a list of UseCase lists that can be removed in order to allow for * the extension to be enabled. Any of the individual lists can be removed. * * @return null if the Camera supports the extension using the list of UseCases, otherwise a * list of UseCase list to remove. */ @NonNull public List<List<UseCase>> checkUseCases(@NonNull Camera camera, @NonNull List<UseCase> useCases, @ExtensionMode int mode) { throw new UnsupportedOperationException("not yet implemented"); } }
/* * ComponentEos.java * * Created on 14. mai 2000, 21:27 */ package neqsim.thermo.component; import neqsim.thermo.phase.PhaseInterface; /** * * @author Even Solbraa * @version */ public class ComponentDefault extends Component { private static final long serialVersionUID = 1000; public ComponentDefault() { } @Override public double fugcoef(PhaseInterface phase) { return 0.0; } }
/* * Copyright (c) 2011-2019, hubin (jobob@qq.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.baomidou.mybatisplus.extension.api; /** * REST API 错误码接口 * * @author hubin * @since 2018-06-05 */ public interface IErrorCode { /** * 错误编码 -1、失败 0、成功 */ long getCode(); /** * 错误描述 */ String getMsg(); }
/* * 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.pinot.thirdeye.rootcause.impl; import org.apache.pinot.thirdeye.datalayer.bao.EventManager; import org.apache.pinot.thirdeye.datalayer.dto.EventDTO; import org.apache.pinot.thirdeye.datalayer.util.Predicate; import org.apache.pinot.thirdeye.datasource.DAORegistry; import org.apache.pinot.thirdeye.rootcause.Entity; import org.apache.pinot.thirdeye.rootcause.MaxScoreSet; import org.apache.pinot.thirdeye.rootcause.Pipeline; import org.apache.pinot.thirdeye.rootcause.PipelineContext; import org.apache.pinot.thirdeye.rootcause.PipelineResult; import org.apache.pinot.thirdeye.rootcause.util.EntityUtils; import org.apache.pinot.thirdeye.rootcause.util.ScoreUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.collections4.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ThirdEyeEventsPipeline produces EventEntities within the current * TimeRange. It matches holidays and customized events based on incoming DimensionEntities (e.g. from contribution * analysis) and scores them based on the number of matching DimensionEntities. * This pipeline will add a buffer of 2 days to the time range provided */ public class ThirdEyeEventsPipeline extends Pipeline { private static final Logger LOG = LoggerFactory.getLogger(ThirdEyeEventsPipeline.class); private static final String DIMENSION_COUNTRY_CODE = "countryCode"; enum StrategyType { LINEAR, TRIANGULAR, QUADRATIC, HYPERBOLA, DIMENSION, COMPOUND } private static final String PROP_K = "k"; private static final int PROP_K_DEFAULT = -1; private static final String PROP_STRATEGY = "strategy"; private static final String PROP_STRATEGY_DEFAULT = StrategyType.COMPOUND.toString(); private static final String PROP_EVENT_TYPE = "eventType"; private static final long OVERFETCH = TimeUnit.DAYS.toMillis(2); private final StrategyType strategy; private final EventManager eventDAO; private final int k; private final String eventType; /** * Constructor for dependency injection * * @param outputName pipeline output name * @param inputNames input pipeline names * @param eventDAO event DAO * @param strategy scoring strategy * @param k the k * @param eventType the event type */ public ThirdEyeEventsPipeline(String outputName, Set<String> inputNames, EventManager eventDAO, StrategyType strategy, int k, String eventType) { super(outputName, inputNames); this.eventDAO = eventDAO; this.strategy = strategy; this.k = k; this.eventType = eventType; } /** * Alternate constructor for RCAFrameworkLoader * * @param outputName pipeline output name * @param inputNames input pipeline names * @param properties configuration properties ({@code PROP_STRATEGY}) */ public ThirdEyeEventsPipeline(String outputName, Set<String> inputNames, Map<String, Object> properties) { super(outputName, inputNames); this.eventDAO = DAORegistry.getInstance().getEventDAO(); this.strategy = StrategyType.valueOf(MapUtils.getString(properties, PROP_STRATEGY, PROP_STRATEGY_DEFAULT)); this.eventType = MapUtils.getString(properties, PROP_EVENT_TYPE, "holiday"); this.k = MapUtils.getInteger(properties, PROP_K, PROP_K_DEFAULT); } @Override public PipelineResult run(PipelineContext context) { TimeRangeEntity anomaly = TimeRangeEntity.getTimeRangeAnomaly(context); TimeRangeEntity baseline = TimeRangeEntity.getTimeRangeBaseline(context); TimeRangeEntity analysis = TimeRangeEntity.getTimeRangeAnalysis(context); ScoringStrategy strategyAnomaly = makeStrategy(analysis.getStart(), anomaly.getStart(), anomaly.getEnd()); ScoringStrategy strategyBaseline = makeStrategy(baseline.getStart(), baseline.getStart(), baseline.getEnd()); // use both provided and generated Set<DimensionEntity> dimensionEntities = context.filter(DimensionEntity.class); Map<String, DimensionEntity> countryCodeLookup = new HashMap<>(); for (DimensionEntity dimension : dimensionEntities) { if (dimension.getName().equals(DIMENSION_COUNTRY_CODE)) { countryCodeLookup.put(dimension.getValue(), dimension); } } Set<EventEntity> entities = new MaxScoreSet<>(); entities.addAll(EntityUtils.addRelated(score(strategyAnomaly, this.getThirdEyeEvents(analysis.getStart(), anomaly.getEnd()), countryCodeLookup, anomaly.getScore()), anomaly)); entities.addAll(EntityUtils.addRelated(score(strategyBaseline, this.getThirdEyeEvents(baseline.getStart(), baseline.getEnd()), countryCodeLookup, baseline.getScore()), baseline)); return new PipelineResult(context, EntityUtils.topk(entities, this.k)); } private List<EventDTO> getThirdEyeEvents(long start, long end) { return this.eventDAO.findByPredicate(Predicate.AND( Predicate.GE("startTime", start - OVERFETCH), Predicate.LT("endTime", end + OVERFETCH), Predicate.EQ("eventType", eventType.toUpperCase()) )); } /* ************************************************************************** * Entity scoring * *************************************************************************/ private List<EventEntity> score(ScoringStrategy strategy, Iterable<EventDTO> events, Map<String, DimensionEntity> countryCodeLookup, double coefficient) { List<EventEntity> entities = new ArrayList<>(); for(EventDTO dto : events) { List<Entity> related = new ArrayList<>(); if (dto.getTargetDimensionMap().containsKey(DIMENSION_COUNTRY_CODE)) { for (String countryCode : dto.getTargetDimensionMap().get(DIMENSION_COUNTRY_CODE)) { final String countryKey = countryCode.toLowerCase(); if (countryCodeLookup.containsKey(countryKey)) { related.add(countryCodeLookup.get(countryKey)); } } } ThirdEyeEventEntity entity = ThirdEyeEventEntity.fromDTO(1.0, related, dto, eventType); entities.add(entity.withScore(strategy.score(entity) * coefficient)); } return entities; } private ScoringStrategy makeStrategy(long lookback, long start, long end) { switch(this.strategy) { case LINEAR: return new ScoreWrapper(new ScoreUtils.LinearStartTimeStrategy(start, end)); case TRIANGULAR: return new ScoreWrapper(new ScoreUtils.TriangularStartTimeStrategy(lookback, start, end)); case QUADRATIC: return new ScoreWrapper(new ScoreUtils.QuadraticTriangularStartTimeStrategy(lookback, start, end)); case HYPERBOLA: return new ScoreWrapper(new ScoreUtils.HyperbolaStrategy(start, end)); case DIMENSION: return new DimensionStrategy(); case COMPOUND: return new CompoundStrategy(new ScoreWrapper(new ScoreUtils.HyperbolaStrategy(start, end))); default: throw new IllegalArgumentException(String.format("Invalid strategy type '%s'", this.strategy)); } } private interface ScoringStrategy { double score(ThirdEyeEventEntity entity); } /** * Wrapper for ScoreUtils time-based strategies */ private static class ScoreWrapper implements ScoringStrategy { private final ScoreUtils.TimeRangeStrategy delegate; ScoreWrapper(ScoreUtils.TimeRangeStrategy delegate) { this.delegate = delegate; } @Override public double score(ThirdEyeEventEntity entity) { return this.delegate.score(entity.getDto().getStartTime(), entity.getDto().getEndTime()); } } /** * Uses the highest score of dimension entities as they relate to an event */ private static class DimensionStrategy implements ScoringStrategy { @Override public double score(ThirdEyeEventEntity entity) { double max = 0.0; for(Entity r : entity.getRelated()) { if(r instanceof DimensionEntity) { final DimensionEntity de = (DimensionEntity) r; if (de.getName().equals(DIMENSION_COUNTRY_CODE)) { max = Math.max(de.getScore(), max); } } } return max; } } /** * Compound strategy that considers both event time as well as the presence of related dimension entities */ private static class CompoundStrategy implements ScoringStrategy { private final ScoringStrategy delegateTime; private final ScoringStrategy delegateDimension = new DimensionStrategy(); CompoundStrategy(ScoringStrategy delegateTime) { this.delegateTime = delegateTime; } @Override public double score(ThirdEyeEventEntity entity) { double scoreTime = this.delegateTime.score(entity); double scoreDimension = this.delegateDimension.score(entity); double scoreHasDimension = scoreDimension > 0 ? 1 : 0; // ignore truncated results if (scoreTime <= 0) return 0; return scoreTime + scoreHasDimension + Math.min(scoreDimension, 1); } } }
package galaxyspace.core.client.models.entity; import galaxyspace.core.prefab.entities.EntityAstroWolf; import micdoodle8.mods.galacticraft.core.GCItems; import micdoodle8.mods.galacticraft.core.items.ItemOxygenTank; import micdoodle8.mods.galacticraft.core.util.OxygenUtil; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.math.MathHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ModelAstroWolf extends ModelBase { /** main box for the wolf head */ public ModelRenderer wolfHeadMain; /** The wolf's body */ public ModelRenderer wolfBody; /** Wolf'se first leg */ public ModelRenderer wolfLeg1; /** Wolf's second leg */ public ModelRenderer wolfLeg2; /** Wolf's third leg */ public ModelRenderer wolfLeg3; /** Wolf's fourth leg */ public ModelRenderer wolfLeg4; /** Helmet */ public ModelRenderer wolfHelmet; /** The wolf's tail */ ModelRenderer wolfTail; /** The wolf's mane */ ModelRenderer wolfMane; public ModelRenderer tube1; public ModelRenderer tube2; public ModelRenderer tube3; public ModelRenderer tube1_1; public ModelRenderer tube1_2; public ModelRenderer tube1_3; public ModelRenderer tube1_4; public ModelRenderer tube1_5; public ModelRenderer oxBallon; public ModelAstroWolf() { this.textureWidth = 128; this.textureHeight = 64; float f = 0.0F; float f1 = 13.5F; this.wolfHeadMain = new ModelRenderer(this, 0, 0); this.wolfHeadMain.addBox(-2.0F, -3.0F, -2.0F, 6, 6, 4, 0.0F); this.wolfHeadMain.setRotationPoint(-1.0F, 13.5F, -7.0F); this.wolfBody = new ModelRenderer(this, 18, 14); this.wolfBody.addBox(-3.0F, -2.0F, -3.0F, 6, 9, 6, 0.0F); this.wolfBody.setRotationPoint(0.0F, 14.0F, 2.0F); this.wolfMane = new ModelRenderer(this, 21, 0); this.wolfMane.addBox(-3.0F, -3.0F, -3.0F, 8, 6, 7, 0.0F); this.wolfMane.setRotationPoint(-1.0F, 14.0F, 2.0F); this.wolfLeg1 = new ModelRenderer(this, 0, 18); this.wolfLeg1.addBox(0.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F); this.wolfLeg1.setRotationPoint(-2.5F, 16.0F, 7.0F); this.wolfLeg2 = new ModelRenderer(this, 0, 18); this.wolfLeg2.addBox(0.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F); this.wolfLeg2.setRotationPoint(0.5F, 16.0F, 7.0F); this.wolfLeg3 = new ModelRenderer(this, 0, 18); this.wolfLeg3.addBox(0.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F); this.wolfLeg3.setRotationPoint(-2.5F, 16.0F, -4.0F); this.wolfLeg4 = new ModelRenderer(this, 0, 18); this.wolfLeg4.addBox(0.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F); this.wolfLeg4.setRotationPoint(0.5F, 16.0F, -4.0F); this.wolfTail = new ModelRenderer(this, 9, 18); this.wolfTail.addBox(0.0F, 0.0F, -1.0F, 2, 8, 2, 0.0F); this.wolfTail.setRotationPoint(-1.0F, 12.0F, 8.0F); this.wolfHelmet = new ModelRenderer(this, 51, 0); this.wolfHelmet.setRotationPoint(-0.0F, 12.6F, -9.2F); this.wolfHelmet.addBox(-5.0F, -5.0F, -5.0F, 10, 10, 10, -0.6F); this.setRotateAngle(wolfHelmet, 0.0F, 0.0F, 8.726646259971648E-4F); this.wolfHeadMain.setTextureOffset(16, 14).addBox(-2.0F, -5.0F, 0.0F, 2, 2, 1, 0.0F); this.wolfHeadMain.setTextureOffset(16, 14).addBox(2.0F, -5.0F, 0.0F, 2, 2, 1, 0.0F); this.wolfHeadMain.setTextureOffset(0, 10).addBox(-0.5F, 0.0F, -5.0F, 3, 3, 4, 0.0F); this.tube1 = new ModelRenderer(this, 51, 20); this.tube1.setRotationPoint(-0.5F, 9.0F, -6.0F); this.tube1.addBox(0.0F, 0.0F, 0.0F, 1, 1, 1, 0.0F); this.tube2 = new ModelRenderer(this, 51, 20); this.tube2.setRotationPoint(-0.5F, 9.3F, -0.5F); this.tube2.addBox(0.0F, 0.0F, 0.0F, 1, 1, 1, 0.0F); this.tube3 = new ModelRenderer(this, 51, 20); this.tube3.setRotationPoint(-0.5F, 10.1F, 0.5F); this.tube3.addBox(0.0F, 0.0F, 0.0F, 1, 1, 1, 0.0F); this.tube1_1 = new ModelRenderer(this, 51, 20); this.tube1_1.setRotationPoint(-0.5F, 9.0F, -5.0F); this.tube1_1.addBox(0.0F, 0.0F, 0.0F, 1, 1, 1, 0.0F); this.tube1_2 = new ModelRenderer(this, 51, 20); this.tube1_2.setRotationPoint(-0.5F, 9.0F, -4.0F); this.tube1_2.addBox(0.0F, 0.0F, 0.0F, 1, 1, 1, 0.0F); this.tube1_3 = new ModelRenderer(this, 51, 20); this.tube1_3.setRotationPoint(-0.5F, 9.0F, -3.0F); this.tube1_3.addBox(0.0F, 0.0F, 0.0F, 1, 1, 1, 0.0F); this.tube1_4 = new ModelRenderer(this, 51, 20); this.tube1_4.setRotationPoint(-0.5F, 9.0F, -2.0F); this.tube1_4.addBox(0.0F, 0.0F, 0.0F, 1, 1, 1, 0.0F); this.tube1_5 = new ModelRenderer(this, 51, 20); this.tube1_5.setRotationPoint(-0.5F, 9.0F, -1.0F); this.tube1_5.addBox(0.0F, 0.0F, 0.0F, 1, 1, 1, 0.0F); this.oxBallon = new ModelRenderer(this, 51, 20); this.oxBallon.setRotationPoint(-1.0F, 9.0F, 0.0F); this.oxBallon.addBox(0.0F, 0.0F, 0.0F, 2, 2, 5, 0.0F); } /** * Sets the models various rotation angles then renders the model. */ public void render(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale) { super.render(entityIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale); this.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale, entityIn); EntityAstroWolf entitywolf = (EntityAstroWolf)entityIn; if (this.isChild) { float f = 2.0F; GlStateManager.pushMatrix(); GlStateManager.translate(0.0F, 5.0F * scale, 2.0F * scale); this.wolfHeadMain.renderWithRotation(scale); GlStateManager.popMatrix(); GlStateManager.pushMatrix(); GlStateManager.scale(0.5F, 0.5F, 0.5F); GlStateManager.translate(0.0F, 24.0F * scale, 0.0F); this.wolfBody.render(scale); this.wolfLeg1.render(scale); this.wolfLeg2.render(scale); this.wolfLeg3.render(scale); this.wolfLeg4.render(scale); this.wolfTail.renderWithRotation(scale); this.wolfMane.render(scale); if(entitywolf.wolfInventory.getStackInSlot(0).getItem() == GCItems.oxMask && !OxygenUtil.isAABBInBreathableAirBlock(entitywolf)) { this.wolfHelmet.renderWithRotation(scale); this.tube1.render(scale); this.tube2.render(scale); this.tube3.render(scale); this.tube1_1.render(scale); this.tube1_2.render(scale); this.tube1_3.render(scale); this.tube1_4.render(scale); this.tube1_5.render(scale); } if(entitywolf.wolfInventory.getStackInSlot(2).getItem() instanceof ItemOxygenTank) this.oxBallon.render(scale); GlStateManager.popMatrix(); } else { this.wolfHeadMain.renderWithRotation(scale); this.wolfBody.render(scale); this.wolfLeg1.render(scale); this.wolfLeg2.render(scale); this.wolfLeg3.render(scale); this.wolfLeg4.render(scale); this.wolfTail.renderWithRotation(scale); this.wolfMane.render(scale); if(entitywolf.wolfInventory.getStackInSlot(0).getItem() == GCItems.oxMask && !OxygenUtil.isAABBInBreathableAirBlock(entitywolf)) { this.wolfHelmet.render(scale); this.tube1.render(scale); this.tube2.render(scale); this.tube3.render(scale); this.tube1_1.render(scale); this.tube1_2.render(scale); this.tube1_3.render(scale); this.tube1_4.render(scale); this.tube1_5.render(scale); } if(entitywolf.wolfInventory.getStackInSlot(2).getItem() instanceof ItemOxygenTank) this.oxBallon.render(scale); } } /** * Used for easily adding entity-dependent animations. The second and third float params here are the same second * and third as in the setRotationAngles method. */ public void setLivingAnimations(EntityLivingBase entitylivingbaseIn, float limbSwing, float limbSwingAmount, float partialTickTime) { EntityAstroWolf entitywolf = (EntityAstroWolf)entitylivingbaseIn; if (entitywolf.isAngry()) { this.wolfTail.rotateAngleY = 0.0F; } else { this.wolfTail.rotateAngleY = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; } if (entitywolf.isSitting()) { this.wolfMane.setRotationPoint(-1.0F, 16.0F, -3.0F); this.wolfMane.rotateAngleX = ((float)Math.PI * 2F / 5F); this.wolfMane.rotateAngleY = 0.0F; this.wolfBody.setRotationPoint(0.0F, 18.0F, 0.0F); this.wolfBody.rotateAngleX = ((float)Math.PI / 4F); this.wolfTail.setRotationPoint(-1.0F, 21.0F, 6.0F); this.wolfLeg1.setRotationPoint(-2.5F, 22.0F, 2.0F); this.wolfLeg1.rotateAngleX = ((float)Math.PI * 3F / 2F); this.wolfLeg2.setRotationPoint(0.5F, 22.0F, 2.0F); this.wolfLeg2.rotateAngleX = ((float)Math.PI * 3F / 2F); this.wolfLeg3.rotateAngleX = 5.811947F; this.wolfLeg3.setRotationPoint(-2.49F, 17.0F, -4.0F); this.wolfLeg4.rotateAngleX = 5.811947F; this.wolfLeg4.setRotationPoint(0.51F, 17.0F, -4.0F); this.tube1_1.offsetY = 0.05F; this.tube1_2.offsetY = 0.08F; this.tube1_3.offsetY = 0.1F; this.tube1_4.offsetY = 0.13F; this.tube1_5.offsetY = 0.15F; this.tube2.offsetZ = 0.03F; this.tube2.offsetY = 0.18F; this.tube3.offsetY = 0.22F; this.oxBallon.rotateAngleX = 14.95F; this.oxBallon.rotateAngleY = 0F; this.oxBallon.offsetX = 0F; this.oxBallon.offsetY = 0.55F; this.oxBallon.offsetZ = 0.25F; } else { this.wolfBody.setRotationPoint(0.0F, 14.0F, 2.0F); this.wolfBody.rotateAngleX = ((float)Math.PI / 2F); this.wolfMane.setRotationPoint(-1.0F, 14.0F, -3.0F); this.wolfMane.rotateAngleX = this.wolfBody.rotateAngleX; this.wolfTail.setRotationPoint(-1.0F, 12.0F, 8.0F); this.wolfLeg1.setRotationPoint(-2.5F, 16.0F, 7.0F); this.wolfLeg2.setRotationPoint(0.5F, 16.0F, 7.0F); this.wolfLeg3.setRotationPoint(-2.5F, 16.0F, -4.0F); this.wolfLeg4.setRotationPoint(0.5F, 16.0F, -4.0F); this.wolfLeg1.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; this.wolfLeg2.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount; this.wolfLeg3.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount; this.wolfLeg4.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; this.tube1_1.offsetY = 0.0F; this.tube1_2.offsetY = 0.0F; this.tube1_3.offsetY = 0.0F; this.tube1_4.offsetY = 0.0F; this.tube1_5.offsetY = 0.0F; this.tube2.offsetZ = 0.0F; this.tube2.offsetY = 0.0F; this.tube3.offsetY = 0.0F; this.oxBallon.rotateAngleX = 0F; this.oxBallon.rotateAngleY = 3.15F; this.oxBallon.offsetX = 0.13F; this.oxBallon.offsetY = 0F; this.oxBallon.offsetZ = 0.4F; } this.wolfHeadMain.rotateAngleZ = entitywolf.getInterestedAngle(partialTickTime) + entitywolf.getShakeAngle(partialTickTime, 0.0F); this.wolfHelmet.rotateAngleZ = entitywolf.getInterestedAngle(partialTickTime) + entitywolf.getShakeAngle(partialTickTime, 0.0F); this.wolfMane.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.08F); this.wolfBody.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.16F); this.wolfTail.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.2F); } /** * Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms * and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how * "far" arms and legs can swing at most. */ public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) { super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); this.wolfHeadMain.rotateAngleX = headPitch * 0.017453292F; this.wolfHeadMain.rotateAngleY = netHeadYaw * 0.017453292F; this.wolfHelmet.rotateAngleX = headPitch * 0.017453292F; this.wolfHelmet.rotateAngleY = netHeadYaw * 0.017453292F; this.wolfTail.rotateAngleX = ageInTicks; } public void setRotateAngle(ModelRenderer modelRenderer, float x, float y, float z) { modelRenderer.rotateAngleX = x; modelRenderer.rotateAngleY = y; modelRenderer.rotateAngleZ = z; } }
/* * Copyright 2011-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.data.neo4j.integration.issues.gh2474; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.data.domain.Sort; import org.springframework.data.neo4j.repository.Neo4jRepository; import org.springframework.data.neo4j.repository.query.Query; /** * @author Stephen Jackson * @author Michael J. Simons */ public interface CityModelRepository extends Neo4jRepository<CityModel, UUID> { Optional<CityModelDTO> findByCityId(UUID cityId); @Query("" + "MATCH (n:CityModel)" + "RETURN n :#{orderBy(#sort)}") List<CityModel> customQuery(Sort sort); long deleteAllByExoticProperty(String property); }
/*<license> Copyright 2004 - $Date$ by PeopleWare n.v.. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. </license>*/ package org.ppwcode.util.reflect_I.teststubs; public interface SuperSuperSuperStubInterface { void stubMethodC(); }
package com.uxxu.konashi.lib.action; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import com.uxxu.konashi.lib.KonashiErrorType; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by izumin on 9/18/15. */ public class PwmLedDriveActionTest { @Mock private BluetoothGattService mService; @Mock private BluetoothGattCharacteristic mCharacteristic; private PwmLedDriveAction mAction; private ArgumentCaptor<byte[]> mValueCaptor; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mValueCaptor = ArgumentCaptor.forClass(byte[].class); when(mService.getCharacteristic(any(UUID.class))).thenReturn(mCharacteristic); } @Test public void hasValidParams_WithInvalidDutyRatio() throws Exception { mAction = new PwmLedDriveAction(mService, 2, 400, 3); assertThat(mAction.validate()).isEqualTo(KonashiErrorType.INVALID_DUTY_RATIO); } @Test public void hasValidParams_WithDutyOverPeriod() throws Exception { mAction = new PwmLedDriveAction(mService, 2, 400, 3); assertThat(mAction.validate()).isEqualTo(KonashiErrorType.INVALID_DUTY_RATIO); } @Test public void hasValidParams_WithValidDutyRatio() throws Exception { mAction = new PwmLedDriveAction(mService, 2, 30, 4000); assertThat(mAction.validate()).isEqualTo(KonashiErrorType.NO_ERROR); } @Test public void setValue_WithValidParams() throws Exception { mAction = new PwmLedDriveAction(mService, 2, 30, 4000); mAction.setValue(); verify(mCharacteristic, times(1)).setValue(mValueCaptor.capture()); assertThat(mValueCaptor.getValue()).isEqualTo( new byte[]{(byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x0b, (byte) 0xb8} ); } }
package com.dieam.reactnativepushnotification.modules; import android.app.Activity; import android.app.Application; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.NotificationManagerCompat; import com.dieam.reactnativepushnotification.helpers.ApplicationBadgeHelper; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import java.util.HashMap; import java.util.Map; import java.util.Random; import android.util.Log; import com.google.firebase.messaging.FirebaseMessaging; public class RNPushNotification extends ReactContextBaseJavaModule implements ActivityEventListener { public static final String LOG_TAG = "RNPushNotification";// all logging should use this tag private RNPushNotificationHelper mRNPushNotificationHelper; private final Random mRandomNumberGenerator = new Random(System.currentTimeMillis()); private RNPushNotificationJsDelivery mJsDelivery; public RNPushNotification(ReactApplicationContext reactContext) { super(reactContext); reactContext.addActivityEventListener(this); Application applicationContext = (Application) reactContext.getApplicationContext(); // The @ReactNative methods use this mRNPushNotificationHelper = new RNPushNotificationHelper(applicationContext); // This is used to delivery callbacks to JS mJsDelivery = new RNPushNotificationJsDelivery(reactContext); registerNotificationsRegistration(); } @Override public String getName() { return "RNPushNotification"; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); return constants; } private Bundle getBundleFromIntent(Intent intent) { Bundle bundle = null; if (intent.hasExtra("notification")) { bundle = intent.getBundleExtra("notification"); } else if (intent.hasExtra("google.message_id")) { bundle = intent.getExtras(); } return bundle; } public void onNewIntent(Intent intent) { Bundle bundle = this.getBundleFromIntent(intent); if (bundle != null) { bundle.putBoolean("foreground", false); intent.putExtra("notification", bundle); mJsDelivery.notifyNotification(bundle); } } private void registerNotificationsRegistration() { IntentFilter intentFilter = new IntentFilter(getReactApplicationContext().getPackageName() + ".RNPushNotificationRegisteredToken"); getReactApplicationContext().registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String token = intent.getStringExtra("token"); WritableMap params = Arguments.createMap(); params.putString("deviceToken", token); mJsDelivery.sendEvent("remoteNotificationsRegistered", params); } }, intentFilter); } private void registerNotificationsReceiveNotificationActions(ReadableArray actions) { IntentFilter intentFilter = new IntentFilter(); // Add filter for each actions. for (int i = 0; i < actions.size(); i++) { String action = actions.getString(i); intentFilter.addAction(getReactApplicationContext().getPackageName() + "." + action); } getReactApplicationContext().registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getBundleExtra("notification"); // Notify the action. mJsDelivery.notifyNotificationAction(bundle); // Dismiss the notification popup. NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); int notificationID = Integer.parseInt(bundle.getString("id")); manager.cancel(notificationID); } }, intentFilter); } @ReactMethod public void checkPermissions(Promise promise) { ReactContext reactContext = getReactApplicationContext(); NotificationManagerCompat managerCompat = NotificationManagerCompat.from(reactContext); promise.resolve(managerCompat.areNotificationsEnabled()); } @ReactMethod public void requestPermissions(String senderID) { ReactContext reactContext = getReactApplicationContext(); Intent GCMService = new Intent(reactContext, RNPushNotificationRegistrationService.class); try { GCMService.putExtra("senderID", senderID); reactContext.startService(GCMService); } catch (Exception e) { Log.d("EXCEPTION SERVICE::::::", "requestPermissions: " + e); } } @ReactMethod public void subscribeToTopic(String topic) { FirebaseMessaging.getInstance().subscribeToTopic(topic); } @ReactMethod public void presentLocalNotification(ReadableMap details) { Bundle bundle = Arguments.toBundle(details); // If notification ID is not provided by the user, generate one at random if (bundle.getString("id") == null) { bundle.putString("id", String.valueOf(mRandomNumberGenerator.nextInt())); } mRNPushNotificationHelper.sendToNotificationCentre(bundle); } @ReactMethod public void scheduleLocalNotification(ReadableMap details) { Bundle bundle = Arguments.toBundle(details); // If notification ID is not provided by the user, generate one at random if (bundle.getString("id") == null) { bundle.putString("id", String.valueOf(mRandomNumberGenerator.nextInt())); } mRNPushNotificationHelper.sendNotificationScheduled(bundle); } @ReactMethod public void getInitialNotification(Promise promise) { WritableMap params = Arguments.createMap(); Activity activity = getCurrentActivity(); if (activity != null) { Bundle bundle = this.getBundleFromIntent(activity.getIntent()); if (bundle != null) { bundle.putBoolean("foreground", false); String bundleString = mJsDelivery.convertJSON(bundle); params.putString("dataJSON", bundleString); } } promise.resolve(params); } @ReactMethod public void setApplicationIconBadgeNumber(int number) { ApplicationBadgeHelper.INSTANCE.setApplicationIconBadgeNumber(getReactApplicationContext(), number); } // removed @Override temporarily just to get it working on different versions of RN public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { onActivityResult(requestCode, resultCode, data); } // removed @Override temporarily just to get it working on different versions of RN public void onActivityResult(int requestCode, int resultCode, Intent data) { // Ignored, required to implement ActivityEventListener for RN 0.33 } @ReactMethod /** * Cancels all scheduled local notifications, and removes all entries from the notification * centre. * * We're attempting to keep feature parity with the RN iOS implementation in * <a href="https://github.com/facebook/react-native/blob/master/Libraries/PushNotificationIOS/RCTPushNotificationManager.m#L289">RCTPushNotificationManager</a>. * * @see <a href="https://facebook.github.io/react-native/docs/pushnotificationios.html">RN docs</a> */ public void cancelAllLocalNotifications() { mRNPushNotificationHelper.cancelAllScheduledNotifications(); mRNPushNotificationHelper.clearNotifications(); } @ReactMethod /** * Added by Viktor@Pilloxa 2019-04-03 */ public void cancelAllScheduledNotifications() { mRNPushNotificationHelper.cancelAllScheduledNotifications(); } @ReactMethod /** * Added by Viktor@Pilloxa 2019-04-03 */ public void clearAllVisibleNotifications() { mRNPushNotificationHelper.clearNotifications(); } @ReactMethod /** * Cancel scheduled notifications, and removes notifications from the notification centre. * * Note - as we are trying to achieve feature parity with iOS, this method cannot be used * to remove specific alerts from the notification centre. * * @see <a href="https://facebook.github.io/react-native/docs/pushnotificationios.html">RN docs</a> */ public void cancelLocalNotifications(ReadableMap userInfo) { mRNPushNotificationHelper.cancelScheduledNotification(userInfo); } @ReactMethod /** * Clear notification from the notification centre. */ public void clearLocalNotification(int notificationID) { mRNPushNotificationHelper.clearNotification(notificationID); } @ReactMethod public void registerNotificationActions(ReadableArray actions) { registerNotificationsReceiveNotificationActions(actions); } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.fabric; import static com.facebook.infer.annotation.ThreadConfined.ANY; import static com.facebook.infer.annotation.ThreadConfined.UI; import static com.facebook.react.fabric.FabricComponents.getFabricComponentName; import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getMaxSize; import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getMinSize; import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getYogaMeasureMode; import static com.facebook.react.fabric.mounting.LayoutMetricsConversions.getYogaSize; import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; import android.annotation.SuppressLint; import android.content.Context; import android.os.SystemClock; import android.view.View; import androidx.annotation.AnyThread; import androidx.annotation.GuardedBy; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import com.facebook.common.logging.FLog; import com.facebook.debug.holder.PrinterHolder; import com.facebook.debug.tags.ReactDebugOverlayTags; import com.facebook.infer.annotation.ThreadConfined; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.NativeMap; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactMarker; import com.facebook.react.bridge.ReactMarkerConstants; import com.facebook.react.bridge.ReactNoCrashSoftException; import com.facebook.react.bridge.ReactSoftException; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.RetryableMountingLayerException; import com.facebook.react.bridge.UIManager; import com.facebook.react.bridge.UIManagerListener; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.config.ReactFeatureFlags; import com.facebook.react.fabric.events.EventBeatManager; import com.facebook.react.fabric.events.EventEmitterWrapper; import com.facebook.react.fabric.events.FabricEventEmitter; import com.facebook.react.fabric.mounting.MountingManager; import com.facebook.react.fabric.mounting.mountitems.BatchMountItem; import com.facebook.react.fabric.mounting.mountitems.CreateMountItem; import com.facebook.react.fabric.mounting.mountitems.DeleteMountItem; import com.facebook.react.fabric.mounting.mountitems.DispatchCommandMountItem; import com.facebook.react.fabric.mounting.mountitems.DispatchIntCommandMountItem; import com.facebook.react.fabric.mounting.mountitems.DispatchStringCommandMountItem; import com.facebook.react.fabric.mounting.mountitems.InsertMountItem; import com.facebook.react.fabric.mounting.mountitems.MountItem; import com.facebook.react.fabric.mounting.mountitems.PreAllocateViewMountItem; import com.facebook.react.fabric.mounting.mountitems.RemoveDeleteMultiMountItem; import com.facebook.react.fabric.mounting.mountitems.RemoveMountItem; import com.facebook.react.fabric.mounting.mountitems.SendAccessibilityEvent; import com.facebook.react.fabric.mounting.mountitems.UpdateEventEmitterMountItem; import com.facebook.react.fabric.mounting.mountitems.UpdateLayoutMountItem; import com.facebook.react.fabric.mounting.mountitems.UpdatePaddingMountItem; import com.facebook.react.fabric.mounting.mountitems.UpdatePropsMountItem; import com.facebook.react.fabric.mounting.mountitems.UpdateStateMountItem; import com.facebook.react.modules.core.ReactChoreographer; import com.facebook.react.modules.i18nmanager.I18nUtil; import com.facebook.react.uimanager.ReactRoot; import com.facebook.react.uimanager.ReactRootViewTagGenerator; import com.facebook.react.uimanager.StateWrapper; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewManagerPropertyUpdater; import com.facebook.react.uimanager.ViewManagerRegistry; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.systrace.Systrace; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @SuppressLint("MissingNativeLoadLibrary") public class FabricUIManager implements UIManager, LifecycleEventListener { public static final String TAG = "FabricUIManager"; // The IS_DEVELOPMENT_ENVIRONMENT variable is used to log extra data when running fabric in a // development environment. DO NOT ENABLE THIS ON PRODUCTION OR YOU WILL BE FIRED! public static final boolean IS_DEVELOPMENT_ENVIRONMENT = false; public static final boolean ENABLE_FABRIC_LOGS = ReactFeatureFlags.enableFabricLogs || PrinterHolder.getPrinter() .shouldDisplayLogMessage(ReactDebugOverlayTags.FABRIC_UI_MANAGER); private static final int FRAME_TIME_MS = 16; private static final int MAX_TIME_IN_FRAME_FOR_NON_BATCHED_OPERATIONS_MS = 8; private static final int PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY = 250; static { FabricSoLoader.staticInit(); } @Nullable private Binding mBinding; @NonNull private final ReactApplicationContext mReactApplicationContext; @NonNull private final MountingManager mMountingManager; @NonNull private final EventDispatcher mEventDispatcher; @NonNull private final ConcurrentHashMap<Integer, ThemedReactContext> mReactContextForRootTag = new ConcurrentHashMap<>(); @NonNull private final EventBeatManager mEventBeatManager; @NonNull private final Object mViewCommandMountItemsLock = new Object(); @NonNull private final Object mMountItemsLock = new Object(); @NonNull private final Object mPreMountItemsLock = new Object(); private boolean mInDispatch = false; private int mReDispatchCounter = 0; @GuardedBy("mViewCommandMountItemsLock") @NonNull private List<DispatchCommandMountItem> mViewCommandMountItems = new ArrayList<>(); @NonNull private final CopyOnWriteArrayList<UIManagerListener> mListeners = new CopyOnWriteArrayList<>(); @GuardedBy("mMountItemsLock") @NonNull private List<MountItem> mMountItems = new ArrayList<>(); @GuardedBy("mPreMountItemsLock") @NonNull private ArrayDeque<PreAllocateViewMountItem> mPreMountItems = new ArrayDeque<>(PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY); @ThreadConfined(UI) @NonNull private final DispatchUIFrameCallback mDispatchUIFrameCallback; @ThreadConfined(UI) private int mLastExecutedMountItemSurfaceId = -1; @ThreadConfined(UI) private boolean mLastExecutedMountItemSurfaceIdActive = false; /** * This is used to keep track of whether or not the FabricUIManager has been destroyed. Once the * Catalyst instance is being destroyed, we should cease all operation here. */ private volatile boolean mDestroyed = false; private boolean mDriveCxxAnimations = false; private long mRunStartTime = 0l; private long mBatchedExecutionTime = 0l; private long mDispatchViewUpdatesTime = 0l; private long mCommitStartTime = 0l; private long mLayoutTime = 0l; private long mFinishTransactionTime = 0l; private long mFinishTransactionCPPTime = 0l; // C++ keeps track of commit numbers for telemetry purposes. We don't want to incur a JNI // round-trip cost just for this, so commits from C++ are numbered 0+ and synchronous commits // are 10k+. Since these are only used for perf tracking, it's unlikely for the number of commits // from C++ to exceed 9,999 and it should be obvious what's going on when analyzing performance. private int mCurrentSynchronousCommitNumber = 10000; public FabricUIManager( ReactApplicationContext reactContext, ViewManagerRegistry viewManagerRegistry, EventDispatcher eventDispatcher, EventBeatManager eventBeatManager) { mDispatchUIFrameCallback = new DispatchUIFrameCallback(reactContext); mReactApplicationContext = reactContext; mMountingManager = new MountingManager(viewManagerRegistry); mEventDispatcher = eventDispatcher; mEventBeatManager = eventBeatManager; mReactApplicationContext.addLifecycleEventListener(this); } // TODO (T47819352): Rename this to startSurface for consistency with xplat/iOS @Override @UiThread @ThreadConfined(UI) public <T extends View> int addRootView( final T rootView, final WritableMap initialProps, final @Nullable String initialUITemplate) { final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag(); ReactRoot reactRootView = (ReactRoot) rootView; // TODO T31905686: Combine with startSurface below ThemedReactContext reactContext = new ThemedReactContext( mReactApplicationContext, rootView.getContext(), reactRootView.getSurfaceID()); mMountingManager.addRootView(rootTag, rootView); String moduleName = reactRootView.getJSModuleName(); mReactContextForRootTag.put(rootTag, reactContext); if (ENABLE_FABRIC_LOGS) { FLog.d(TAG, "Starting surface for module: %s and reactTag: %d", moduleName, rootTag); } mBinding.startSurface(rootTag, moduleName, (NativeMap) initialProps); if (initialUITemplate != null) { mBinding.renderTemplateToSurface(rootTag, initialUITemplate); } return rootTag; } @Override @AnyThread @ThreadConfined(ANY) public <T extends View> int startSurface( final T rootView, final String moduleName, final WritableMap initialProps, int widthMeasureSpec, int heightMeasureSpec) { final int rootTag = ReactRootViewTagGenerator.getNextRootViewTag(); Context context = rootView.getContext(); ThemedReactContext reactContext = new ThemedReactContext(mReactApplicationContext, context, moduleName); if (ENABLE_FABRIC_LOGS) { FLog.d(TAG, "Starting surface for module: %s and reactTag: %d", moduleName, rootTag); } mMountingManager.addRootView(rootTag, rootView); mReactContextForRootTag.put(rootTag, reactContext); mBinding.startSurfaceWithConstraints( rootTag, moduleName, (NativeMap) initialProps, getMinSize(widthMeasureSpec), getMaxSize(widthMeasureSpec), getMinSize(heightMeasureSpec), getMaxSize(heightMeasureSpec), I18nUtil.getInstance().isRTL(context), I18nUtil.getInstance().doLeftAndRightSwapInRTL(context)); return rootTag; } /** Method called when an event has been dispatched on the C++ side. */ @DoNotStrip @SuppressWarnings("unused") public void onRequestEventBeat() { mEventDispatcher.dispatchAllEvents(); } @AnyThread @ThreadConfined(ANY) @Override public void stopSurface(int surfaceID) { mBinding.stopSurface(surfaceID); mReactContextForRootTag.remove(surfaceID); } @Override public void initialize() { mEventDispatcher.registerEventEmitter(FABRIC, new FabricEventEmitter(this)); mEventDispatcher.addBatchEventDispatchedListener(mEventBeatManager); } // This is called on the JS thread (see CatalystInstanceImpl). @Override @AnyThread @ThreadConfined(ANY) public void onCatalystInstanceDestroy() { FLog.i(TAG, "FabricUIManager.onCatalystInstanceDestroy"); if (mDestroyed) { ReactSoftException.logSoftException( FabricUIManager.TAG, new IllegalStateException("Cannot double-destroy FabricUIManager")); return; } mDestroyed = true; // This is not technically thread-safe, since it's read on the UI thread and written // here on the JS thread. We've marked it as volatile so that this writes to UI-thread // memory immediately. mDispatchUIFrameCallback.stop(); mEventDispatcher.removeBatchEventDispatchedListener(mEventBeatManager); mEventDispatcher.unregisterEventEmitter(FABRIC); // Remove lifecycle listeners (onHostResume, onHostPause) since the FabricUIManager is going // away. Then stop the mDispatchUIFrameCallback false will cause the choreographer // callbacks to stop firing. mReactApplicationContext.removeLifecycleEventListener(this); onHostPause(); // This is not technically thread-safe, since it's read on the UI thread and written // here on the JS thread. We've marked it as volatile so that this writes to UI-thread // memory immediately. mDispatchUIFrameCallback.stop(); // Stop all attached surfaces if (ReactFeatureFlags.enableFabricStopAllSurfacesOnTeardown) { FLog.e(TAG, "stop all attached surfaces"); for (int surfaceId : mReactContextForRootTag.keySet()) { FLog.e(TAG, "stop attached surface: " + surfaceId); stopSurface(surfaceId); } } mBinding.unregister(); mBinding = null; ViewManagerPropertyUpdater.clear(); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private void preallocateView( int rootTag, int reactTag, final String componentName, @Nullable ReadableMap props, @Nullable Object stateWrapper, boolean isLayoutable) { ThemedReactContext context = mReactContextForRootTag.get(rootTag); String component = getFabricComponentName(componentName); synchronized (mPreMountItemsLock) { mPreMountItems.add( new PreAllocateViewMountItem( context, rootTag, reactTag, component, props, (StateWrapper) stateWrapper, isLayoutable)); } } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem createMountItem( String componentName, @Nullable ReadableMap props, @Nullable Object stateWrapper, int reactRootTag, int reactTag, boolean isLayoutable) { String component = getFabricComponentName(componentName); ThemedReactContext reactContext = mReactContextForRootTag.get(reactRootTag); if (reactContext == null) { throw new IllegalArgumentException("Unable to find ReactContext for root: " + reactRootTag); } return new CreateMountItem( reactContext, reactRootTag, reactTag, component, props, (StateWrapper) stateWrapper, isLayoutable); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem removeMountItem(int reactTag, int parentReactTag, int index) { return new RemoveMountItem(reactTag, parentReactTag, index); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem insertMountItem(int reactTag, int parentReactTag, int index) { return new InsertMountItem(reactTag, parentReactTag, index); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem deleteMountItem(int reactTag) { return new DeleteMountItem(reactTag); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem removeDeleteMultiMountItem(int[] metadata) { return new RemoveDeleteMultiMountItem(metadata); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem updateLayoutMountItem( int reactTag, int x, int y, int width, int height, int layoutDirection) { return new UpdateLayoutMountItem(reactTag, x, y, width, height, layoutDirection); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem updatePaddingMountItem(int reactTag, int left, int top, int right, int bottom) { return new UpdatePaddingMountItem(reactTag, left, top, right, bottom); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem updatePropsMountItem(int reactTag, ReadableMap map) { return new UpdatePropsMountItem(reactTag, map); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem updateStateMountItem(int reactTag, @Nullable Object stateWrapper) { return new UpdateStateMountItem(reactTag, (StateWrapper) stateWrapper); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem updateEventEmitterMountItem(int reactTag, Object eventEmitter) { return new UpdateEventEmitterMountItem(reactTag, (EventEmitterWrapper) eventEmitter); } @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private MountItem createBatchMountItem( int rootTag, MountItem[] items, int size, int commitNumber) { return new BatchMountItem(rootTag, items, size, commitNumber); } @DoNotStrip @SuppressWarnings("unused") private long measure( int rootTag, String componentName, ReadableMap localData, ReadableMap props, ReadableMap state, float minWidth, float maxWidth, float minHeight, float maxHeight) { return measure( rootTag, componentName, localData, props, state, minWidth, maxWidth, minHeight, maxHeight, null); } @DoNotStrip @SuppressWarnings("unused") private long measure( int rootTag, String componentName, ReadableMap localData, ReadableMap props, ReadableMap state, float minWidth, float maxWidth, float minHeight, float maxHeight, @Nullable float[] attachmentsPositions) { ReactContext context = rootTag < 0 ? mReactApplicationContext : mReactContextForRootTag.get(rootTag); return mMountingManager.measure( context, componentName, localData, props, state, getYogaSize(minWidth, maxWidth), getYogaMeasureMode(minWidth, maxWidth), getYogaSize(minHeight, maxHeight), getYogaMeasureMode(minHeight, maxHeight), attachmentsPositions); } @Override @UiThread @ThreadConfined(UI) public void synchronouslyUpdateViewOnUIThread(int reactTag, @NonNull ReadableMap props) { UiThreadUtil.assertOnUiThread(); int commitNumber = mCurrentSynchronousCommitNumber++; // We are on the UI thread so this is safe to call. We try to flush any existing // mount instructions that are queued. tryDispatchMountItems(); try { ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_UPDATE_UI_MAIN_THREAD_START, null, commitNumber); if (ENABLE_FABRIC_LOGS) { FLog.d( TAG, "SynchronouslyUpdateViewOnUIThread for tag %d: %s", reactTag, (IS_DEVELOPMENT_ENVIRONMENT ? props.toHashMap().toString() : "<hidden>")); } updatePropsMountItem(reactTag, props).execute(mMountingManager); } catch (Exception ex) { // TODO T42943890: Fix animations in Fabric and remove this try/catch ReactSoftException.logSoftException( TAG, new ReactNoCrashSoftException( "Caught exception in synchronouslyUpdateViewOnUIThread", ex)); } finally { ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_UPDATE_UI_MAIN_THREAD_END, null, commitNumber); } } public void addUIManagerEventListener(UIManagerListener listener) { mListeners.add(listener); } public void removeUIManagerEventListener(UIManagerListener listener) { mListeners.remove(listener); } /** * This method enqueues UI operations directly to the UI thread. This might change in the future * to enforce execution order using {@link ReactChoreographer#CallbackType}. This method should * only be called as the result of a new tree being committed. */ @DoNotStrip @SuppressWarnings("unused") @AnyThread @ThreadConfined(ANY) private void scheduleMountItem( @NonNull final MountItem mountItem, int commitNumber, long commitStartTime, long diffStartTime, long diffEndTime, long layoutStartTime, long layoutEndTime, long finishTransactionStartTime, long finishTransactionEndTime) { // When Binding.cpp calls scheduleMountItems during a commit phase, it always calls with // a BatchMountItem. No other sites call into this with a BatchMountItem, and Binding.cpp only // calls scheduleMountItems with a BatchMountItem. boolean isBatchMountItem = mountItem instanceof BatchMountItem; boolean shouldSchedule = !(isBatchMountItem && ((BatchMountItem) mountItem).getSize() == 0); // In case of sync rendering, this could be called on the UI thread. Otherwise, // it should ~always be called on the JS thread. for (UIManagerListener listener : mListeners) { listener.didScheduleMountItems(this); } if (isBatchMountItem) { mCommitStartTime = commitStartTime; mLayoutTime = layoutEndTime - layoutStartTime; mFinishTransactionCPPTime = finishTransactionEndTime - finishTransactionStartTime; mFinishTransactionTime = SystemClock.uptimeMillis() - finishTransactionStartTime; mDispatchViewUpdatesTime = SystemClock.uptimeMillis(); } if (shouldSchedule) { synchronized (mMountItemsLock) { mMountItems.add(mountItem); } if (UiThreadUtil.isOnUiThread()) { // We only read these flags on the UI thread. tryDispatchMountItems(); } } // Post markers outside of lock and after sync mounting finishes its execution if (isBatchMountItem) { ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_COMMIT_START, null, commitNumber, commitStartTime); ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_FINISH_TRANSACTION_START, null, commitNumber, finishTransactionStartTime); ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_FINISH_TRANSACTION_END, null, commitNumber, finishTransactionEndTime); ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_DIFF_START, null, commitNumber, diffStartTime); ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_DIFF_END, null, commitNumber, diffEndTime); ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_LAYOUT_START, null, commitNumber, layoutStartTime); ReactMarker.logFabricMarker( ReactMarkerConstants.FABRIC_LAYOUT_END, null, commitNumber, layoutEndTime); ReactMarker.logFabricMarker(ReactMarkerConstants.FABRIC_COMMIT_END, null, commitNumber); } } @UiThread @ThreadConfined(UI) private void tryDispatchMountItems() { // If we're already dispatching, don't reenter. // Reentrance can potentially happen a lot on Android in Fabric because // `updateState` from the // mounting layer causes mount items to be dispatched synchronously. We want to 1) make sure // we don't reenter in those cases, but 2) still execute those queued instructions // synchronously. // This is a pretty blunt tool, but we might not have better options since we really don't want // to execute anything out-of-order. if (mInDispatch) { return; } final boolean didDispatchItems; try { didDispatchItems = dispatchMountItems(); } catch (Throwable e) { mReDispatchCounter = 0; throw e; } finally { // Clean up after running dispatchMountItems - even if an exception was thrown mInDispatch = false; } for (UIManagerListener listener : mListeners) { listener.didDispatchMountItems(this); } // Decide if we want to try reentering if (mReDispatchCounter < 10 && didDispatchItems) { // Executing twice in a row is normal. Only log after that point. if (mReDispatchCounter > 2) { ReactSoftException.logSoftException( TAG, new ReactNoCrashSoftException( "Re-dispatched " + mReDispatchCounter + " times. This indicates setState (?) is likely being called too many times during mounting.")); } mReDispatchCounter++; tryDispatchMountItems(); } mReDispatchCounter = 0; } @UiThread @ThreadConfined(UI) private List<DispatchCommandMountItem> getAndResetViewCommandMountItems() { if (!ReactFeatureFlags.allowEarlyViewCommandExecution) { return null; } synchronized (mViewCommandMountItemsLock) { List<DispatchCommandMountItem> result = mViewCommandMountItems; if (result.isEmpty()) { return null; } mViewCommandMountItems = new ArrayList<>(); return result; } } @UiThread @ThreadConfined(UI) private List<MountItem> getAndResetMountItems() { synchronized (mMountItemsLock) { List<MountItem> result = mMountItems; if (result.isEmpty()) { return null; } mMountItems = new ArrayList<>(); return result; } } private ArrayDeque<PreAllocateViewMountItem> getAndResetPreMountItems() { synchronized (mPreMountItemsLock) { ArrayDeque<PreAllocateViewMountItem> result = mPreMountItems; if (result.isEmpty()) { return null; } mPreMountItems = new ArrayDeque<>(PRE_MOUNT_ITEMS_INITIAL_SIZE_ARRAY); return result; } } /** * Check if a surfaceId is active and ready for MountItems to be executed against it. It is safe * and cheap to call this repeatedly because we expect many operations to be batched with the same * surfaceId in a row and we memoize the parameters and results. * * @param surfaceId * @param context * @return */ @UiThread @ThreadConfined(UI) private boolean surfaceActiveForExecution(int surfaceId, String context) { if (mLastExecutedMountItemSurfaceId != surfaceId) { mLastExecutedMountItemSurfaceId = surfaceId; mLastExecutedMountItemSurfaceIdActive = mReactContextForRootTag.get(surfaceId) != null; // If there are many MountItems with the same SurfaceId, we only // log a warning for the first one that is skipped. if (!mLastExecutedMountItemSurfaceIdActive) { ReactSoftException.logSoftException( TAG, new ReactNoCrashSoftException( "dispatchMountItems: skipping " + context + ", because surface not available: " + surfaceId)); } } return mLastExecutedMountItemSurfaceIdActive; } @UiThread @ThreadConfined(UI) /** Nothing should call this directly except for `tryDispatchMountItems`. */ private boolean dispatchMountItems() { if (mReDispatchCounter == 0) { mBatchedExecutionTime = 0; } mRunStartTime = SystemClock.uptimeMillis(); List<DispatchCommandMountItem> viewCommandMountItemsToDispatch = getAndResetViewCommandMountItems(); List<MountItem> mountItemsToDispatch = getAndResetMountItems(); if (mountItemsToDispatch == null && viewCommandMountItemsToDispatch == null) { return false; } // As an optimization, execute all ViewCommands first // This should be: // 1) Performant: ViewCommands are often a replacement for SetNativeProps, which we've always // wanted to be as "synchronous" as possible. // 2) Safer: ViewCommands are inherently disconnected from the tree commit/diff/mount process. // JS imperatively queues these commands. // If JS has queued a command, it's reasonable to assume that the more time passes, the more // likely it is that the view disappears. // Thus, by executing ViewCommands early, we should actually avoid a category of // errors/glitches. if (viewCommandMountItemsToDispatch != null) { Systrace.beginSection( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricUIManager::mountViews viewCommandMountItems to execute: " + viewCommandMountItemsToDispatch.size()); for (DispatchCommandMountItem command : viewCommandMountItemsToDispatch) { if (ENABLE_FABRIC_LOGS) { FLog.d(TAG, "dispatchMountItems: Executing viewCommandMountItem: " + command.toString()); } try { command.execute(mMountingManager); } catch (RetryableMountingLayerException e) { // If the exception is marked as Retryable, we retry the viewcommand exactly once, after // the current batch of mount items has finished executing. if (command.getRetries() == 0) { command.incrementRetries(); dispatchCommandMountItem(command); } else { // It's very common for commands to be executed on views that no longer exist - for // example, a blur event on TextInput being fired because of a navigation event away // from the current screen. If the exception is marked as Retryable, we log a soft // exception but never crash in debug. // It's not clear that logging this is even useful, because these events are very // common, mundane, and there's not much we can do about them currently. ReactSoftException.logSoftException( TAG, new ReactNoCrashSoftException( "Caught exception executing ViewCommand: " + command.toString(), e)); } } catch (Throwable e) { // Non-Retryable exceptions are logged as soft exceptions in prod, but crash in Debug. ReactSoftException.logSoftException( TAG, new RuntimeException( "Caught exception executing ViewCommand: " + command.toString(), e)); } } Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); } // If there are MountItems to dispatch, we make sure all the "pre mount items" are executed // first ArrayDeque<PreAllocateViewMountItem> mPreMountItemsToDispatch = getAndResetPreMountItems(); if (mPreMountItemsToDispatch != null) { Systrace.beginSection( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricUIManager::mountViews preMountItems to execute: " + mPreMountItemsToDispatch.size()); while (!mPreMountItemsToDispatch.isEmpty()) { PreAllocateViewMountItem mountItem = mPreMountItemsToDispatch.pollFirst(); if (surfaceActiveForExecution( mountItem.getRootTag(), "dispatchMountItems PreAllocateViewMountItem")) { mountItem.execute(mMountingManager); } } Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); } if (mountItemsToDispatch != null) { Systrace.beginSection( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricUIManager::mountViews mountItems to execute: " + mountItemsToDispatch.size()); long batchedExecutionStartTime = SystemClock.uptimeMillis(); for (MountItem mountItem : mountItemsToDispatch) { if (ENABLE_FABRIC_LOGS) { // If a MountItem description is split across multiple lines, it's because it's a compound // MountItem. Log each line separately. String[] mountItemLines = mountItem.toString().split("\n"); for (String m : mountItemLines) { FLog.d(TAG, "dispatchMountItems: Executing mountItem: " + m); } } // Make sure surface associated with this MountItem has been started, and not stopped. // TODO T68118357: clean up this logic and simplify this method overall if (mountItem instanceof BatchMountItem) { BatchMountItem batchMountItem = (BatchMountItem) mountItem; if (!surfaceActiveForExecution( batchMountItem.getRootTag(), "dispatchMountItems BatchMountItem")) { continue; } } // TODO: if early ViewCommand dispatch ships 100% as a feature, this can be removed. // This try/catch catches Retryable errors that can only be thrown by ViewCommands, which // won't be executed here in Early Dispatch mode. try { mountItem.execute(mMountingManager); } catch (RetryableMountingLayerException e) { // It's very common for commands to be executed on views that no longer exist - for // example, a blur event on TextInput being fired because of a navigation event away // from the current screen. If the exception is marked as Retryable, we log a soft // exception but never crash in debug. // It's not clear that logging this is even useful, because these events are very // common, mundane, and there's not much we can do about them currently. if (mountItem instanceof DispatchCommandMountItem) { ReactSoftException.logSoftException( TAG, new ReactNoCrashSoftException( "Caught exception executing retryable mounting layer instruction: " + mountItem.toString(), e)); } else { throw e; } } } mBatchedExecutionTime += SystemClock.uptimeMillis() - batchedExecutionStartTime; } Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); return true; } @UiThread @ThreadConfined(UI) private void dispatchPreMountItems(long frameTimeNanos) { Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricUIManager::premountViews"); // dispatchPreMountItems cannot be reentrant, but we want to prevent dispatchMountItems from // reentering during dispatchPreMountItems mInDispatch = true; try { while (true) { long timeLeftInFrame = FRAME_TIME_MS - ((System.nanoTime() - frameTimeNanos) / 1000000); if (timeLeftInFrame < MAX_TIME_IN_FRAME_FOR_NON_BATCHED_OPERATIONS_MS) { break; } PreAllocateViewMountItem preMountItemToDispatch; synchronized (mPreMountItemsLock) { if (mPreMountItems.isEmpty()) { break; } preMountItemToDispatch = mPreMountItems.pollFirst(); } if (surfaceActiveForExecution( preMountItemToDispatch.getRootTag(), "dispatchPreMountItems")) { preMountItemToDispatch.execute(mMountingManager); } } } finally { mInDispatch = false; } Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); } public void setBinding(Binding binding) { mBinding = binding; } /** * Updates the layout metrics of the root view based on the Measure specs received by parameters. */ @Override @UiThread @ThreadConfined(UI) public void updateRootLayoutSpecs( final int rootTag, final int widthMeasureSpec, final int heightMeasureSpec) { if (ENABLE_FABRIC_LOGS) { FLog.d(TAG, "Updating Root Layout Specs"); } ThemedReactContext reactContext = mReactContextForRootTag.get(rootTag); boolean isRTL = false; boolean doLeftAndRightSwapInRTL = false; if (reactContext != null) { isRTL = I18nUtil.getInstance().isRTL(reactContext); doLeftAndRightSwapInRTL = I18nUtil.getInstance().doLeftAndRightSwapInRTL(reactContext); } mBinding.setConstraints( rootTag, getMinSize(widthMeasureSpec), getMaxSize(widthMeasureSpec), getMinSize(heightMeasureSpec), getMaxSize(heightMeasureSpec), isRTL, doLeftAndRightSwapInRTL); } @Override public void receiveEvent(int reactTag, String eventName, @Nullable WritableMap params) { EventEmitterWrapper eventEmitter = mMountingManager.getEventEmitter(reactTag); if (eventEmitter == null) { // This can happen if the view has disappeared from the screen (because of async events) FLog.d(TAG, "Unable to invoke event: " + eventName + " for reactTag: " + reactTag); return; } eventEmitter.invoke(eventName, params); } @Override public void onHostResume() { ReactChoreographer.getInstance() .postFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback); } @Override @NonNull @SuppressWarnings("unchecked") public EventDispatcher getEventDispatcher() { return mEventDispatcher; } @Override public void onHostPause() { ReactChoreographer.getInstance() .removeFrameCallback(ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback); } @Override public void onHostDestroy() {} @Deprecated @Override @AnyThread @ThreadConfined(ANY) public void dispatchCommand( final int reactTag, final int commandId, @Nullable final ReadableArray commandArgs) { dispatchCommandMountItem(new DispatchIntCommandMountItem(reactTag, commandId, commandArgs)); } @Override @AnyThread @ThreadConfined(ANY) public void dispatchCommand( final int reactTag, final String commandId, @Nullable final ReadableArray commandArgs) { dispatchCommandMountItem(new DispatchStringCommandMountItem(reactTag, commandId, commandArgs)); } @AnyThread @ThreadConfined(ANY) private void dispatchCommandMountItem(DispatchCommandMountItem command) { if (ReactFeatureFlags.allowEarlyViewCommandExecution) { synchronized (mViewCommandMountItemsLock) { mViewCommandMountItems.add(command); } } else { synchronized (mMountItemsLock) { mMountItems.add(command); } } } @Override @AnyThread @ThreadConfined(ANY) public void sendAccessibilityEvent(int reactTag, int eventType) { synchronized (mMountItemsLock) { mMountItems.add(new SendAccessibilityEvent(reactTag, eventType)); } } /** * Set the JS responder for the view associated with the tags received as a parameter. * * @param reactTag React tag of the first parent of the view that is NOT virtual * @param initialReactTag React tag of the JS view that initiated the touch operation * @param blockNativeResponder If native responder should be blocked or not */ @DoNotStrip public void setJSResponder( final int reactTag, final int initialReactTag, final boolean blockNativeResponder) { synchronized (mMountItemsLock) { mMountItems.add( new MountItem() { @Override public void execute(MountingManager mountingManager) { mountingManager.setJSResponder(reactTag, initialReactTag, blockNativeResponder); } }); } } /** * Clears the JS Responder specified by {@link #setJSResponder(int, int, boolean)}. After this * method is called, all the touch events are going to be handled by JS. */ @DoNotStrip public void clearJSResponder() { synchronized (mMountItemsLock) { mMountItems.add( new MountItem() { @Override public void execute(MountingManager mountingManager) { mountingManager.clearJSResponder(); } }); } } @Override public void profileNextBatch() { // TODO T31905686: Remove this method and add support for multi-threading performance counters } // Called from Binding.cpp @DoNotStrip @AnyThread public void onAnimationStarted() { mDriveCxxAnimations = true; } // Called from Binding.cpp @DoNotStrip @AnyThread public void onAllAnimationsComplete() { mDriveCxxAnimations = false; } @Override public Map<String, Long> getPerformanceCounters() { HashMap<String, Long> performanceCounters = new HashMap<>(); performanceCounters.put("CommitStartTime", mCommitStartTime); performanceCounters.put("LayoutTime", mLayoutTime); performanceCounters.put("DispatchViewUpdatesTime", mDispatchViewUpdatesTime); performanceCounters.put("RunStartTime", mRunStartTime); performanceCounters.put("BatchedExecutionTime", mBatchedExecutionTime); performanceCounters.put("FinishFabricTransactionTime", mFinishTransactionTime); performanceCounters.put("FinishFabricTransactionCPPTime", mFinishTransactionCPPTime); return performanceCounters; } private class DispatchUIFrameCallback extends GuardedFrameCallback { private volatile boolean mIsMountingEnabled = true; private DispatchUIFrameCallback(@NonNull ReactContext reactContext) { super(reactContext); } @AnyThread void stop() { mIsMountingEnabled = false; } @Override @UiThread @ThreadConfined(UI) public void doFrameGuarded(long frameTimeNanos) { if (!mIsMountingEnabled || mDestroyed) { FLog.w(TAG, "Not flushing pending UI operations because of previously thrown Exception"); return; } // Drive any animations from C++. // There is a race condition here between getting/setting // `mDriveCxxAnimations` which shouldn't matter; it's safe to call // the mBinding method, unless mBinding has gone away. if (mDriveCxxAnimations && mBinding != null) { mBinding.driveCxxAnimations(); } try { dispatchPreMountItems(frameTimeNanos); tryDispatchMountItems(); } catch (Exception ex) { FLog.e(TAG, "Exception thrown when executing UIFrameGuarded", ex); stop(); throw ex; } finally { ReactChoreographer.getInstance() .postFrameCallback( ReactChoreographer.CallbackType.DISPATCH_UI, mDispatchUIFrameCallback); } } } }
package space.engine.simpleQueue.pool; import org.junit.Test; import space.engine.simpleQueue.ConcurrentLinkedSimpleQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; public class SimpleThreadPoolTest { @Test(timeout = 250L) public void testLifecycle() { SimpleThreadPool pool = new SimpleThreadPool(4, new ConcurrentLinkedSimpleQueue<>()); AtomicInteger counter = new AtomicInteger(); pool.executeAll(IntStream.range(0, 32).mapToObj(i -> counter::incrementAndGet)); pool.stop().awaitUninterrupted(); assertEquals(32, counter.get()); } @Test(expected = RejectedExecutionException.class) public void testRejectedExecution() { SimpleThreadPool pool = new SimpleThreadPool(1, new ConcurrentLinkedSimpleQueue<>()); pool.stop(); pool.execute(() -> { throw new RuntimeException("Should not be executed!"); }); } }
package com.ruiqin.mapdemo.constant; /** * Created by ruiqin.shen * 类说明:常量类 */ public class Constant { //登陆成功之后保存 public static final String SP_TOKEN = "token";//用户token,登录成功之后保存 public static final String SP_SECRETKEY = "secretKey";//用户token,登录成功之后保存 public static final String SP_MOBILENUM = "mobileNum";//用户手机号,登录成功之后保存 public static final String SP_GESTUREPASSWORD = "gesturePassword";//手势密码 public static final String CONST_SECRETKEY = "1e469f986f5d4991a83b95d4";//默认的秘钥值 public static final String CONST_CHARSET = "UTF-8"; public static final String PLATFORM = "2";//平台 public static final String CUSTOMER_SERVICE_PHONE = "020-29037882";//客服电话 public static final String WX_GZH = "baidaibao2017";//公众号 }
/* * Copyright 2013 MovingBlocks * * 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.terasology.benchmark.chunks.arrays; import com.google.protobuf.ByteString; import org.terasology.world.chunks.blockdata.TeraArray; import org.terasology.world.chunks.blockdata.TeraArray.SerializationHandler; import java.nio.ByteBuffer; public class BenchmarkTeraArraySerializeToByteString extends BenchmarkTeraArraySerialization { protected ByteBuffer buffer; @SuppressWarnings("rawtypes") public BenchmarkTeraArraySerializeToByteString(SerializationHandler handler, TeraArray array) { super(handler, array); } @Override public String getTitle() { return array.getClass().getSimpleName() + " serialization into ByteString"; } @Override public void setup() { buffer = ByteBuffer.allocate(BUFFER_SIZE); } @Override public void prerun() { } @SuppressWarnings("unchecked") @Override public void run() { handler.serialize(array, buffer); int length = buffer.position(); buffer.rewind(); final ByteString b = ByteString.copyFrom(buffer, length); buffer.rewind(); } @Override public void postrun() { } @Override public void finish(boolean aborted) { } }
/* * copyright (c) 2015ff IST GmbH Dresden, Germany - https://www.ist-software.com * * This software may be modified and distributed under the terms of the MIT license. */ package com.composum.pages.commons.service; import com.composum.pages.commons.model.ElementTypeFilter; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.jcr.RepositoryException; import java.util.List; /** * the service interface for Pages editing operations */ public interface EditService { /** * @return 'true' if the element can be a child of the container */ boolean isAllowedElement(@Nonnull ResourceResolver resolver, @Nonnull ResourceManager.ResourceReference container, @Nonnull ResourceManager.ResourceReference element); /** * Determines the list of potential target containers for a page content element. */ ResourceManager.ReferenceList filterTargetContainers(ResourceResolver resolver, ResourceManager.ReferenceList candidates, ResourceManager.ResourceReference element); /** * Determines the list of resource types (nodes of type 'cpp:Component') for any of the containers. * * @param resolver the requests resolver (session) * @param scope the search filter configuration * @param containers the set of designated container references * @param resourceTypePath return the component path instead of resource type if 'true' * @return the result of a component type query filtered by the filter object */ List<String> getAllowedElementTypes(@Nonnull ResourceResolver resolver, @Nullable ComponentManager.ComponentScope scope, @Nonnull ResourceManager.ReferenceList containers, boolean resourceTypePath); /** * Determines the list of resource types (nodes of type 'cpp:Component') which are accepted by the filter. * * @param resolver the requests resolver (session) * @param scope the search filter configuration * @param containers the set of designated container references * @param filter the filter instance (resource type pattern filter) * @param resourceTypePath return the component path instead of resource type if 'true' * @return the result of a component type query filtered by the filter object */ List<String> getAllowedElementTypes(@Nonnull ResourceResolver resolver, @Nullable ComponentManager.ComponentScope scope, @Nonnull ResourceManager.ReferenceList containers, @Nonnull ElementTypeFilter filter, boolean resourceTypePath); /** * Returns or creates and returns the resource addressed by a reference. * * @param resolver the resolver to use for resource resolving and creation * @param reference the path and type of the resource * @return the resource instance */ Resource getReferencedResource(ResourceResolver resolver, ResourceManager.ResourceReference reference) throws PersistenceException; /** * Inserts a new resource. * * @param resolver the resolver (session context) * @param resourceType the type of the new resource * @param target the target (the parent resource) of the move * @param before the designated sibling in an ordered target collection */ Resource insertElement(ResourceResolver resolver, String resourceType, ResourceManager.ResourceReference target, Resource before) throws RepositoryException, PersistenceException; /** * Moves an element and adopts all references to the moved resource or one of its children. * * @param resolver the resolver (session context) * @param changeRoot the root element for reference search and change * @param source the resource to move * @param targetParent the target (a reference to the parent resource) of the move * @param before the designated sibling in an ordered target collection * @param updatedReferrers output parameter: the List of referers found - these were changed and might need setting a last modification date * @return the new resource at the target path */ Resource moveElement(ResourceResolver resolver, Resource changeRoot, Resource source, ResourceManager.ResourceReference targetParent, Resource before, @Nonnull List<Resource> updatedReferrers) throws RepositoryException, PersistenceException; /** * Copies an element. * * @param resolver the resolver (session context) * @param source the resource to move * @param targetParent the target (a reference to the parent resource) of the move * @param before the designated sibling in an ordered target collection * @return the new resource at the target path */ Resource copyElement(ResourceResolver resolver, Resource source, ResourceManager.ResourceReference targetParent, Resource before) throws RepositoryException, PersistenceException; }
package com.ifast.common.component.oss.config; import com.ifast.common.component.oss.support.UploadServer; import com.ifast.common.component.oss.support.aliyun.AliyunOSSProperties; import com.ifast.common.component.oss.support.aliyun.AliyunUploadServer; import com.ifast.common.component.oss.support.local.LocalUploadProperties; import com.ifast.common.component.oss.support.local.LocalUploadServer; import com.ifast.common.component.oss.support.qiniu.QiNiuOSSProperties; import com.ifast.common.component.oss.support.qiniu.QiNiuUploadServer; import com.qiniu.common.Zone; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * <pre> * </pre> * <small> 2018/10/10 16:50 | Aron</small> */ @Configuration @EnableCaching @Slf4j public class OSSConfiguration { /** * 阿里云OSS上传 */ /* @Bean @ConditionalOnProperty(prefix="ifast.oss.aliyun", name="accessKeySecret") @ConditionalOnMissingBean(UploadServer.class) public UploadServer aliyunUploadServer(AliyunOSSProperties properties) { if(log.isDebugEnabled()){ log.debug("启用阿里云上传服务"); } return new AliyunUploadServer(properties); } */ /** * 七牛上传 */ /* @Bean @ConditionalOnProperty(prefix="ifast.oss.qiniu", name="accessKey") @ConditionalOnMissingBean(UploadServer.class) public UploadServer qiNiuUploadServer(QiNiuOSSProperties ossConfig) { if(log.isDebugEnabled()){ log.debug("启用七牛云上传服务"); } return new QiNiuUploadServer(ossConfig, Zone.zone2()); } */ /** * 本地上传(默认),需配合Nginx解析静态资源 */ @Bean @ConditionalOnProperty(prefix="ifast.oss.local", name="localPath") @ConditionalOnMissingBean(UploadServer.class) public UploadServer localUploadServer(LocalUploadProperties properties) { if(log.isDebugEnabled()){ log.debug("启用本地上传服务"); } return new LocalUploadServer(properties); } }
package cn.mutils.app; /** * BuildConfig of framework */ public class AppBuildConfig { public static boolean DEBUG = true; }
/* * 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.example.sharding.spring.boot.jpa; import org.apache.shardingsphere.example.core.api.ExampleExecuteTemplate; import org.apache.shardingsphere.example.core.api.service.ExampleService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import java.sql.SQLException; @ComponentScan("org.apache.shardingsphere.example.core.jpa") @EntityScan(basePackages = "org.apache.shardingsphere.example.core.jpa.entity") @SpringBootApplication(exclude = JtaAutoConfiguration.class) public class ShardingSpringBootJpaExample { public static void main(final String[] args) throws SQLException { try (ConfigurableApplicationContext applicationContext = SpringApplication.run(ShardingSpringBootJpaExample.class, args)) { ExampleExecuteTemplate.run(applicationContext.getBean(ExampleService.class)); } } }
package org.diplomatiq.diplomatiqbackend.utils.crypto.srp; import org.bouncycastle.crypto.agreement.srp.SRP6Client; import org.bouncycastle.crypto.agreement.srp.SRP6StandardGroups; import org.bouncycastle.crypto.agreement.srp.SRP6VerifierGenerator; import org.bouncycastle.crypto.digests.GeneralDigest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.params.SRP6GroupParameters; import org.springframework.stereotype.Component; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; @Component public class SRP6Factory { private static final SRP6GroupParameters SRP6_GROUP_PARAMETERS = SRP6StandardGroups.rfc5054_4096; private static final GeneralDigest SRP6_DIGEST = new SHA256Digest(); private static final SecureRandom SECURE_RANDOM = getSecureRandom(); private static SecureRandom getSecureRandom() { try { return SecureRandom.getInstanceStrong(); } catch (NoSuchAlgorithmException ex) { return new SecureRandom(); } } public RequestBoundaryCrossingSRP6Server getSrp6Server(BigInteger verifier) { RequestBoundaryCrossingSRP6Server srp6Server = new RequestBoundaryCrossingSRP6Server(); srp6Server.init(SRP6_GROUP_PARAMETERS, verifier, SRP6_DIGEST, SECURE_RANDOM); return srp6Server; } public SRP6Client getSrp6Client() { SRP6Client srp6Client = new SRP6Client(); srp6Client.init(SRP6_GROUP_PARAMETERS, SRP6_DIGEST, SECURE_RANDOM); return srp6Client; } public SRP6VerifierGenerator getSrp6VerifierGenerator() { SRP6VerifierGenerator srp6VerifierGenerator = new SRP6VerifierGenerator(); srp6VerifierGenerator.init(SRP6_GROUP_PARAMETERS, SRP6_DIGEST); return srp6VerifierGenerator; } }
package gov.ca.emsa.pulse.sequoia.domain; public class SequoiaLink { private String relation; private String url; public String getRelation() { return relation; } public void setRelation(String relation) { this.relation = relation; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
class Solution { // O(n^2) time O(n) space public int maxEnvelopes(int[][] envelopes) { if (envelopes.length == 0 || envelopes[0].length == 0) return 0; Arrays.sort(envelopes, (a, b) -> a[0] - b[0]); int[] dp = new int[envelopes.length]; int maxAns = 1; for (int i = 0; i < envelopes.length; i++) { dp[i] = 1; for (int j = 0; j < i; j++){ if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } maxAns = Math.max(maxAns, dp[i]); } return maxAns; } }
package com.stark.patterns.behavioral.chainofresponsibility; public enum RequestType { CONFERENCE, PURCHASE; }
/* * Copyright (c) 2011-2019, Qulice.com * All rights reserved. * * 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. 3) Neither the name of the Qulice.com 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 HOLDER 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 com.qulice.findbugs; import com.google.common.base.Joiner; import com.qulice.spi.Environment; import com.qulice.spi.ValidationException; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; /** * Test case for {@link FindBugsValidator}. * @since 0.3 */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class FindBugsValidatorTest { /** * FindbugsValidator can pass correct files with no exceptions. * @throws Exception If something wrong happens inside */ @Test public void passesCorrectFilesWithNoExceptions() throws Exception { final Environment env = new Environment.Mock() .withFile("src/main/java/Main.java", "class Main { int x = 0; }") .withDefaultClasspath(); new FindBugsValidator().validate(env); } /** * FindbugsValidator can report incorrectly added throws. * @throws Exception If something wrong happens inside */ @Disabled @org.junit.Test(expected = ValidationException.class) public void reportsIncorrectlyAddedThrows() throws Exception { final byte[] bytecode = new BytecodeMocker() .withSource( Joiner.on("\n").join( "package test;", "final class Main {", "public void foo() throws InterruptedException {", "System.out.println(\"test\");", "}", "}" ) ) .mock(); final Environment env = new Environment.Mock() .withFile("target/classes/Main.class", bytecode) .withDefaultClasspath(); new FindBugsValidator().validate(env); } /** * FindbugsValidator can ignore correct throws. * @throws Exception If something wrong happens inside */ @Test public void ignoresCorrectlyAddedThrows() throws Exception { final byte[] bytecode = new BytecodeMocker() .withSource( Joiner.on("\n").join( "package test;", "final class Main {", "public void foo() throws InterruptedException {", "Thread.sleep(1);", "}", "}" ) ) .mock(); final Environment env = new Environment.Mock() .withFile("target/classes/Main.class", bytecode) .withDefaultClasspath(); new FindBugsValidator().validate(env); } /** * FindbugsValidator throw exception for invalid file. * @throws Exception If something wrong happens inside */ @org.junit.Test(expected = ValidationException.class) public void throwsExceptionOnViolation() throws Exception { final byte[] bytecode = new BytecodeMocker() .withSource("class Foo { public Foo clone() { return this; } }") .mock(); final Environment env = new Environment.Mock() .withFile("target/classes/Foo.class", bytecode) .withDefaultClasspath(); new FindBugsValidator().validate(env); } /** * FindbugsValidator can exclude classes from check. * @throws Exception If something wrong happens inside */ @Test public void excludesIncorrectClassFormCheck() throws Exception { final byte[] bytecode = new BytecodeMocker() .withSource("class Foo { public Foo clone() { return this; } }") .mock(); final Environment env = new Environment.Mock() .withFile("target/classes/Foo.class", bytecode) .withExcludes("Foo") .withDefaultClasspath(); new FindBugsValidator().validate(env); } /** * FindbugsValidator can exclude several classes from check. * @throws Exception If something wrong happens inside */ @Test public void excludesSeveralIncorrectClassFromCheck() throws Exception { final byte[] bytecode = new BytecodeMocker() .withSource("class Foo { public Foo clone() { return this; } }") .mock(); final byte[] another = new BytecodeMocker() .withSource("class Bar { public Bar clone() { return this; } }") .mock(); final Environment env = new Environment.Mock() .withFile("target/classes/Foo.class", bytecode) .withFile("target/classes/Bar.class", another) .withExcludes("Foo,Bar") .withDefaultClasspath(); new FindBugsValidator().validate(env); } }
/**************************************************************** * 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.james.protocols.lmtp.core; import org.apache.james.protocols.smtp.SMTPSession; /** * {@link ReceivedDataLineFilter} which will add the Received header to the message * * */ public class ReceivedDataLineFilter extends org.apache.james.protocols.smtp.core.ReceivedDataLineFilter { private static final String SERVICE_TYPE = "LMTP"; /** * Always returns <code>LMTP</code> */ @Override protected String getServiceType(SMTPSession session, String heloMode) { return SERVICE_TYPE; } }
/* The MIT License (MIT) Copyright (c) 2015 Los Andes University 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 co.edu.uniandes.csw.bakery.tests; /** * * @generate */ public class Utils { public static final String apiPath = "api"; public static final String username = System.getenv("USERNAME_USER"); public static final String password = System.getenv("PASSWORD_USER"); }
package com.xebialabs.invoice.web.rest.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpHeaders; /** * Tests based on parsing algorithm in app/components/util/pagination-util.service.js * * @see PaginationUtil */ public class PaginationUtilUnitTest { @Test public void generatePaginationHttpHeadersTest() { String baseUrl = "/api/_search/example"; List<String> content = new ArrayList<>(); Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl); List<String> strHeaders = headers.get(HttpHeaders.LINK); assertNotNull(strHeaders); assertTrue(strHeaders.size() == 1); String headerData = strHeaders.get(0); assertTrue(headerData.split(",").length == 4); String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\"," + "</api/_search/example?page=5&size=50>; rel=\"prev\"," + "</api/_search/example?page=7&size=50>; rel=\"last\"," + "</api/_search/example?page=0&size=50>; rel=\"first\""; assertEquals(expectedData, headerData); List<String> xTotalCountHeaders = headers.get("X-Total-Count"); assertTrue(xTotalCountHeaders.size() == 1); assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L)); } }
package com.maryanto.dimas.example.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; @Data @AllArgsConstructor @NoArgsConstructor public class Payment { private String transactionId; private String stan; private String cardNumber; private BigDecimal amount; }
package com.brunodles.annotationprocessorhelper.test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by bruno on 14/01/17. */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface Annotation2 { }
/** * 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.gst.portfolio.shareproducts.service; import java.math.BigDecimal; import java.util.Map; import javax.persistence.PersistenceException; import org.apache.commons.lang.exception.ExceptionUtils; import com.gst.accounting.producttoaccountmapping.service.ProductToGLAccountMappingWritePlatformService; import com.gst.infrastructure.core.api.JsonCommand; import com.gst.infrastructure.core.data.CommandProcessingResult; import com.gst.infrastructure.core.data.CommandProcessingResultBuilder; import com.gst.infrastructure.core.exception.PlatformDataIntegrityException; import com.gst.infrastructure.core.serialization.FromJsonHelper; import com.gst.portfolio.shareproducts.constants.ShareProductApiConstants; import com.gst.portfolio.shareproducts.domain.ShareProduct; import com.gst.portfolio.shareproducts.domain.ShareProductDividendPayOutDetails; import com.gst.portfolio.shareproducts.domain.ShareProductDividentPayOutDetailsRepositoryWrapper; import com.gst.portfolio.shareproducts.domain.ShareProductRepositoryWrapper; import com.gst.portfolio.shareproducts.exception.DividentProcessingException; import com.gst.portfolio.shareproducts.serialization.ShareProductDataSerializer; import org.joda.time.LocalDate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import com.google.gson.JsonElement; @Service public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareProductWritePlatformService { private final ShareProductRepositoryWrapper repository; private final ShareProductDataSerializer serializer; private final FromJsonHelper fromApiJsonHelper; private final ShareProductDividentPayOutDetailsRepositoryWrapper shareProductDividentPayOutDetailsRepository; private final ShareProductDividendAssembler shareProductDividendAssembler; private final ProductToGLAccountMappingWritePlatformService accountMappingWritePlatformService; @Autowired public ShareProductWritePlatformServiceJpaRepositoryImpl(final ShareProductRepositoryWrapper repository, final ShareProductDataSerializer serializer, final FromJsonHelper fromApiJsonHelper, final ShareProductDividentPayOutDetailsRepositoryWrapper shareProductDividentPayOutDetailsRepositor, final ShareProductDividendAssembler shareProductDividendAssembler, final ProductToGLAccountMappingWritePlatformService accountMappingWritePlatformService) { this.repository = repository; this.serializer = serializer; this.fromApiJsonHelper = fromApiJsonHelper; this.shareProductDividentPayOutDetailsRepository = shareProductDividentPayOutDetailsRepositor; this.shareProductDividendAssembler = shareProductDividendAssembler; this.accountMappingWritePlatformService = accountMappingWritePlatformService; } @Override public CommandProcessingResult createShareProduct(JsonCommand jsonCommand) { try { ShareProduct product = this.serializer.validateAndCreate(jsonCommand); this.repository.save(product); // save accounting mappings this.accountMappingWritePlatformService.createShareProductToGLAccountMapping(product.getId(), jsonCommand); return new CommandProcessingResultBuilder() // .withCommandId(jsonCommand.commandId()) // .withEntityId(product.getId()) // .build(); }catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (PersistenceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(jsonCommand, throwable, dve); return CommandProcessingResult.empty(); } } @Override public CommandProcessingResult updateProduct(Long productId, JsonCommand jsonCommand) { try { ShareProduct product = this.repository.findOneWithNotFoundDetection(productId); final Map<String, Object> changes = this.serializer.validateAndUpdate(jsonCommand, product); // accounting related changes final boolean accountingTypeChanged = changes.containsKey(ShareProductApiConstants.accountingRuleParamName); final Map<String, Object> accountingMappingChanges = this.accountMappingWritePlatformService .updateShareProductToGLAccountMapping(product.getId(), jsonCommand, accountingTypeChanged, product.getAccountingType()); changes.putAll(accountingMappingChanges); if (!changes.isEmpty()) { this.repository.saveAndFlush(product); } return new CommandProcessingResultBuilder() // .withCommandId(jsonCommand.commandId()) // .withEntityId(productId) // .with(changes) // .build(); }catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); }catch (PersistenceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()) ; handleDataIntegrityIssues(jsonCommand, throwable, dve); return CommandProcessingResult.empty(); } } @Override public CommandProcessingResult createShareProductDividend(final Long productId, final JsonCommand jsonCommand) { try { this.serializer.validateDividendDetails(jsonCommand); JsonElement element = jsonCommand.parsedJson(); final LocalDate dividendPeriodStartDate = this.fromApiJsonHelper.extractLocalDateNamed( ShareProductApiConstants.dividendPeriodStartDateParamName, element); final LocalDate dividendPeriodEndDate = this.fromApiJsonHelper.extractLocalDateNamed( ShareProductApiConstants.dividendPeriodEndDateParamName, element); final BigDecimal dividendAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( ShareProductApiConstants.dividendAmountParamName, element); final ShareProductDividendPayOutDetails dividendPayOutDetails = this.shareProductDividendAssembler.calculateDividends( productId, dividendAmount, dividendPeriodStartDate, dividendPeriodEndDate); if (dividendPayOutDetails == null) { throw new DividentProcessingException("eligible.shares.not.found", "No eligible shares for creating dividends"); } this.shareProductDividentPayOutDetailsRepository.save(dividendPayOutDetails); return new CommandProcessingResultBuilder() // .withCommandId(jsonCommand.commandId()) // .withEntityId(productId) // .withSubEntityId(dividendPayOutDetails.getId())// .build(); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(dve); return CommandProcessingResult.empty(); } } @Override public CommandProcessingResult approveShareProductDividend(final Long PayOutDetailId) { try { ShareProductDividendPayOutDetails dividendPayOutDetails = this.shareProductDividentPayOutDetailsRepository .findOneWithNotFoundDetection(PayOutDetailId); if (dividendPayOutDetails.getStatus().isApproved()) { throw new DividentProcessingException("alreay.approved", "Can't approve already appoved dividends "); } dividendPayOutDetails.approveDividendPayout(); this.shareProductDividentPayOutDetailsRepository.save(dividendPayOutDetails); return new CommandProcessingResultBuilder() // .withEntityId(PayOutDetailId) // .build(); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(dve); return CommandProcessingResult.empty(); } } @Override public CommandProcessingResult deleteShareProductDividend(final Long PayOutDetailId) { try { ShareProductDividendPayOutDetails dividendPayOutDetails = this.shareProductDividentPayOutDetailsRepository .findOneWithNotFoundDetection(PayOutDetailId); if (dividendPayOutDetails.getStatus().isApproved()) { throw new DividentProcessingException("alreay.approved", "Can't delete already appoved dividends "); } this.shareProductDividentPayOutDetailsRepository.delete(dividendPayOutDetails); return new CommandProcessingResultBuilder() // .withEntityId(PayOutDetailId) // .build(); } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(dve); return CommandProcessingResult.empty(); } } private void handleDataIntegrityIssues(final Exception e) { throw new PlatformDataIntegrityException("error.msg.shareproduct.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); } private void handleDataIntegrityIssues(final JsonCommand command, final Throwable realCause, final Exception dve) { if (realCause.getMessage().contains("'name'")) { final String name = command.stringValueOfParameterNamed(ShareProductApiConstants.name_paramname); throw new PlatformDataIntegrityException("error.msg.shareproduct.duplicate.name", "Share Product with name `" + name + "` already exists", "name", name); } throw new PlatformDataIntegrityException("error.msg.shareproduct.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); } }
package com.mlcr.easy._326; /** * @program: MyLeetCodeRecorder * @description: https://leetcode-cn.com/problems/power-of-three/ * @author: 0range * @create: 2021-06-11 15:23 **/ public class Solution { public boolean isPowerOfThree(int n) { if (n < 1) { return false; } while (n > 1) { if (n % 3 != 0) { return false; } n /= 3; } return true; } }
/* * Copyright (c) 2015 Mikhail Sokolov * * 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 eu.binjr.common.xml.adapters; import java.time.LocalDate; import java.time.format.DateTimeFormatter; /** * {@code XmlAdapter} mapping JSR-310 {@code LocalDate} to ISO-8601 string * <p> * It uses {@link DateTimeFormatter#ISO_DATE} for parsing and serializing, * time-zone information ignored. * * @see LocalDate */ public class LocalDateXmlAdapter extends TemporalAccessorXmlAdapter<LocalDate> { public LocalDateXmlAdapter() { super(DateTimeFormatter.ISO_DATE, LocalDate::from); } }
package fi.seco.collections.collection; import java.util.Collection; import java.util.Comparator; public class BinaryHeap<T> extends ABinaryHeap<T> { private final Comparator<T> c; @Override protected boolean lessThan(T a, T b) { return c.compare(a, b) < 0; } public BinaryHeap(Collection<T> a, Comparator<T> c) { super(a, true); this.c = c; heapify(); } public BinaryHeap(int maxSize, Comparator<T> c) { super(maxSize); this.c = c; } public BinaryHeap(T[] a, Comparator<T> c) { super(a, true); this.c = c; heapify(); } }
package com.spacecowboy.fragmentarydemos.at; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import com.spacecowboy.fragmentarydemos.R; import java.util.ArrayList; import java.util.List; /** * @author: SpaceCowboy * @date: 2018/12/24 * @description: */ public class MyOnKeyListener implements View.OnKeyListener { private AtEditText editText; public MyOnKeyListener(AtEditText editText) { this.editText = editText; } @Override public boolean onKey(View view, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) { //当为删除键并且是按下动作时执行 String content = editText.getText().toString(); int selectionStart = editText.getSelectionStart(); int endIndex = 0; int startIndex; int deleteNum = 0; List<Integer> spanIndexes = new ArrayList<Integer>(); for (int i = 0; i < editText.getAtList().size(); i++) { String name = "@" + editText.getAtList().get(i).name; if ((startIndex = content.indexOf(name, endIndex)) != -1) { if (startIndex > selectionStart) break; // 如果开始索引值,大于光标位置,那么退出遍历 endIndex = startIndex + name.length(); deleteNum = i; spanIndexes.add(startIndex);//name 的开始索引,键值为偶数,从0开始 spanIndexes.add(startIndex + name.length()); //name 的结束索引,键值为奇数,从1开始 if (endIndex > selectionStart) break; // 如果结束索引值,大于光标位置,那么退出遍历 } } // spanIndexes 必须大于0 且 光标位置不能大于 结束索引位置 if (spanIndexes.size() > 0 && spanIndexes.get(spanIndexes.size() - 1) >= selectionStart) { editText.setText(changeTextColor(content.substring(0, spanIndexes.get(spanIndexes.size() - 2)) + content.substring(spanIndexes.get(spanIndexes.size() - 1)))); //字符串替换,删掉符合条件的字符串 editText.setSelection(spanIndexes.get(spanIndexes.size() - 2)); // 设置光标位置 editText.getAtList().remove(deleteNum); //删除对应实体 return true; } } return false; } private SpannableString changeTextColor(String sText) { int endIndex = 0; int startIndex = 0; List<Integer> spanIndexes = new ArrayList<Integer>(); for (int i = 0; i < editText.getAtList().size(); i++) { String tempname = "@" + editText.getAtList().get(i).name; if ((startIndex = sText.indexOf(tempname, endIndex)) != -1) { endIndex = startIndex + tempname.length(); spanIndexes.add(startIndex);//name 的开始索引,键值为偶数,从0开始 spanIndexes.add(startIndex + tempname.length()); //name 的结束索引,键值为奇数,从1开始 } } SpannableString spanText = new SpannableString(sText); if (spanIndexes != null && spanIndexes.size() != 0) { for (int i = 0; i < spanIndexes.size(); i++) { if (i % 2 == 0) { // 开始位置 startIndex = spanIndexes.get(i); } else { // 结束位置 spanText.setSpan(new ForegroundColorSpan(editText.getContext().getResources().getColor(R.color.colorPrimaryDark)), startIndex, spanIndexes.get(i), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } } return spanText; } }
/* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root * or https://opensource.org/licenses/MIT */ package utam.compiler.translator; import static com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_COMMENTS; import static utam.core.declarative.translator.UnitTestRunner.NONE; import static utam.core.declarative.translator.UnitTestRunner.validateUnitTestDirectory; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import utam.compiler.UtamCompilationError; import utam.compiler.translator.DefaultSourceConfiguration.SourceWithoutPackages; import utam.compiler.translator.DefaultSourceConfiguration.RecursiveScanner; import utam.compiler.translator.DefaultSourceConfiguration.ScannerConfig; import utam.core.declarative.translator.ProfileConfiguration; import utam.core.declarative.translator.TranslatorSourceConfig; import utam.core.declarative.translator.TranslatorTargetConfig; import utam.core.declarative.translator.UnitTestRunner; /** * JSON based config for UTAM compiler * * @author elizaveta.ivanova * @since 234 */ public class JsonCompilerConfig { static final String ERR_READING_COMPILER_CONFIG = "Error reading compiler config '%s'"; private final Module moduleConfig; private final String filePathsRoot; private static ObjectMapper getJsonCompilerMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enable(ALLOW_COMMENTS); // for compatibility with possible JS options - ignore unknown properties mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper; } public JsonCompilerConfig(File configFile, File compilerRoot) throws IOException { try { moduleConfig = getJsonCompilerMapper().readValue(configFile, Module.class); filePathsRoot = compilerRoot.toString(); } catch (IOException e) { throw new IOException(String.format(ERR_READING_COMPILER_CONFIG, configFile.toString()), e); } } public List<ProfileConfiguration> getConfiguredProfiles() { return moduleConfig.getConfiguredProfiles(); } public TranslatorTargetConfig getTargetConfig() { return moduleConfig.getTargetConfig(filePathsRoot); } public TranslatorSourceConfig getSourceConfig() { return moduleConfig.getSourceConfig(filePathsRoot); } public String getModuleName() { return moduleConfig.moduleName; } // for tests Module getModule() { return moduleConfig; } /** * JSON mapping that represents a Page Objects module with namespaces and profiles * * @author james.evans * @since 234 */ public static class Module { static final String DEFAULT_JSON_FILE_MASK_REGEX = "(.*)\\.utam\\.json$"; static final String ERR_DUPLICATE_PROFILE = "Profile '%s' is already configured"; private final List<Profile> profiles = new ArrayList<>(); final List<Namespace> namespaces = new ArrayList<>(); private final String pageObjectFileMaskRegex; private final String moduleName; private final String pageObjectsRootDirectory; private final String pageObjectsOutputDir; private final String resourcesOutputDir; private final String unitTestsOutputDir; private final UnitTestRunner unitTestRunnerType; /** * Initializes a new instance of the Module class. Instantiated via JSON deserialization. * * @param moduleName the arbitrary name of the module in the source repository * @param filesMaskRegex used by scanner to distinguish JSON with page objects * @param pageObjectsRootDirectory the directory in the source repository in which to * recursively search for UTAM Page Object declarative * description files * @param pageObjectsOutputDir target root folder for generated Page Objects * @param resourcesOutputDir target folder for generated resources like profiles * configurations * @param unitTestDirectory target root folder for generated unit tests * @param unitTestRunner type of the unit tests runner for unit tests generation, * default is NONE, can also be "testng" or "junit" * @param namespaces an array of Namespace objects describing the namespaces * within the module * @param profiles an array of Profile objects representing the profiles used in * JSON files of the module */ @JsonCreator public Module( @JsonProperty(value = "module") String moduleName, @JsonProperty(value = "pageObjectsFilesMask", defaultValue = DEFAULT_JSON_FILE_MASK_REGEX) String filesMaskRegex, @JsonProperty(value = "pageObjectsRootDir", required = true) String pageObjectsRootDirectory, @JsonProperty(value = "pageObjectsOutputDir", required = true) String pageObjectsOutputDir, @JsonProperty(value = "resourcesOutputDir", required = true) String resourcesOutputDir, @JsonProperty(value = "unitTestsOutputDir") final String unitTestDirectory, @JsonProperty(value = "unitTestsRunner", defaultValue = "NONE") UnitTestRunner unitTestRunner, @JsonProperty(value = "namespaces") List<Namespace> namespaces, @JsonProperty(value = "profiles") List<Profile> profiles ) { this.moduleName = Objects.requireNonNullElse(moduleName, ""); this.pageObjectsRootDirectory = pageObjectsRootDirectory; this.namespaces.addAll(Objects.requireNonNullElse(namespaces, new ArrayList<>())); setUniqueProfiles(profiles); this.pageObjectFileMaskRegex = Objects.requireNonNullElse(filesMaskRegex, DEFAULT_JSON_FILE_MASK_REGEX); this.pageObjectsOutputDir = pageObjectsOutputDir; this.resourcesOutputDir = resourcesOutputDir; this.unitTestsOutputDir = validateUnitTestDirectory(unitTestRunner, unitTestDirectory); this.unitTestRunnerType = Objects.requireNonNullElse(unitTestRunner, NONE); } void setUniqueProfiles(List<Profile> profiles) { if(profiles == null || profiles.isEmpty()) { return; } // check duplicates Set<String> configuredProfiles = new HashSet<>(); profiles.forEach(profile -> { if (configuredProfiles.contains(profile.name)) { throw new UtamCompilationError(String.format(ERR_DUPLICATE_PROFILE, profile.name)); } configuredProfiles.add(profile.name); }); this.profiles.addAll(profiles); } // used in tests Module(String moduleName, String filesMaskRegex, String pageObjectsRootDirectory) { this(moduleName, filesMaskRegex, pageObjectsRootDirectory, null, null, null, null, new ArrayList<>(), new ArrayList<>()); } // used in tests Module(String moduleName, String pageObjectsRootDirectory) { this(moduleName, null, pageObjectsRootDirectory, null, null, null, null, new ArrayList<>(), new ArrayList<>()); } public TranslatorSourceConfig getSourceConfig(String compilerRootFolderName) { if(namespaces.isEmpty()) { return new SourceWithoutPackages(compilerRootFolderName + pageObjectsRootDirectory, pageObjectFileMaskRegex); } RecursiveScanner scanner = new RecursiveScanner(compilerRootFolderName + pageObjectsRootDirectory); return new DefaultSourceConfiguration( new ScannerConfig(pageObjectFileMaskRegex, getPackagesMapping()), scanner); } public TranslatorTargetConfig getTargetConfig(String compilerRootFolderName) { return new DefaultTargetConfiguration( compilerRootFolderName + pageObjectsOutputDir, compilerRootFolderName + resourcesOutputDir, unitTestRunnerType, compilerRootFolderName + unitTestsOutputDir); } public Map<String, String> getPackagesMapping() { Map<String, String> packages = new HashMap<>(); namespaces.forEach(namespace -> namespace.setPackageMapping(packages)); return packages; } /** * Gets the name of the module. * * @return the name of the module */ public String getName() { return moduleName; } /** * Gets the directory in the source repository in which to recursively search for UTAM Page * Object declarative description files * * @return the directory in the source repository in which to recursively search for UTAM Page * Object declarative description files */ public String getPageObjectsRootDirectory() { return pageObjectsRootDirectory; } /** * get list of configured profiles * * @return list of profile configurations */ public List<ProfileConfiguration> getConfiguredProfiles() { List<ProfileConfiguration> all = new ArrayList<>(); profiles.forEach(p -> p.setConfiguredProfile(all)); return all; } /** * get list of raw profiles from config * * @return list of profiles from JSON */ public List<Profile> getRawProfiles() { return profiles; } /** * file mask to recognize JSON with a page object * * @return string with mask */ public String getPageObjectFileMaskRegex() { return pageObjectFileMaskRegex; } /** * target root folder for generated Page Objects * * @return string with file path */ public String getPageObjectsOutputDir() { return pageObjectsOutputDir; } /** * target root folder for generated resources * * @return string with file path */ public String getResourcesOutputDir() { return resourcesOutputDir; } /** * target root folder for generated Page Objects unit tests * * @return string with file path */ public String getUnitTestsOutputDir() { return unitTestsOutputDir; } /** * type of the unit tests to generate, one of: "none", "junit", "testng" * * @return string with file path */ public UnitTestRunner getUnitTestRunnerType() { return unitTestRunnerType; } } /** * JSON mapping that represents a profile configured for a UTAM Page Objects module * * @author james.evans * @since 234 */ public static class Profile { static final String ERR_DUPLICATE_PROFILE_DIFF_VALUES = "Profile '%s' is already configured with different values"; private final String name; private final String[] values; /** * Initializes a new instance of the Profile class. Instantiated via JSON deserialization. * * @param name the name of the profile * @param values the values of the profile */ @JsonCreator public Profile( @JsonProperty(value = "name") String name, @JsonProperty(value = "values") String[] values) { this.name = name; this.values = values; } public ProfileConfiguration getProfileConfiguration() { return new StringValueProfileConfig(name, values); } public void setConfiguredProfile(List<ProfileConfiguration> profiles) { ProfileConfiguration profileConfiguration = getProfileConfiguration(); for (ProfileConfiguration alreadyConfigured : profiles) { if (profileConfiguration.equals(alreadyConfigured)) { // same profile config already added return; } // check for profile with same name but different values if (alreadyConfigured.getPropertyKey().equals(profileConfiguration.getPropertyKey())) { throw new UtamCompilationError( String.format(ERR_DUPLICATE_PROFILE_DIFF_VALUES, alreadyConfigured.getPropertyKey())); } } profiles.add(profileConfiguration); } } /** * JSON mapping that represents a namespace within a UTAM Page Objects module * * @author james.evans */ public static class Namespace { static final String ERR_DUPLICATE_MAPPING = "Namespace config: value for '%s' is already configured as '%s'"; private final String typePrefix; private final String pathMatchRegex; /** * Initializes a new instance of the Namespace class. Instantiated via JSON deserialization. * * @param typePrefix type prefix * @param pathMatchRegex the mapped name used by the UTAM compiler to generate packages for the * generated Page Object source code */ @JsonCreator public Namespace( @JsonProperty(value = "typeMatch", required = true) String typePrefix, @JsonProperty(value = "pathMatch", required = true) String pathMatchRegex) { this.typePrefix = typePrefix; this.pathMatchRegex = pathMatchRegex; } /** * Gets the mapped name used by the UTAM compiler to generate packages for the generated Page * Object source code. public because used in distribution JSON config * * @return the mapped name used by the UTAM compiler to generate packages for the generated Page * Object source code */ public String getTypeMatch() { return typePrefix; } /** * public because can be used in distribution JSON config in a downstream project * * @return regex to use for scanning folders */ public String getPathMatch() { return pathMatchRegex; } /** * Key to create types to packages mapping, distribution setup can override this method * * @return key for package mapping */ protected String getPackageMappingKey() { return getTypeMatch(); } /** * Value to create types to packages mapping, distribution setup can override this method * * @return value for package mapping */ protected String getPackageMappingValue() { return getPathMatch(); } // setter ensures that namespaces are unique within a module void setPackageMapping(Map<String, String> packages) { String key = getPackageMappingKey(); String value = getPackageMappingValue(); if (packages.containsKey(key) && !packages.get(key).equals(value)) { throw new UtamCompilationError( String.format(ERR_DUPLICATE_MAPPING, key, packages.get(key))); } packages.put(key, value); } } }
package edu.mum.service; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import edu.mum.domain.Block; import edu.mum.domain.Course; import edu.mum.domain.Faculty; import edu.mum.repository.CourseRepository; import edu.mum.repository.FacultyRepository; @Service public class FacultyHelper { @Autowired private CourseRepository courseDao; @Autowired private FacultyRepository facultyDao; private List<Course> courses; private List<Faculty> faculties; private Course FPP = new Course(); private Course MPP = new Course(); public void assignCourseAndFaculty(Block block) { courses = (List<Course>) courseDao.findAll(); faculties = (List<Faculty>) facultyDao.findAll(); for (int i = 0; i < courses.size(); i++) { if (courses.get(i).getCourseName().equalsIgnoreCase("FPP")) this.FPP = courses.get(i); if (courses.get(i).getCourseName().equalsIgnoreCase("MPP")) this.MPP = courses.get(i); } Map<Faculty, Course> facultyCourseMap = new HashMap<>(); if (block.getBlockOrder() > 1) { List<Course> choosen = getCourse(block.getBlockOrder(), block.getSections().size(), (int) (Math.floor(block.getEntry().getNumOfFpp()) / 25)); if (block.getBlockOrder() == 2) { for (int i = 0; i < Math.floor(block.getEntry().getNumOfFpp()) / 25; i++) { choosen.add(this.MPP); } } facultyCourseMap = getFaculty(choosen, block.getBlockOrder(), block.getSections().size()); } else if (block.getBlockOrder() == 1) { facultyCourseMap = getFirstBlockFaculty((int) Math.floor(block.getEntry().getNumOfFpp() / 25), (int) Math.floor(block.getEntry().getNumOfMpp() / 25)); } int cnt = 0; for (Faculty key : facultyCourseMap.keySet()) { block.getSections().get(cnt).setCourse(facultyCourseMap.get(key)); block.getSections().get(cnt).setFaculty(key); cnt++; if (block.getSections().size() == cnt) break; } for (Faculty key : facultyCourseMap.keySet()) { for (int i = 0; i < block.getSections().size(); i++) { if (block.getSections().get(i).getCourse() == null) { block.getSections().get(i).setCourse(facultyCourseMap.get(key)); block.getSections().get(i).setFaculty(new Faculty("UNSTAFFED")); break; } } } } private List<Course> getCourse(long blkId, int noSection, int numOfFpp) { List<Course> selected = new ArrayList<>(); if (blkId == 2) { selected.addAll(firstElective(noSection - numOfFpp)); for (Course c : selected) { System.out.println("=======> mpp course check" + c.getCourseName()); } } else if (blkId == 3) { selected.addAll(firstElective((int) Math.round(noSection / 2))); selected.addAll(get500Courses(noSection - (int) Math.round(noSection / 2))); } else if (blkId > 3) { selected.addAll(get500Courses((int) Math.round(noSection / 1.5))); selected.addAll(get400Courses(noSection - (int) Math.round(noSection / 1.5))); } return selected; } private List<Course> firstElective(int noSection) { List<Course> selected = new ArrayList<>(); courses.stream().filter(c -> c.getIsPreReq()).filter(c -> (c.getCourseCode() > 400 && c.getCourseCode() < 500)) .filter(c -> { if (c.getCourseName().equalsIgnoreCase("MPP")) return false; else return true; }).forEach(selected::add); if (selected.size() > noSection) { for (int i = 0; i < (selected.size() - noSection); i++) { selected.remove(i); } } else { for (int i = 0, j = 0; i < courses.size() && j < (noSection - selected.size()); i++) { if (courses.get(i).getCourseCode() > 400 && courses.get(i).getCourseCode() < 500 && (!(courses.get(i).getCourseName().equalsIgnoreCase("MPP"))) && !selected.contains(courses.get(i))) { selected.add(courses.get(i)); j++; } } } return selected; } private HashSet<Course> get500Courses(int number) { List<Course> course500 = courses.stream().filter(c -> c.getCourseCode() > 500).collect(Collectors.toList()); HashSet<Course> choosen = new HashSet<>(); Random rand = new Random(); // int j = 0; for (; choosen.size() < number;) { choosen.add(course500.get(rand.nextInt(course500.size()))); // choosen.add(course500.get(j)); // j++; } return choosen; } private HashSet<Course> get400Courses(int number) { List<Course> course400 = courses.stream().filter(c -> c.getCourseCode() < 500 && c.getCourseCode() > 400) .filter(c -> !c.getCourseName().equalsIgnoreCase("MPP")).collect(Collectors.toList()); HashSet<Course> choosen = new HashSet<>(); Random rand = new Random(); // int i = 0; for (; choosen.size() < number;) { choosen.add(course400.get(rand.nextInt(course400.size()))); // choosen.add(course400.get(i)); // i++; } return choosen; } private Map<Faculty, Course> getFaculty(List<Course> selected, int blkId, int noFpp) { Map<Faculty, Course> map = new HashMap<>(); selected.forEach(c -> { for (int j = 0; j < faculties.size(); j++) { if (faculties.get(j).getCourse().contains(c) /* && faculties.get(j).aet check availability also */) { if (!map.containsKey(faculties.get(j)) && !map.containsValue(c) || !map.containsKey(faculties.get(j)) && c.getCourseName().equalsIgnoreCase("MPP")) map.put(faculties.get(j), c); } } }); int k = map.size(); Map<Faculty, Course> mapR = new HashMap<>(); for (Faculty key : map.keySet()) { if (map.get(key).getCourseName().equalsIgnoreCase("MPP") && k > noFpp) { k--; mapR.put(key, map.get(key)); System.out.println("=====>Mpp checked" + k); } } mapR.keySet().forEach(c -> map.remove(c, mapR.get(c))); return map; } private Map<Faculty, Course> getFirstBlockFaculty(int fppNo, int mppNo) { System.out.println("====== facultyHelper " + this.MPP.getCourseName()); Map<Faculty, Course> map = new HashMap<>(); List<Faculty> mppFaculty = faculties.stream().filter(f -> { for (int i = 0; i < f.getCourse().size(); i++) { if (f.getCourse().get(i).getCourseName().equalsIgnoreCase("MPP")) { return true; } } return false; }).collect(Collectors.toList()); List<Faculty> fppFaculty = faculties.stream().filter(f -> { for (int i = 0; i < f.getCourse().size(); i++) { if (f.getCourse().get(i).getCourseName().equalsIgnoreCase("FPP")) { return true; } } return false; }).collect(Collectors.toList()); Random rand = new Random(); // System.out.println("====== facultyHelper1 "+this.MPP.getCourseName()); for (int i = 0; i < mppNo; i++) { if (map.size() < mppNo) { map.put(mppFaculty.get(rand.nextInt(mppFaculty.size())), this.MPP); System.out.println("====== facultyHelper1 " + this.MPP.getCourseName()); } } for (Faculty c : map.keySet()) { System.out.println("==== mapp " + c.getUserProfile().getFirstName() + " " + map.get(c).getCourseName()); } for (int i = 0; i < fppNo; i++) { Faculty f = fppFaculty.get(rand.nextInt(fppFaculty.size())); if (!map.containsKey(f) && map.size()<(mppNo + fppNo)) { map.put((f), this.FPP); // System.out.println("====== facultyHelper2 " + this.FPP.getCourseName()); } } for (Faculty c : map.keySet()) { System.out.println("==== fpp " + c.getUserProfile().getFirstName() + " " + map.get(c).getCourseName()); } return map; } }
package com.verygood.security.larky.modules.x509; import org.bouncycastle.asn1.x509.KeyUsage; /** * Enumeration of bits used in key usage extension field */ public enum X509KeyUsage { /** * Digital signature * Binary: 10000000 * Hex: 0x80 * Dec: 128 * */ DIGITAL_SIGNATURE(KeyUsage.digitalSignature, "digitalSignature"), /** * Non repudiation * Binary: 1000000 * Hex: 0x40 * Dec: 64 * */ NON_REPUDIATION(KeyUsage.nonRepudiation, "nonRepudiation"), /** * Key encipherment * Binary: 100000 * Hex: 0x20 * Dec: 32 * */ KEY_ENCIPHERMENT(KeyUsage.keyEncipherment, "keyEncipherment"), /** * Data encipherment * Binary: 10000 * Hex: 0x10 * Dec: 16 * */ DATA_ENCIPHERMENT(KeyUsage.dataEncipherment, "dataEncipherment"), /** * Key agreement * Binary: 100 * Hex: 0x08 * Dec: 8 * */ KEY_AGREEMENT(KeyUsage.keyAgreement, "keyAgreement"), /** * Certificate signing * Binary: 100 * Hex: 0x04 * Dec: 4 * */ KEY_CERTIFICATE_SIGNING(KeyUsage.keyCertSign, "keyCertSign"), /** * CRL signing * Binary: 10 * Hex: 0x02 * Dec: 2 * */ CRL_SIGNING(KeyUsage.cRLSign, "crlSign"), /** * Encipher only * Binary: 1 * Hex: 0x01 * Dec: 1 * */ ENCIPHER_ONLY(KeyUsage.encipherOnly, "encipherOnly"), /** * Decipherment only * Binary: 1000000000000000 * Hex: 0x8000 * Dec: 32768 * */ DECIPHERMENT_ONLY(KeyUsage.decipherOnly, "decipherOnly"); private final int bit; private final String name; X509KeyUsage(int bit, String name) { this.bit = bit; this.name = name; } /** * Gets the key usage bit as an integer. * * @return The key usage bit as an integer. */ public int usageBit() { return bit; } /** * Gets the name of the key usage bit. * * @return The name of the key usage bit */ public String getName() { return name; } /** * Gets the key usage by name. * * @param name Key Usage Bit Name * @return X509KeyUsage with given name. * * @throws IllegalArgumentException If no X509KeyUsage with given name exists. */ public static X509KeyUsage fromName(final String name) { try { return X509KeyUsage.valueOf(X509KeyUsage.class, name); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid X509KeyUsage name: " + name); } } }
package com.aimissu.ptt.presenter; import com.aimissu.basemvp.mvp.BasePresenter; import com.aimissu.ptt.view.IOtherView; /** */ public class OtherPresenter extends BasePresenter<IOtherView> implements IOtherPresenter { public OtherPresenter(IOtherView baseView) { super(baseView); } }
/* * 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.ignite.internal.processors.cache.distributed; import org.apache.ignite.cache.CacheAtomicityMode; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; /** * */ public class CacheTxLoadingConcurrentGridStartSelfTestAllowOverwrite extends CacheLoadingConcurrentGridStartSelfTestAllowOverwrite { /** {@inheritDoc} */ @Override protected CacheAtomicityMode atomicityMode() { return TRANSACTIONAL; } }
package cn.leon.rocketmq; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RocketmqApplication { public static void main(String[] args) { SpringApplication.run(RocketmqApplication.class, args); } }
/* * 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.streampipes.connect.config; public class ConfigKeys { final static String KAFKA_HOST = "SP_KAFKA_HOST"; final static String KAFKA_PORT = "SP_KAFKA_PORT"; final static String CONNECT_CONTAINER_WORKER_HOST = "SP_CONNECT_CONTAINER_WORKER_HOST"; final static String CONNECT_CONTAINER_WORKER_PORT = "SP_CONNECT_CONTAINER_WORKER_PORT"; final static String CONNECT_CONTAINER_MASTER_HOST = "SP_CONNECT_CONTAINER_MASTER_HOST"; final static String CONNECT_CONTAINER_MASTER_PORT = "SP_CONNECT_CONTAINER_MASTER_PORT"; }
package com.mersocarlin.androidrest.domain.model; import java.util.Date; public class Person { public int id; public String name; public String email; public Date createdAt; public String homePhone; public String mobilePhone; public String workPhone; public Person() { this.createdAt = new Date(); } @Override public String toString() { return String.format("\nName: %s, email: %s, homePhone: %s, mobilePhone: %s, workPhone: %s, createdAt: %s", this.name, this.email, this.homePhone, this.mobilePhone, this.workPhone, this.createdAt); } }
package com.mycompany.product; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.mycompany.product.dao.ProductRepository; import com.mycompany.product.entity.Product; import com.mycompany.product.exception.BadRequestException; @RestController public class ProductService { @Autowired ProductRepository prodRepo ; @RequestMapping(value="/product/{id}", method = RequestMethod.GET ) Product getProduct(@PathVariable("id") int id) { Product prod = prodRepo.findOne(id); if (prod == null) throw new BadRequestException(BadRequestException.ID_NOT_FOUND, "No product for id " + id) ; else return prod ; } @RequestMapping("/products") List<Product> getProductsForCategory(@RequestParam("id") int id) { return prodRepo.findByCatId(id); } @RequestMapping(value="/product/{id}", method = RequestMethod.PUT) Product updateProduct(@PathVariable("id") int id, @RequestBody Product product) { // First fetch an existing product and then modify it. Product existingProduct = prodRepo.findOne(id); if (existingProduct == null) { String errMsg = "Product Not found with code " + id ; throw new BadRequestException(BadRequestException.ID_NOT_FOUND, errMsg); } // Now update it back existingProduct.setCatId(product.getCatId()); existingProduct.setName(product.getName()); Product savedProduct = prodRepo.save(existingProduct) ; // Return the updated product return savedProduct ; } @RequestMapping(value="/product", method = RequestMethod.POST) Product insertProduct(@RequestBody Product product) { Product savedProduct = prodRepo.save(product) ; return savedProduct ; } @RequestMapping(value="/product/{id}", method = RequestMethod.DELETE) Product deleteProduct(@PathVariable("id") int id) { // First fetch an existing product and then delete it. Product existingProduct = prodRepo.findOne(id); if (existingProduct == null) { String errMsg = "Product Not found with code " + id ; throw new BadRequestException(BadRequestException.ID_NOT_FOUND, errMsg); } // Return the deleted product prodRepo.delete(existingProduct); return existingProduct ; } }
package tasks.eshop.repositories; import tasks.eshop.model.OrderItems; import org.springframework.data.repository.CrudRepository; /** * @author Vadym Stroiu * @created on 12.09.2021 */ public interface OrderItemsRepository extends CrudRepository<OrderItems, Integer> { }
package com.supos.cloud.provider.consumer; import com.supos.cloud.JacksonUtil; import com.supos.cloud.core.mq.MqMessage; import com.supos.cloud.provider.model.dto.PcSendEmailRequest; import com.supos.cloud.provider.service.OptSendMailService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Set; /** * The class Opt send email topic consumer. * * @author walkman */ @Slf4j @Service public class OptSendEmailTopicConsumer { @Resource private OptSendMailService optSendMailService; /** * Handler send email topic. * * @param body the body * @param topicName the topic name * @param tags the tags * @param keys the keys */ public void handlerSendEmailTopic(String body, String topicName, String tags, String keys) { MqMessage.checkMessage(body, keys, topicName); PcSendEmailRequest request; try { request = JacksonUtil.parseJson(body, PcSendEmailRequest.class); } catch (Exception e) { log.error("发送短信MQ出现异常={}", e.getMessage(), e); throw new IllegalArgumentException("处理MQ信息,JSON转换异常"); } String subject = request.getSubject(); String text = request.getText(); Set<String> to = request.getTo(); optSendMailService.sendTemplateMail(subject, text, to); } }
package com.b.c.j; import com.b.c.e; import java.util.HashMap; public class b extends com.b.c.b { protected static final HashMap<Integer, String> e = new HashMap(); static { e.put(Integer.valueOf(5), "Extension Code"); } public b() { setDescriptor(new a(this)); } protected HashMap<Integer, String> a() { return e; } public int getExtensionCode() throws e { return getInt(5); } public String getName() { return "JFXX"; } } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/b/c/j/b.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.javascript.rhino.jstype.JSTypeNative.GLOBAL_THIS; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.javascript.jscomp.CodingConvention.SubclassRelationship; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.StaticSourceFile; import com.google.javascript.rhino.StaticSymbolTable; import com.google.javascript.rhino.TokenStream; import com.google.javascript.rhino.TypeI; import com.google.javascript.rhino.jstype.StaticTypedRef; import com.google.javascript.rhino.jstype.StaticTypedScope; import com.google.javascript.rhino.jstype.StaticTypedSlot; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.annotation.Nullable; /** * Builds a global namespace of all the objects and their properties in * the global scope. Also builds an index of all the references to those names. * * @author nicksantos@google.com (Nick Santos) */ class GlobalNamespace implements StaticTypedScope<TypeI>, StaticSymbolTable<GlobalNamespace.Name, GlobalNamespace.Ref> { private final AbstractCompiler compiler; private final Node root; private final Node externsRoot; private boolean inExterns; private Scope externsScope; private boolean generated = false; /** * Each reference has an index in post-order. * Notice that some nodes are represented by 2 Ref objects, so * this index is not necessarily unique. */ private int currentPreOrderIndex = 0; /** Global namespace tree */ private final List<Name> globalNames = new ArrayList<>(); /** Maps names (e.g. "a.b.c") to nodes in the global namespace tree */ private final Map<String, Name> nameMap = new HashMap<>(); /** * Creates an instance that may emit warnings when building the namespace. * * @param compiler The AbstractCompiler, for reporting code changes * @param root The root of the rest of the code to build a namespace for. */ GlobalNamespace(AbstractCompiler compiler, Node root) { this(compiler, null, root); } /** * Creates an instance that may emit warnings when building the namespace. * * @param compiler The AbstractCompiler, for reporting code changes * @param externsRoot The root of the externs to build a namespace for. If * this is null, externs and properties defined on extern types will not * be included in the global namespace. If non-null, it allows * user-defined function on extern types to be included in the global * namespace. E.g. String.foo. * @param root The root of the rest of the code to build a namespace for. */ GlobalNamespace(AbstractCompiler compiler, Node externsRoot, Node root) { this.compiler = compiler; this.externsRoot = externsRoot; this.root = root; } boolean hasExternsRoot() { return externsRoot != null; } @Override public Node getRootNode() { return root.getParent(); } @Override public StaticTypedScope<TypeI> getParentScope() { return null; } @Override public Name getSlot(String name) { return getOwnSlot(name); } @Override public Name getOwnSlot(String name) { ensureGenerated(); return nameMap.get(name); } @Override public TypeI getTypeOfThis() { return compiler.getTypeIRegistry().getNativeObjectType(GLOBAL_THIS); } @Override public Iterable<Ref> getReferences(Name slot) { ensureGenerated(); return Collections.unmodifiableList(slot.getRefs()); } @Override public StaticTypedScope<TypeI> getScope(Name slot) { return this; } @Override public Iterable<Name> getAllSymbols() { ensureGenerated(); return Collections.unmodifiableCollection(getNameIndex().values()); } private void ensureGenerated() { if (!generated) { process(); } } /** * Gets a list of the roots of the forest of the global names, where the * roots are the top-level names. */ List<Name> getNameForest() { ensureGenerated(); return globalNames; } /** * Gets an index of all the global names, indexed by full qualified name * (as in "a", "a.b.c", etc.). */ Map<String, Name> getNameIndex() { ensureGenerated(); return nameMap; } /** * A simple data class that contains the information necessary to inspect * a node for changes to the global namespace. */ static class AstChange { final JSModule module; final Scope scope; final Node node; AstChange(JSModule module, Scope scope, Node node) { this.module = module; this.scope = scope; this.node = node; } @Override public boolean equals(Object obj) { checkState(obj instanceof AstChange); AstChange other = (AstChange) obj; return Objects.equals(this.module, other.module) && Objects.equals(this.scope, other.scope) && Objects.equals(this.node, other.node); } @Override public int hashCode() { return Objects.hash(this.module, this.scope, this.node); } } /** * If the client adds new nodes to the AST, scan these new nodes * to see if they've added any references to the global namespace. * @param newNodes New nodes to check. */ void scanNewNodes(Set<AstChange> newNodes) { BuildGlobalNamespace builder = new BuildGlobalNamespace(); for (AstChange info : newNodes) { if (!info.node.isQualifiedName() && !NodeUtil.isObjectLitKey(info.node)) { continue; } scanFromNode(builder, info.module, info.scope, info.node); } } private void scanFromNode( BuildGlobalNamespace builder, JSModule module, Scope scope, Node n) { // Check affected parent nodes first. if (n.isName() || n.isGetProp()) { scanFromNode(builder, module, scope, n.getParent()); } builder.collect(module, scope, n); } /** * Builds the namespace lazily. */ private void process() { if (hasExternsRoot()) { inExterns = true; NodeTraversal.traverseEs6(compiler, externsRoot, new BuildGlobalNamespace()); } inExterns = false; NodeTraversal.traverseEs6(compiler, root, new BuildGlobalNamespace()); generated = true; externsScope = null; } /** * Determines whether a name reference in a particular scope is a global name * reference. * * @param name A variable or property name (e.g. "a" or "a.b.c.d") * @param s The scope in which the name is referenced * @return Whether the name reference is a global name reference */ private boolean isGlobalNameReference(String name, Scope s) { String topVarName = getTopVarName(name); return isGlobalVarReference(topVarName, s); } /** * Gets the top variable name from a possibly namespaced name. * * @param name A variable or qualified property name (e.g. "a" or "a.b.c.d") * @return The top variable name (e.g. "a") */ private static String getTopVarName(String name) { int firstDotIndex = name.indexOf('.'); return firstDotIndex == -1 ? name : name.substring(0, firstDotIndex); } /** * Determines whether a variable name reference in a particular scope is a * global variable reference. * * @param name A variable name (e.g. "a") * @param s The scope in which the name is referenced * @return Whether the name reference is a global variable reference */ private boolean isGlobalVarReference(String name, Scope s) { Var v = s.getVar(name); if (v == null && externsScope != null) { v = externsScope.getVar(name); } return v != null && !v.isLocal(); } // ------------------------------------------------------------------------- /** Builds a tree representation of the global namespace. Omits prototypes. */ private class BuildGlobalNamespace extends NodeTraversal.AbstractPreOrderCallback { /** Collect the references in pre-order. */ @Override public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { // If we are traversing the externs, then we save a pointer to the scope // generated by them, so that we can do lookups in it later. if (hasExternsRoot() && n == externsRoot) { externsScope = t.getScope(); } collect(t.getModule(), t.getScope(), n); return true; } public void collect(JSModule module, Scope scope, Node n) { Node parent = n.getParent(); String name; boolean isSet = false; Name.Type type = Name.Type.OTHER; boolean isPropAssign = false; boolean shouldCreateProp = true; switch (n.getToken()) { case GETTER_DEF: case SETTER_DEF: case STRING_KEY: case MEMBER_FUNCTION_DEF: // This may be a key in an object literal declaration. name = null; if (parent.isObjectLit()) { name = getNameForObjLitKey(n); } else if (parent.isClassMembers()) { name = getNameForClassMembers(n); } if (name == null) { return; } isSet = true; switch (n.getToken()) { case MEMBER_FUNCTION_DEF: type = getValueType(n.getFirstChild()); if (n.getParent().isClassMembers() && !n.isStaticMember()) { shouldCreateProp = false; } break; case STRING_KEY: type = getValueType(n.getFirstChild()); break; case GETTER_DEF: type = Name.Type.GET; break; case SETTER_DEF: type = Name.Type.SET; break; default: throw new IllegalStateException("unexpected:" + n); } break; case NAME: // This may be a variable get or set. switch (parent.getToken()) { case VAR: case LET: case CONST: isSet = true; Node rvalue = n.getFirstChild(); type = (rvalue == null) ? Name.Type.OTHER : getValueType(rvalue); break; case ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); } break; case GETPROP: return; case FUNCTION: Node grandparent = parent.getParent(); if (grandparent == null || NodeUtil.isFunctionExpression(parent)) { return; } isSet = true; type = Name.Type.FUNCTION; break; case CATCH: case INC: case DEC: isSet = true; type = Name.Type.OTHER; break; case CLASS: // The first child is the class name, and the second child is the superclass name. if (parent.getFirstChild() == n) { isSet = true; type = Name.Type.CLASS; } break; case ARRAY_PATTERN: // Specific case to handle inlining with array destructuring isSet = true; type = Name.Type.OTHER; break; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } name = n.getString(); break; case GETPROP: // This may be a namespaced name get or set. if (parent != null) { switch (parent.getToken()) { case ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); isPropAssign = true; } break; case INC: case DEC: isSet = true; type = Name.Type.OTHER; break; case GETPROP: return; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } if (!n.isQualifiedName()) { return; } name = n.getQualifiedName(); break; case CALL: if (isObjectHasOwnPropertyCall(n)) { String qname = n.getFirstFirstChild().getQualifiedName(); Name globalName = getOrCreateName(qname, true); globalName.usedHasOwnProperty = true; } return; default: return; } // We are only interested in global names. if (!isGlobalNameReference(name, scope)) { return; } if (isSet) { // Use the closest hoist scope to select handleSetFromGlobal or handleSetFromLocal // because they use the term 'global' in an ES5, pre-block-scoping sense. Scope hoistScope = scope.getClosestHoistScope(); if (hoistScope.isGlobal()) { handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type, shouldCreateProp); } else { handleSetFromLocal(module, scope, n, parent, name, shouldCreateProp); } } else { handleGet(module, scope, n, parent, name); } } /** * Gets the fully qualified name corresponding to an object literal key, * as long as it and its prefix property names are valid JavaScript * identifiers. The object literal may be nested inside of other object * literals. * * For example, if called with node {@code n} representing "z" in any of * the following expressions, the result would be "w.x.y.z": * <code> var w = {x: {y: {z: 0}}}; </code> * <code> w.x = {y: {z: 0}}; </code> * <code> w.x.y = {'a': 0, 'z': 0}; </code> * * @param n A child of an OBJLIT node * @return The global name, or null if {@code n} doesn't correspond to the * key of an object literal that can be named */ String getNameForObjLitKey(Node n) { Node parent = n.getParent(); checkState(parent.isObjectLit()); Node grandparent = parent.getParent(); if (grandparent == null) { return null; } Node greatGrandparent = grandparent.getParent(); String name; switch (grandparent.getToken()) { case NAME: // VAR // NAME (grandparent) // OBJLIT (parent) // STRING (n) if (greatGrandparent == null || !NodeUtil.isNameDeclaration(greatGrandparent)) { return null; } name = grandparent.getString(); break; case ASSIGN: // ASSIGN (grandparent) // NAME|GETPROP // OBJLIT (parent) // STRING (n) Node lvalue = grandparent.getFirstChild(); name = lvalue.getQualifiedName(); break; case STRING_KEY: // OBJLIT // STRING (grandparent) // OBJLIT (parent) // STRING (n) if (greatGrandparent != null && greatGrandparent.isObjectLit()) { name = getNameForObjLitKey(grandparent); } else { return null; } break; default: return null; } if (name != null) { String key = n.getString(); if (TokenStream.isJSIdentifier(key)) { return name + '.' + key; } } return null; } /** * Gets the fully qualified name corresponding to an class member function, * as long as it and its prefix property names are valid JavaScript * identifiers. * * For example, if called with node {@code n} representing "y" in any of * the following expressions, the result would be "x.y": * <code> class x{y(){}}; </code> * <code> var x = class{y(){}}; </code> * <code> var x; x = class{y(){}}; </code> * * @param n A child of an CLASS_MEMBERS node * @return The global name, or null if {@code n} doesn't correspond to * a class member function that can be named */ String getNameForClassMembers(Node n) { Node parent = n.getParent(); checkState(parent.isClassMembers()); String className = NodeUtil.getName(parent.getParent()); return className == null ? null : className + '.' + n.getString(); } /** * Gets the type of a value or simple expression. * * @param n An r-value in an assignment or variable declaration (not null) * @return A {@link Name.Type} */ Name.Type getValueType(Node n) { // Shorthand assignment of extended object literal if (n == null) { return Name.Type.OTHER; } switch (n.getToken()) { case CLASS: return Name.Type.CLASS; case OBJECTLIT: return Name.Type.OBJECTLIT; case FUNCTION: return Name.Type.FUNCTION; case OR: // Recurse on the second value. If the first value were an object // literal or function, then the OR would be meaningless and the // second value would be dead code. Assume that if the second value // is an object literal or function, then the first value will also // evaluate to one when it doesn't evaluate to false. return getValueType(n.getLastChild()); case HOOK: // The same line of reasoning used for the OR case applies here. Node second = n.getSecondChild(); Name.Type t = getValueType(second); if (t != Name.Type.OTHER) { return t; } Node third = second.getNext(); return getValueType(third); default: break; } return Name.Type.OTHER; } /** * Updates our representation of the global namespace to reflect an assignment to a global name * in any scope where variables are hoisted to the global scope (i.e. the global scope in an ES5 * sense). * * @param module the current module * @param scope the current scope * @param n The node currently being visited * @param parent {@code n}'s parent * @param name The global name (e.g. "a" or "a.b.c.d") * @param isPropAssign Whether this set corresponds to a property * assignment of the form <code>a.b.c = ...;</code> * @param type The type of the value that the name is being assigned */ void handleSetFromGlobal(JSModule module, Scope scope, Node n, Node parent, String name, boolean isPropAssign, Name.Type type, boolean shouldCreateProp) { if (maybeHandlePrototypePrefix(module, scope, n, parent, name)) { return; } Name nameObj = getOrCreateName(name, shouldCreateProp); nameObj.type = type; if (n.getBooleanProp(Node.MODULE_EXPORT)) { nameObj.isModuleProp = true; } maybeRecordEs6Subclass(n, parent, nameObj); Ref set = new Ref(module, scope, n, nameObj, Ref.Type.SET_FROM_GLOBAL, currentPreOrderIndex++); nameObj.addRef(set); if (isNestedAssign(parent)) { // This assignment is both a set and a get that creates an alias. Ref get = new Ref(module, scope, n, nameObj, Ref.Type.ALIASING_GET, currentPreOrderIndex++); nameObj.addRef(get); Ref.markTwins(set, get); } else if (isTypeDeclaration(n)) { // Names with a @constructor or @enum annotation are always collapsed nameObj.setDeclaredType(); } } /** * Given a new node and its name that is an ES6 class, checks if it is an ES6 class with an ES6 * superclass. If the superclass is a simple or qualified names, adds itself to the parent's * list of subclasses. Otherwise this does nothing. * * @param n The node being visited. * @param parent {@code n}'s parent * @param subclassNameObj The Name of the new node being visited. */ private void maybeRecordEs6Subclass(Node n, Node parent, Name subclassNameObj) { if (subclassNameObj.type != Name.Type.CLASS || parent == null) { return; } Node superclass = null; if (parent.isClass()) { superclass = parent.getSecondChild(); } else { Node classNode = NodeUtil.getAssignedValue(n); if (classNode != null && classNode.isClass()) { superclass = classNode.getSecondChild(); } } // If there's no superclass, or the superclass expression is more complicated than a simple // or qualified name, return. if (superclass == null || superclass.isEmpty() || !(superclass.isName() || superclass.isGetProp())) { return; } String superclassName = superclass.getQualifiedName(); Name superclassNameObj = getOrCreateName(superclassName, true); // If the superclass is an ES3/5 class we don't record its subclasses. if (superclassNameObj != null && superclassNameObj.type == Name.Type.CLASS) { superclassNameObj.addSubclass(subclassNameObj); } } /** * Determines whether a set operation is a constructor or enumeration * or interface declaration. The set operation may either be an assignment * to a name, a variable declaration, or an object literal key mapping. * * @param n The node that represents the name being set * @return Whether the set operation is either a constructor or enum * declaration */ private boolean isTypeDeclaration(Node n) { Node valueNode = NodeUtil.getRValueOfLValue(n); JSDocInfo info = NodeUtil.getBestJSDocInfo(n); // Heed the annotations only if they're sensibly used. return info != null && valueNode != null && ((info.isConstructor() && valueNode.isFunction()) || (info.isInterface() && valueNode.isFunction()) || (info.hasEnumParameterType() && valueNode.isObjectLit())); } /** * Updates our representation of the global namespace to reflect an * assignment to a global name in a local scope. * * @param module The current module * @param scope The current scope * @param n The node currently being visited * @param parent {@code n}'s parent * @param name The global name (e.g. "a" or "a.b.c.d") */ void handleSetFromLocal(JSModule module, Scope scope, Node n, Node parent, String name, boolean shouldCreateProp) { if (maybeHandlePrototypePrefix(module, scope, n, parent, name)) { return; } Name nameObj = getOrCreateName(name, shouldCreateProp); Ref set = new Ref(module, scope, n, nameObj, Ref.Type.SET_FROM_LOCAL, currentPreOrderIndex++); nameObj.addRef(set); if (n.getBooleanProp(Node.MODULE_EXPORT)) { nameObj.isModuleProp = true; } if (isNestedAssign(parent)) { // This assignment is both a set and a get that creates an alias. Ref get = new Ref(module, scope, n, nameObj, Ref.Type.ALIASING_GET, currentPreOrderIndex++); nameObj.addRef(get); Ref.markTwins(set, get); } } /** * Updates our representation of the global namespace to reflect a read * of a global name. * * @param module The current module * @param scope The current scope * @param n The node currently being visited * @param parent {@code n}'s parent * @param name The global name (e.g. "a" or "a.b.c.d") */ void handleGet(JSModule module, Scope scope, Node n, Node parent, String name) { if (maybeHandlePrototypePrefix(module, scope, n, parent, name)) { return; } Ref.Type type; switch (parent.getToken()) { case EXPR_RESULT: case IF: case INSTANCEOF: case TYPEOF: case VOID: case NOT: case BITNOT: case POS: case NEG: type = Ref.Type.DIRECT_GET; break; case CALL: if (n == parent.getFirstChild()) { // It is a call target type = Ref.Type.CALL_GET; } else if (isClassDefiningCall(parent)) { type = Ref.Type.DIRECT_GET; } else { type = Ref.Type.ALIASING_GET; } break; case NEW: type = n == parent.getFirstChild() ? Ref.Type.DIRECT_GET : Ref.Type.ALIASING_GET; break; case OR: case AND: // This node is x or y in (x||y) or (x&&y). We only know that an // alias is not getting created for this name if the result is used // in a boolean context or assigned to the same name // (e.g. var a = a || {}). type = determineGetTypeForHookOrBooleanExpr(module, scope, parent, name); break; case HOOK: if (n != parent.getFirstChild()) { // This node is y or z in (x?y:z). We only know that an alias is // not getting created for this name if the result is assigned to // the same name (e.g. var a = a ? a : {}). type = determineGetTypeForHookOrBooleanExpr(module, scope, parent, name); } else { type = Ref.Type.DIRECT_GET; } break; case DELPROP: type = Ref.Type.DELETE_PROP; break; case CLASS: // This node is the superclass in an extends clause. type = Ref.Type.DIRECT_GET; break; default: type = Ref.Type.ALIASING_GET; break; } handleGet(module, scope, n, parent, name, type, true); } /** * Updates our representation of the global namespace to reflect a read of a global name. * * @param module The current module * @param scope The current scope * @param n The node currently being visited * @param parent {@code n}'s parent * @param name The global name (e.g. "a" or "a.b.c.d") * @param type The reference type */ void handleGet( JSModule module, Scope scope, Node n, Node parent, String name, Ref.Type type, boolean shouldCreateProp) { Name nameObj = getOrCreateName(name, shouldCreateProp); // No need to look up additional ancestors, since they won't be used. nameObj.addRef(new Ref(module, scope, n, nameObj, type, currentPreOrderIndex++)); } private boolean isClassDefiningCall(Node callNode) { CodingConvention convention = compiler.getCodingConvention(); // Look for goog.inherits, goog.mixin SubclassRelationship classes = convention.getClassesDefinedByCall(callNode); if (classes != null) { return true; } // Look for calls to goog.addSingletonGetter calls. String className = convention.getSingletonGetterClassName(callNode); return className != null; } /** Detect calls of the form a.b.hasOwnProperty(c); that prevent property collapsing on a.b */ private boolean isObjectHasOwnPropertyCall(Node callNode) { checkArgument(callNode.isCall(), callNode); if (!callNode.hasTwoChildren()) { return false; } Node fn = callNode.getFirstChild(); if (!fn.isGetProp()) { return false; } Node callee = fn.getFirstChild(); Node method = fn.getSecondChild(); return method.isString() && "hasOwnProperty".equals(method.getString()) && callee.isQualifiedName(); } /** * Determines whether the result of a hook (x?y:z) or boolean expression * (x||y) or (x&&y) is assigned to a specific global name. * * @param module The current module * @param scope The current scope * @param parent The parent of the current node in the traversal. This node * should already be known to be a HOOK, AND, or OR node. * @param name A name that is already known to be global in the current * scope (e.g. "a" or "a.b.c.d") * @return The expression's get type, either {@link Ref.Type#DIRECT_GET} or * {@link Ref.Type#ALIASING_GET} */ Ref.Type determineGetTypeForHookOrBooleanExpr( JSModule module, Scope scope, Node parent, String name) { Node prev = parent; for (Node anc : parent.getAncestors()) { switch (anc.getToken()) { case INSTANCEOF: case EXPR_RESULT: case VAR: case LET: case CONST: case IF: case WHILE: case FOR: case FOR_IN: case TYPEOF: case VOID: case NOT: case BITNOT: case POS: case NEG: return Ref.Type.DIRECT_GET; case HOOK: if (anc.getFirstChild() == prev) { return Ref.Type.DIRECT_GET; } break; case ASSIGN: if (!anc.getFirstChild().matchesQualifiedName(name)) { return Ref.Type.ALIASING_GET; } break; case NAME: // a variable declaration if (!name.equals(anc.getString())) { return Ref.Type.ALIASING_GET; } break; case CALL: if (anc.getFirstChild() != prev) { return Ref.Type.ALIASING_GET; } break; case DELPROP: return Ref.Type.DELETE_PROP; default: break; } prev = anc; } return Ref.Type.ALIASING_GET; } /** * Updates our representation of the global namespace to reflect a read * of a global name's longest prefix before the "prototype" property if the * name includes the "prototype" property. Does nothing otherwise. * * @param module The current module * @param scope The current scope * @param n The node currently being visited * @param parent {@code n}'s parent * @param name The global name (e.g. "a" or "a.b.c.d") * @return Whether the name was handled */ boolean maybeHandlePrototypePrefix(JSModule module, Scope scope, Node n, Node parent, String name) { // We use a string-based approach instead of inspecting the parse tree // to avoid complexities with object literals, possibly nested, beneath // assignments. int numLevelsToRemove; String prefix; if (name.endsWith(".prototype")) { numLevelsToRemove = 1; prefix = name.substring(0, name.length() - 10); } else { int i = name.indexOf(".prototype."); if (i == -1) { return false; } prefix = name.substring(0, i); numLevelsToRemove = 2; i = name.indexOf('.', i + 11); while (i >= 0) { numLevelsToRemove++; i = name.indexOf('.', i + 1); } } if (parent != null && NodeUtil.isObjectLitKey(n)) { // Object literal keys have no prefix that's referenced directly per // key, so we're done. return true; } for (int i = 0; i < numLevelsToRemove; i++) { parent = n; n = n.getFirstChild(); } handleGet(module, scope, n, parent, prefix, Ref.Type.PROTOTYPE_GET, true); return true; } /** * Determines whether an assignment is nested (i.e. whether its return * value is used). * * @param parent The parent of the current traversal node (not null) * @return Whether it appears that the return value of the assignment is * used */ boolean isNestedAssign(Node parent) { return parent.isAssign() && !parent.getParent().isExprResult(); } /** * Gets a {@link Name} instance for a global name. Creates it if necessary, * as well as instances for any of its prefixes that are not yet defined. * * @param name A global name (e.g. "a", "a.b.c.d") * @return The {@link Name} instance for {@code name} */ Name getOrCreateName(String name, boolean shouldCreateProp) { Name node = nameMap.get(name); if (node == null) { int i = name.lastIndexOf('.'); if (i >= 0) { String parentName = name.substring(0, i); Name parent = getOrCreateName(parentName, true); node = parent.addProperty(name.substring(i + 1), inExterns, shouldCreateProp); } else { node = new Name(name, null, inExterns); globalNames.add(node); } nameMap.put(name, node); } return node; } } // ------------------------------------------------------------------------- /** * A name defined in global scope (e.g. "a" or "a.b.c.d"). These form a tree. * As the parse tree traversal proceeds, we'll discover that some names * correspond to JavaScript objects whose properties we should consider * collapsing. */ static class Name implements StaticTypedSlot<TypeI> { enum Type { CLASS, OBJECTLIT, FUNCTION, GET, SET, OTHER, } private final String baseName; final Name parent; // The children of this name. Must be null if there are no children. @Nullable List<Name> props; /** The first global assignment to a name. */ private Ref declaration; /** All references to a name. This must contain {@code declaration}. */ private List<Ref> refs; /** All Es6 subclasses of a name that is an Es6 class. Must be null if not an ES6 class. */ @Nullable List<Name> subclasses; Type type; private boolean declaredType = false; private boolean isDeclared = false; private boolean isModuleProp = false; private boolean usedHasOwnProperty = false; int globalSets = 0; int localSets = 0; int localSetsWithNoCollapse = 0; int aliasingGets = 0; int totalGets = 0; int callGets = 0; int deleteProps = 0; final boolean inExterns; JSDocInfo docInfo = null; Name(String name, Name parent, boolean inExterns) { this.baseName = name; this.parent = parent; this.type = Type.OTHER; this.inExterns = inExterns; } Name addProperty(String name, boolean inExterns, boolean shouldCreateProp) { if (props == null) { props = new ArrayList<>(); } Name node = new Name(name, this, inExterns); if (shouldCreateProp) { props.add(node); } return node; } Name addSubclass(Name subclassName) { checkArgument(this.type == Type.CLASS && subclassName.type == Type.CLASS); if (subclasses == null) { subclasses = new ArrayList<>(); } subclasses.add(subclassName); return subclassName; } String getBaseName() { return baseName; } @Override public String getName() { return getFullName(); } String getFullName() { return parent == null ? baseName : parent.getFullName() + '.' + baseName; } @Override public Ref getDeclaration() { return declaration; } @Override public boolean isTypeInferred() { return false; } @Override public TypeI getType() { return null; } void addRef(Ref ref) { addRefInternal(ref); switch (ref.type) { case SET_FROM_GLOBAL: if (declaration == null) { declaration = ref; docInfo = getDocInfoForDeclaration(ref); } globalSets++; break; case SET_FROM_LOCAL: localSets++; JSDocInfo info = ref.getNode() == null ? null : NodeUtil.getBestJSDocInfo(ref.getNode()); if (info != null && info.isNoCollapse()) { localSetsWithNoCollapse++; } break; case PROTOTYPE_GET: case DIRECT_GET: Node node = ref.getNode(); if (node != null && node.isGetProp() && node.getParent().isExprResult()) { docInfo = node.getJSDocInfo(); } totalGets++; break; case ALIASING_GET: aliasingGets++; totalGets++; break; case CALL_GET: callGets++; totalGets++; break; case DELETE_PROP: deleteProps++; break; default: throw new IllegalStateException(); } } void removeRef(Ref ref) { if (refs != null && refs.remove(ref)) { if (ref == declaration) { declaration = null; if (refs != null) { for (Ref maybeNewDecl : refs) { if (maybeNewDecl.type == Ref.Type.SET_FROM_GLOBAL) { declaration = maybeNewDecl; break; } } } } JSDocInfo info; switch (ref.type) { case SET_FROM_GLOBAL: globalSets--; break; case SET_FROM_LOCAL: localSets--; info = ref.getNode() == null ? null : NodeUtil.getBestJSDocInfo(ref.getNode()); if (info != null && info.isNoCollapse()) { localSetsWithNoCollapse--; } break; case PROTOTYPE_GET: case DIRECT_GET: totalGets--; break; case ALIASING_GET: aliasingGets--; totalGets--; break; case CALL_GET: callGets--; totalGets--; break; case DELETE_PROP: deleteProps--; break; default: throw new IllegalStateException(); } } } List<Ref> getRefs() { return refs == null ? ImmutableList.of() : refs; } void addRefInternal(Ref ref) { if (refs == null) { refs = new ArrayList<>(); } refs.add(ref); } boolean canEliminate() { if (!canCollapseUnannotatedChildNames() || totalGets > 0) { return false; } if (props != null) { for (Name n : props) { if (!n.canCollapse()) { return false; } } } return true; } boolean isSimpleStubDeclaration() { if (getRefs().size() == 1) { Ref ref = refs.get(0); if (ref.node.getParent().isExprResult()) { return true; } } return false; } boolean isCollapsingExplicitlyDenied() { if (docInfo == null) { Ref ref = getDeclaration(); if (ref != null) { docInfo = getDocInfoForDeclaration(ref); } } return docInfo != null && docInfo.isNoCollapse(); } boolean isInlinableGlobalAlias() { // Only simple aliases with direct usage are inlinable. if (inExterns || globalSets != 1 || localSets != 0 || !canCollapse()) { return false; } // Only allow inlining of simple references. for (Ref ref : getRefs()) { switch (ref.type) { case SET_FROM_GLOBAL: // Expect one global set continue; case SET_FROM_LOCAL: throw new IllegalStateException(); case ALIASING_GET: case DIRECT_GET: case PROTOTYPE_GET: case CALL_GET: continue; case DELETE_PROP: return false; default: throw new IllegalStateException(); } } return true; } boolean canCollapse() { return !inExterns && !isGetOrSetDefinition() && !isCollapsingExplicitlyDenied() && (declaredType || ((parent == null || parent.canCollapseUnannotatedChildNames()) && (globalSets > 0 || localSets > 0) && localSetsWithNoCollapse == 0 && deleteProps == 0)) && !isStaticClassMemberFunction(); } boolean isStaticClassMemberFunction() { // TODO (simranarora) eventually we want to be able to collapse for static class member // function declarations and get rid of this method. We need to be careful about handling // super and this so we back off for now and decided not to collapse static class methods. Ref ref = this.getDeclaration(); if (ref != null) { Node n = ref.getNode(); if (n != null && n.isStaticMember() && n.getParent().isClassMembers()) { return true; } } return false; } boolean isGetOrSetDefinition() { return this.type == Type.GET || this.type == Type.SET; } boolean canCollapseUnannotatedChildNames() { if (type == Type.OTHER || isGetOrSetDefinition() || globalSets != 1 || localSets != 0 || deleteProps != 0) { return false; } // Don't try to collapse if the one global set is a twin reference. // We could theoretically handle this case in CollapseProperties, but // it's probably not worth the effort. checkNotNull(declaration); if (declaration.getTwin() != null) { return false; } if (isCollapsingExplicitlyDenied()) { return false; } if (usedHasOwnProperty) { return false; } if (declaredType) { return true; } // If this is a key of an aliased object literal, then it will be aliased // later. So we won't be able to collapse its properties. if (parent != null && parent.shouldKeepKeys()) { return false; } // If this is aliased, then its properties can't be collapsed either. if (aliasingGets > 0) { return false; } return (parent == null || parent.canCollapseUnannotatedChildNames()); } /** Whether this is an object literal that needs to keep its keys. */ boolean shouldKeepKeys() { return type == Type.OBJECTLIT && (aliasingGets > 0 || isCollapsingExplicitlyDenied()); } boolean needsToBeStubbed() { return globalSets == 0 && localSets > 0 && localSetsWithNoCollapse == 0 && !isCollapsingExplicitlyDenied(); } void setDeclaredType() { declaredType = true; for (Name ancestor = parent; ancestor != null; ancestor = ancestor.parent) { ancestor.isDeclared = true; } } boolean isDeclaredType() { return declaredType; } boolean isConstructor() { Node declNode = declaration.node; Node rvalueNode = NodeUtil.getRValueOfLValue(declNode); JSDocInfo jsdoc = NodeUtil.getBestJSDocInfo(declNode); return rvalueNode != null && rvalueNode.isFunction() && jsdoc != null && jsdoc.isConstructor(); } /** * Determines whether this name is a prefix of at least one class or enum * name. Because classes and enums are always collapsed, the namespace will * have different properties in compiled code than in uncompiled code. * * For example, if foo.bar.DomHelper is a class, then foo and foo.bar are * considered namespaces. */ boolean isNamespaceObjectLit() { return isDeclared && type == Type.OBJECTLIT; } /** * Determines whether this is a simple name (as opposed to a qualified * name). */ boolean isSimpleName() { return parent == null; } @Override public String toString() { return getFullName() + " (" + type + "): " + Joiner.on(", ").join( "globalSets=" + globalSets, "localSets=" + localSets, "totalGets=" + totalGets, "aliasingGets=" + aliasingGets, "callGets=" + callGets); } @Override public JSDocInfo getJSDocInfo() { return docInfo; } /** * Tries to get the doc info for a given declaration ref. */ private static JSDocInfo getDocInfoForDeclaration(Ref ref) { if (ref.node != null) { Node refParent = ref.node.getParent(); if (refParent == null) { // May happen when inlineAliases removes refs from the AST. return null; } switch (refParent.getToken()) { case FUNCTION: case ASSIGN: case CLASS: return refParent.getJSDocInfo(); case VAR: case LET: case CONST: return ref.node == refParent.getFirstChild() ? refParent.getJSDocInfo() : ref.node.getJSDocInfo(); case OBJECTLIT: return ref.node.getJSDocInfo(); default: break; } } return null; } boolean isModuleExport() { return isModuleProp; } } // ------------------------------------------------------------------------- /** * A global name reference. Contains references to the relevant parse tree * node and its ancestors that may be affected. */ static class Ref implements StaticTypedRef<TypeI> { // Note: we are more aggressive about collapsing @enum and @constructor // declarations than implied here, see Name#canCollapse enum Type { /** Set in the global scope: a.b.c = 0; */ SET_FROM_GLOBAL, /** Set in a local scope: function f() { a.b.c = 0; } */ SET_FROM_LOCAL, /** Get a name's prototype: a.b.c.prototype */ PROTOTYPE_GET, /** * Includes all uses that prevent a name's properties from being collapsed: * var x = a.b.c * f(a.b.c) * new Foo(a.b.c) */ ALIASING_GET, /** * Includes all uses that prevent a name from being completely eliminated: * goog.inherits(anotherName, a.b.c) * new a.b.c() * x instanceof a.b.c * void a.b.c * if (a.b.c) {} */ DIRECT_GET, /** * Calling a name: a.b.c(); * Prevents a name from being collapsed if never set. */ CALL_GET, /** * Deletion of a property: delete a.b.c; * Prevents a name from being collapsed at all. */ DELETE_PROP, } Node node; final JSModule module; final Name name; final Type type; /** * The scope in which the reference is resolved. Note that for ALIASING_GETS like "var x = ns;" * this scope may not be the correct hoist scope of the aliasing VAR. */ final Scope scope; final int preOrderIndex; /** * Certain types of references are actually double-refs. For example, * var a = b = 0; * counts as both a "set" of b and an "alias" of b. * * We create two Refs for this node, and mark them as twins of each other. */ private Ref twin = null; /** * Creates a reference at the current node. */ Ref(JSModule module, Scope scope, Node node, Name name, Type type, int index) { this.node = node; this.name = name; this.module = module; this.type = type; this.scope = scope; this.preOrderIndex = index; } private Ref(Ref original, Type type, int index) { this.node = original.node; this.name = original.name; this.module = original.module; this.type = type; this.scope = original.scope; this.preOrderIndex = index; } private Ref(Type type, int index) { this.type = type; this.module = null; this.scope = null; this.name = null; this.preOrderIndex = index; } @Override public Node getNode() { return node; } @Override public StaticSourceFile getSourceFile() { return node != null ? node.getStaticSourceFile() : null; } @Override public StaticTypedSlot<TypeI> getSymbol() { return name; } JSModule getModule() { return module; } Ref getTwin() { return twin; } boolean isSet() { return type == Type.SET_FROM_GLOBAL || type == Type.SET_FROM_LOCAL; } static void markTwins(Ref a, Ref b) { checkArgument( (a.type == Type.ALIASING_GET || b.type == Type.ALIASING_GET) && (a.type == Type.SET_FROM_GLOBAL || a.type == Type.SET_FROM_LOCAL || b.type == Type.SET_FROM_GLOBAL || b.type == Type.SET_FROM_LOCAL)); a.twin = b; b.twin = a; } /** * Create a new ref that is the same as this one, but of * a different class. */ Ref cloneAndReclassify(Type type) { return new Ref(this, type, this.preOrderIndex); } static Ref createRefForTesting(Type type) { return new Ref(type, -1); } @Override public String toString() { return node.toString(); } } }
/** * Copyright 2016 vip.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * 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. * </p> **/ package com.vip.saturn.job; import com.vip.saturn.job.BaseSaturnJob; import com.vip.saturn.job.SaturnJobExecutionContext; import com.vip.saturn.job.SaturnJobReturn; import com.vip.saturn.job.msg.MsgHolder; import java.util.List; public abstract class AbstractSaturnBatchMsgJob extends BaseSaturnJob { /** * 消息作业处理入口 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolder 消息内容 * @param shardingContext 其它参数信息 * @return 返回执行结果 * @throws InterruptedException 注意处理中断异常 */ public abstract SaturnJobReturn handleMsgJob(String jobName, Integer shardItem, String shardParam, MsgHolder msgHolder, SaturnJobExecutionContext shardingContext) throws InterruptedException; /** * 超时强杀之前调用此方法 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolder 消息内容 * @param shardingContext 其它参数信息 */ public void beforeTimeout(String jobName, Integer shardItem, String shardParam, MsgHolder msgHolder, SaturnJobExecutionContext shardingContext) { // 由作业类实现逻辑 } /** * 超时强杀之后调用此方法 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolder 消息内容 * @param shardingContext 其它参数信息 */ public void onTimeout(String jobName, Integer shardItem, String shardParam, MsgHolder msgHolder, SaturnJobExecutionContext shardingContext) { // 由作业类实现逻辑 } /** * 在saturn-console对作业立即终止,或者优雅退出超时,或者与zk失去连接时,都会在强杀业务线程之前调用此方法。 * <p> * 注意,作业执行超时,强杀之前不会调用此方法,而是调用{@link #beforeTimeout(String, Integer, String, MsgHolder, SaturnJobExecutionContext)}方法。 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolder 消息内容 * @param shardingContext 其它参数信息 */ public void beforeForceStop(String jobName, Integer shardItem, String shardParam, MsgHolder msgHolder, SaturnJobExecutionContext shardingContext) { // 由作业类实现逻辑 } /** * 在saturn-console对作业立即终止,或者优雅退出超时,或者与zk失去连接时,都会在强杀业务线程之后调用此方法。 * <p> * 注意,作业执行超时,强杀之后不会调用此方法,而是调用{@link #onTimeout(String, Integer, String, MsgHolder, SaturnJobExecutionContext)}方法。 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolder 消息内容 * @param shardingContext 其它参数信息 */ public void postForceStop(String jobName, Integer shardItem, String shardParam, MsgHolder msgHolder, SaturnJobExecutionContext shardingContext) { // 由作业类实现逻辑 } /** * 批量消息作业处理入口 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolders 消息内容 * @param shardingContext 其它参数信息 * @return 返回执行结果 * @throws InterruptedException 注意处理中断异常 */ public abstract SaturnJobReturn handleBatchMsgJob(String jobName, Integer shardItem, String shardParam, List<MsgHolder> msgHolders, SaturnJobExecutionContext shardingContext) throws InterruptedException; /** * 超时强杀之前调用此方法 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolders 消息内容 * @param shardingContext 其它参数信息 */ public void beforeTimeout(String jobName, Integer shardItem, String shardParam, List<MsgHolder> msgHolders, SaturnJobExecutionContext shardingContext) { // 由作业类实现逻辑 } /** * 超时强杀之后调用此方法 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolders 消息内容 * @param shardingContext 其它参数信息 */ public void onTimeout(String jobName, Integer shardItem, String shardParam, List<MsgHolder> msgHolders, SaturnJobExecutionContext shardingContext) { // 由作业类实现逻辑 } /** * 在saturn-console对作业立即终止,或者优雅退出超时,或者与zk失去连接时,都会在强杀业务线程之前调用此方法。 * <p> * 注意,作业执行超时,强杀之前不会调用此方法,而是调用{@link #beforeTimeout(String, Integer, String, List, SaturnJobExecutionContext)}方法。 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolders 消息内容 * @param shardingContext 其它参数信息 */ public void beforeForceStop(String jobName, Integer shardItem, String shardParam, List<MsgHolder> msgHolders, SaturnJobExecutionContext shardingContext) { // 由作业类实现逻辑 } /** * 在saturn-console对作业立即终止,或者优雅退出超时,或者与zk失去连接时,都会在强杀业务线程之后调用此方法。 * <p> * 注意,作业执行超时,强杀之后不会调用此方法,而是调用{@link #onTimeout(String, Integer, String, List, SaturnJobExecutionContext)}方法。 * @param jobName 作业名 * @param shardItem 分片项 * @param shardParam 分片参数 * @param msgHolders 消息内容 * @param shardingContext 其它参数信息 */ public void postForceStop(String jobName, Integer shardItem, String shardParam, List<MsgHolder> msgHolders, SaturnJobExecutionContext shardingContext) { // 由作业类实现逻辑 } }
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.util.Range; @Autonomous(name="Forward Auton", group="Linear Opmode") //@Disabled public class ForwardAuton extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); //private DcMotor leftDrive = null; //private DcMotor rightDrive = null; DcMotor FLDrive; DcMotor FRDrive; DcMotor BLDrive; DcMotor BRDrive; double power = 0.5; @Override public void runOpMode() { telemetry.addData("Status", "Initialized"); telemetry.update(); FLDrive = hardwareMap.get(DcMotor.class, "front_left_drive"); FRDrive = hardwareMap.get(DcMotor.class, "front_right_drive"); BLDrive = hardwareMap.get(DcMotor.class, "back_left_drive"); BRDrive = hardwareMap.get(DcMotor.class, "back_right_drive"); FLDrive.setDirection(DcMotor.Direction.FORWARD); FRDrive.setDirection(DcMotor.Direction.FORWARD); BLDrive.setDirection(DcMotor.Direction.REVERSE); BRDrive.setDirection(DcMotor.Direction.REVERSE); waitForStart(); runtime.reset(); FLDrive.setPower(power); FRDrive.setPower(power); BLDrive.setPower(power); BRDrive.setPower(power); sleep(2000); power = 0.0; FLDrive.setPower(power); FRDrive.setPower(power); BLDrive.setPower(power); BRDrive.setPower(power); /* while (opModeIsActive()) { double leftPower; double rightPower; double drive = -gamepad1.left_stick_y; double turn = gamepad1.right_stick_x; leftPower = Range.clip(drive + turn, -1.0, 1.0) ; rightPower = Range.clip(drive - turn, -1.0, 1.0) ; leftDrive.setPower(leftPower); rightDrive.setPower(rightPower); telemetry.addData("Status", "Run Time: " + runtime.toString()); telemetry.addData("Motors", "left (%.2f), right (%.2f)", leftPower, rightPower); telemetry.update(); } */ } }
package io.smallrye.reactive.messaging.skip; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import javax.enterprise.context.ApplicationScoped; import javax.inject.Singleton; import org.eclipse.microprofile.reactive.messaging.Incoming; import org.eclipse.microprofile.reactive.messaging.Message; import org.eclipse.microprofile.reactive.messaging.Outgoing; import org.junit.jupiter.api.Test; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import io.smallrye.reactive.messaging.WeldTestBaseWithoutTails; import io.smallrye.reactive.messaging.annotations.Broadcast; public class SingleSkipTest extends WeldTestBaseWithoutTails { @Test public void testSkip() { addBeanClass(SkippingProcessors.class, Sender.class, Receiver.class); initialize(); Receiver receiver = get(Receiver.class); await().until(() -> receiver.out1.size() == 10); await().until(() -> receiver.out2.size() == 10); await().until(() -> receiver.out3.size() == 10); await().until(() -> receiver.out4.size() == 10); assertThat(receiver.out1).containsExactly("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"); assertThat(receiver.out2).containsExactly("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"); assertThat(receiver.out3).containsExactly("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"); assertThat(receiver.out4).containsExactly("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"); } @ApplicationScoped public static class Sender { @Outgoing("in") @Broadcast(4) public Multi<String> generate() { return Multi.createFrom().items( "a", "b", "c", "skip", "d", "skip", "e", "f", "skip", "g", "h", "i", "skip", "j"); } } @Singleton public static class Receiver { private final List<String> out1 = new CopyOnWriteArrayList<>(); private final List<String> out2 = new CopyOnWriteArrayList<>(); private final List<String> out3 = new CopyOnWriteArrayList<>(); private final List<String> out4 = new CopyOnWriteArrayList<>(); @Incoming("out-1") public void consumeOut1(String s) { out1.add(s); } @Incoming("out-2") public void consumeOut2(String s) { out2.add(s); } @Incoming("out-3") public void consumeOut3(String s) { out3.add(s); } @Incoming("out-4") public void consumeOut4(String s) { out4.add(s); } } @ApplicationScoped public static class SkippingProcessors { @Incoming("in") @Outgoing("out-1") public String processPayload(String s) { if (s.equalsIgnoreCase("skip")) { return null; } return s.toUpperCase(); } @Incoming("in") @Outgoing("out-2") public Message<String> processMessage(Message<String> m) { String s = m.getPayload(); if (s.equalsIgnoreCase("skip")) { return null; } return m.withPayload(s.toUpperCase()); } @Incoming("in") @Outgoing("out-3") public Uni<String> processPayloadAsync(String s) { if (s.equalsIgnoreCase("skip")) { // Important, you must not return `null`, but a `null` content return Uni.createFrom().nullItem(); } return Uni.createFrom().item(s.toUpperCase()); } @Incoming("in") @Outgoing("out-4") public Uni<Message<String>> processMessageAsync(Message<String> m) { String s = m.getPayload(); if (s.equalsIgnoreCase("skip")) { return Uni.createFrom().nullItem(); } return Uni.createFrom().item(m.withPayload(s.toUpperCase())); } } }
package org.eiichiro.jaguar; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.testing.ServletTester; import org.eiichiro.jaguar.ClasspathScanner; import org.eiichiro.reverb.system.Environment; import org.junit.Test; public class ClasspathScannerTest { @Test public void testClasspathScanner() throws Exception { try { new ClasspathScanner(); fail(); } catch (IllegalStateException e) { e.printStackTrace(); } Jaguar.bootstrap(); // Running on URLClassLoader. ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (!(loader instanceof URLClassLoader)) { fail(); } URLClassLoader classLoader = (URLClassLoader) loader; List<URL> urls = Arrays.asList(classLoader.getURLs()); Collection<URL> paths = (Collection<URL>) new ClasspathScanner().paths(); assertThat(paths.size(), is(urls.size())); for (URL url : urls) { assertTrue(paths.contains(url)); } // Standalone or running on a embedded Servlet container. urls = new ArrayList<>(); for (String path : Environment.getProperty("java.class.path").split( File.pathSeparator)) { urls.add(new File(path).toURI().toURL()); } Thread.currentThread().setContextClassLoader(new ClassLoader(classLoader) {}); if (Thread.currentThread().getContextClassLoader() instanceof URLClassLoader) { fail(); } paths = (Collection<URL>) new ClasspathScanner().paths(); assertThat(paths.size(), is(urls.size())); for (URL url : urls) { assertTrue(paths.contains(url)); } // Running on a Servlet container with the standard web application // layout. Jaguar.shutdown(); ServletTester tester = new ServletTester(); tester.setContextPath("/jaguar"); tester.addFilter(WebFilter.class, "/*", 0); tester.addServlet(DefaultServlet.class, "/"); tester.addEventListener(new WebListener()); ServletContextHandler context = tester.getContext(); for (URL url : urls) { if (url.getPath().endsWith("jaguar-core/target/test-classes/")) { context.setResourceBase(url.getPath()); } } tester.start(); paths = (Collection<URL>) new ClasspathScanner().paths(); assertThat(paths.size(), is(2)); if (paths.toArray(new URL[0])[0].getPath().endsWith("jaguar-core/target/test-classes/WEB-INF/classes/")) { assertTrue(paths.toArray(new URL[0])[1].getPath().endsWith("jaguar-core/target/test-classes/WEB-INF/lib/jaguar-core-2.0-rc5.jar")); } else { assertTrue(paths.toArray(new URL[0])[0].getPath().endsWith("jaguar-core/target/test-classes/WEB-INF/lib/jaguar-core-2.0-rc5.jar")); assertTrue(paths.toArray(new URL[0])[1].getPath().endsWith("jaguar-core/target/test-classes/WEB-INF/classes/")); } tester.stop(); Jaguar.shutdown(); Thread.currentThread().setContextClassLoader(loader); } @Test public void testScan() { Jaguar.bootstrap(); Collection<Class<?>> classes = new ClasspathScanner().scan(); assertTrue(classes.contains(ClasspathScannerComponent1.class)); assertTrue(classes.contains(ClasspathScannerComponent2.class)); assertTrue(classes.contains(ClasspathScannerComponent3.class)); assertTrue(classes.contains(ClasspathScannerComponent4.class)); assertTrue(classes.contains(ClasspathScannerProvider.class)); assertFalse(classes.contains(ClasspathScannerComponent5.class)); Jaguar.shutdown(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Tela.java * * Created on 25/09/2009, 22:54:46 */ package visao; import javax.swing.JOptionPane; import modelo.Pessoa; import persistencia.DAO; import persistencia.DAOPessoa; /** * * @author Hemerson */ public class Tela extends javax.swing.JFrame { Pessoa pessoa; DAO dao; /** Creates new form Tela */ public Tela() { initComponents(); this.setLocationRelativeTo(null); dao = new DAOPessoa(); this.limpa(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTextFieldNome = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextFieldID = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jTextFieldTelefone = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jButtonPrimeiro = new javax.swing.JButton(); jButtonAnterior = new javax.swing.JButton(); jButtonProximo = new javax.swing.JButton(); jButtonUltimo = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItemSalvar = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel1.setText("Nome:"); jTextFieldNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldNomeActionPerformed(evt); } }); jTextFieldNome.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jTextFieldNomeFocusLost(evt); } }); jLabel2.setText("ID:"); jTextFieldID.setBackground(new java.awt.Color(255, 255, 255)); jTextFieldID.setEditable(false); jLabel3.setText("Telefone:"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTextFieldID, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(52, 52, 52) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jTextFieldNome)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextFieldID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(jTextFieldTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jButtonPrimeiro.setText("<"); jButtonPrimeiro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonPrimeiroActionPerformed(evt); } }); jButtonAnterior.setText("<<"); jButtonAnterior.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAnteriorActionPerformed(evt); } }); jButtonProximo.setText(">>"); jButtonProximo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonProximoActionPerformed(evt); } }); jButtonUltimo.setText(">"); jButtonUltimo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonUltimoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jButtonPrimeiro, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonAnterior, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonProximo, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonUltimo, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonPrimeiro) .addComponent(jButtonUltimo) .addComponent(jButtonProximo) .addComponent(jButtonAnterior)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jMenu1.setText("Arquivo"); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem1.setText("Novo"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItemSalvar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); jMenuItemSalvar.setText("Salvar"); jMenuItemSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemSalvarActionPerformed(evt); } }); jMenu1.add(jMenuItemSalvar); jMenuBar1.add(jMenu1); jMenu2.setText("Editar"); jMenuItem4.setText("Alterar"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu2.add(jMenuItem4); jMenuItem5.setText("Excluir"); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem5ActionPerformed(evt); } }); jMenu2.add(jMenuItem5); jMenu3.setText("Localizar"); jMenuItem2.setText("ID"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu3.add(jMenuItem2); jMenuItem3.setText("Nome"); jMenu3.add(jMenuItem3); jMenu2.add(jMenu3); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed this.limpa(); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItemSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSalvarActionPerformed try { JOptionPane.showMessageDialog(null, dao.incluir(this.pegaDados())); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro na insercao!"); } this.limpa(); }//GEN-LAST:event_jMenuItemSalvarActionPerformed private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed try { JOptionPane.showMessageDialog(null, dao.atualizar(Integer.parseInt(jTextFieldID.getText()), this.pegaDados())); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro na atualizacao!"); } this.limpa(); }//GEN-LAST:event_jMenuItem4ActionPerformed private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed int resposta = 0; try { resposta = JOptionPane.showConfirmDialog(null, "Deseja realmente apagar?", "Exclusao",JOptionPane.YES_NO_OPTION); if(resposta == 0){ JOptionPane.showMessageDialog(null, dao.excluir(Integer.parseInt(jTextFieldID.getText()))); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro na exclusao"); } this.limpa(); }//GEN-LAST:event_jMenuItem5ActionPerformed private void jButtonPrimeiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPrimeiroActionPerformed try { this.mostraDados((Pessoa)dao.primeiro()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao mostrar primeiro registro!"); this.limpa(); } }//GEN-LAST:event_jButtonPrimeiroActionPerformed private void jButtonUltimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUltimoActionPerformed try { this.mostraDados((Pessoa)dao.ultimo()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao mostrar ultimo registro!"); this.limpa(); } }//GEN-LAST:event_jButtonUltimoActionPerformed private void jButtonAnteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAnteriorActionPerformed try { this.mostraDados((Pessoa)dao.anterior(Integer.parseInt(jTextFieldID.getText()))); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao mostrar registro anterior!"); this.limpa(); } }//GEN-LAST:event_jButtonAnteriorActionPerformed private void jButtonProximoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonProximoActionPerformed try { this.mostraDados((Pessoa)dao.proximo(Integer.parseInt(jTextFieldID.getText()))); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao mostrar proximo registro!"); this.limpa(); } }//GEN-LAST:event_jButtonProximoActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed int codigo = Integer.parseInt(JOptionPane.showInputDialog(null,"Digite o ID:")); try { this.mostraDados((Pessoa)dao.localizar(codigo)); } catch (Exception e) { JOptionPane.showMessageDialog(null, "ID nao encontrado!"); this.limpa(); } }//GEN-LAST:event_jMenuItem2ActionPerformed private void jTextFieldNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldNomeActionPerformed jTextFieldTelefone.requestFocus(); }//GEN-LAST:event_jTextFieldNomeActionPerformed private void jTextFieldNomeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldNomeFocusLost jTextFieldTelefone.requestFocus(); }//GEN-LAST:event_jTextFieldNomeFocusLost /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Tela().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonAnterior; private javax.swing.JButton jButtonPrimeiro; private javax.swing.JButton jButtonProximo; private javax.swing.JButton jButtonUltimo; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItemSalvar; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextFieldID; private javax.swing.JTextField jTextFieldNome; private javax.swing.JTextField jTextFieldTelefone; // End of variables declaration//GEN-END:variables private Pessoa pegaDados() { pessoa = new Pessoa(); try { pessoa.setId(Integer.parseInt(jTextFieldID.getText())); pessoa.setNome(jTextFieldNome.getText()); pessoa.setTelefone(jTextFieldTelefone.getText()); } catch (Exception e) { return null; } return pessoa; } private void limpa(){ jTextFieldID.setText(""+dao.maiorID()); jTextFieldNome.setText(""); jTextFieldTelefone.setText(""); jTextFieldNome.requestFocus(); } private void mostraDados(Pessoa pessoa){ jTextFieldID.setText(""+pessoa.getId()); jTextFieldNome.setText(pessoa.getNome()); jTextFieldTelefone.setText(pessoa.getTelefone()); } }
package com.atguigu.gulimall.coupon.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gulimall.coupon.entity.HomeAdvEntity; import com.atguigu.gulimall.coupon.service.HomeAdvService; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.R; /** * 首页轮播广告 * * @author tiankong * @email tiankong@gmail.com * @date 2021-06-12 12:37:07 */ @RestController @RequestMapping("coupon/homeadv") public class HomeAdvController { @Autowired private HomeAdvService homeAdvService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("coupon:homeadv:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = homeAdvService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("coupon:homeadv:info") public R info(@PathVariable("id") Long id){ HomeAdvEntity homeAdv = homeAdvService.getById(id); return R.ok().put("homeAdv", homeAdv); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("coupon:homeadv:save") public R save(@RequestBody HomeAdvEntity homeAdv){ homeAdvService.save(homeAdv); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("coupon:homeadv:update") public R update(@RequestBody HomeAdvEntity homeAdv){ homeAdvService.updateById(homeAdv); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("coupon:homeadv:delete") public R delete(@RequestBody Long[] ids){ homeAdvService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
/* * Copyright 2019-2021 The Polypheny 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. * * This file incorporates code covered by the following terms: * * 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.polypheny.db.algebra.mutable; import java.util.List; import org.polypheny.db.algebra.core.Minus; import org.polypheny.db.algebra.type.AlgDataType; import org.polypheny.db.plan.AlgOptCluster; /** * Mutable equivalent of {@link Minus}. */ public class MutableMinus extends MutableSetOp { private MutableMinus( AlgOptCluster cluster, AlgDataType rowType, List<MutableAlg> inputs, boolean all ) { super( cluster, rowType, MutableAlgType.MINUS, inputs, all ); } /** * Creates a MutableMinus. * * @param rowType Row type * @param inputs Input relational expressions * @param all Whether to perform a multiset subtraction or a set subtraction */ public static MutableMinus of( AlgDataType rowType, List<MutableAlg> inputs, boolean all ) { assert inputs.size() >= 2; final MutableAlg input0 = inputs.get( 0 ); return new MutableMinus( input0.cluster, rowType, inputs, all ); } @Override public StringBuilder digest( StringBuilder buf ) { return buf.append( "Minus(all: " ).append( all ).append( ")" ); } @Override public MutableAlg clone() { return MutableMinus.of( rowType, cloneChildren(), all ); } }
package com.alipay.api.request; import com.alipay.api.domain.AlipayOpenAppApiresQueryModel; import java.util.Map; import com.alipay.api.AlipayRequest; import com.alipay.api.internal.util.AlipayHashMap; import com.alipay.api.response.AlipayOpenAppApiresQueryResponse; import com.alipay.api.AlipayObject; /** * ALIPAY API: alipay.open.app.apires.query request * * @author auto create * @since 1.0, 2019-04-12 11:10:01 */ public class AlipayOpenAppApiresQueryRequest implements AlipayRequest<AlipayOpenAppApiresQueryResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * isp预发验证专用 */ private String bizContent; public void setBizContent(String bizContent) { this.bizContent = bizContent; } public String getBizContent() { return this.bizContent; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; public String getNotifyUrl() { return this.notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return this.returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getApiVersion() { return this.apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public void setTerminalType(String terminalType){ this.terminalType=terminalType; } public String getTerminalType(){ return this.terminalType; } public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public String getTerminalInfo(){ return this.terminalInfo; } public void setProdCode(String prodCode) { this.prodCode=prodCode; } public String getProdCode() { return this.prodCode; } public String getApiMethodName() { return "alipay.open.app.apires.query"; } public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("biz_content", this.bizContent); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } public Class<AlipayOpenAppApiresQueryResponse> getResponseClass() { return AlipayOpenAppApiresQueryResponse.class; } public boolean isNeedEncrypt() { return this.needEncrypt; } public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } public AlipayObject getBizModel() { return this.bizModel; } public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
package com.wuest.prefab.Structures.Base; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.wuest.prefab.Gui.GuiLangKeys; import com.wuest.prefab.Prefab; import com.wuest.prefab.Structures.Config.StructureConfiguration; import com.wuest.prefab.Structures.Events.StructureEventHandler; import com.wuest.prefab.Triple; import com.wuest.prefab.ZipUtil; import net.minecraft.block.*; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.item.HangingEntity; import net.minecraft.entity.item.ItemFrameEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.DyeColor; import net.minecraft.nbt.CompoundNBT; import net.minecraft.state.Property; import net.minecraft.state.properties.BedPart; import net.minecraft.state.properties.DoubleBlockHalf; import net.minecraft.tileentity.ChestTileEntity; import net.minecraft.tileentity.FurnaceTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.IStringSerializable; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraft.world.server.ServerWorld; import net.minecraftforge.registries.ForgeRegistries; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; /** * Each structure represents a building which is pre-defined in a JSON file. * * @author WuestMan */ @SuppressWarnings({"unchecked", "WeakerAccess", "ConstantConditions"}) public class Structure { public ArrayList<BlockPos> allBlockPositions = new ArrayList<>(); public ArrayList<BlockPos> clearedBlockPos = new ArrayList<BlockPos>(); public ArrayList<BuildBlock> priorityOneBlocks = new ArrayList<BuildBlock>(); public ArrayList<BuildBlock> priorityTwoBlocks = new ArrayList<>(); public ArrayList<BuildBlock> priorityThreeBlocks = new ArrayList<BuildBlock>(); public ArrayList<BuildBlock> airBlocks = new ArrayList<>(); public StructureConfiguration configuration; public ServerWorld world; public BlockPos originalPos; public Direction assumedNorth; public boolean hasAirBlocks = false; public boolean entitiesRemoved = false; @Expose public ArrayList<BuildTileEntity> tileEntities = new ArrayList<BuildTileEntity>(); @Expose public ArrayList<BuildEntity> entities = new ArrayList<BuildEntity>(); @Expose private String name; @Expose private BuildClear clearSpace; @Expose private ArrayList<BuildBlock> blocks; public Structure() { this.Initialize(); } /** * Creates an instance of the structure after reading from a resource location and converting it from JSON. * * @param <T> The type which extends Structure. * @param resourceLocation The location of the JSON file to load. Example: "assets/prefab/structures/warehouse.json" * @param child The child class which extends Structure. * @return Null if the resource wasn't found or the JSON could not be parsed, otherwise the de-serialized object. */ public static <T extends Structure> T CreateInstance(String resourceLocation, Class<? extends Structure> child) { T structure = null; Gson file = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); structure = (T) file.fromJson(ZipUtil.decompressResource(resourceLocation), child); return structure; } public static void CreateStructureFile(Structure structure, String fileLocation) { try { Gson converter = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); StringWriter stringWriter = new StringWriter(); converter.toJson(structure, stringWriter); ZipUtil.zipStringToFile(stringWriter.toString(), fileLocation); } catch (Exception e) { e.printStackTrace(); } } public static void ScanStructure(World world, BlockPos originalPos, BlockPos cornerPos1, BlockPos cornerPos2, String fileLocation, BuildClear clearedSpace, Direction playerFacing, boolean includeAir, boolean excludeWater) { Structure scannedStructure = new Structure(); scannedStructure.setClearSpace(clearedSpace); for (BlockPos currentPos : BlockPos.getAllInBoxMutable(cornerPos1, cornerPos2)) { if (world.isAirBlock(currentPos) && !includeAir) { continue; } BlockState currentState = world.getBlockState(currentPos); Block currentBlock = currentState.getBlock(); if (currentState.getMaterial() == Material.WATER && excludeWater) { continue; } BuildBlock buildBlock = Structure.createBuildBlockFromBlockState(currentState, currentBlock, currentPos, originalPos); if (currentBlock instanceof DoorBlock) { DoubleBlockHalf blockHalf = currentState.get(DoorBlock.HALF); if (blockHalf == DoubleBlockHalf.LOWER) { BlockState upperHalfState = world.getBlockState(currentPos.up()); if (upperHalfState.getBlock() instanceof DoorBlock) { Block upperBlock = upperHalfState.getBlock(); BuildBlock upperHalf = Structure.createBuildBlockFromBlockState(upperHalfState, upperBlock, currentPos.up(), originalPos); buildBlock.setSubBlock(upperHalf); } } else { // Don't process upper door halves. These were already done. continue; } } else if (currentBlock instanceof BedBlock) { BedPart bedPart = currentState.get(BedBlock.PART); if (bedPart == BedPart.HEAD) { BlockState bedFoot = null; boolean foundFoot = false; Direction facing = Direction.NORTH; while (!foundFoot) { bedFoot = world.getBlockState(currentPos.offset(facing)); if (bedFoot.getBlock() instanceof BedBlock && bedFoot.get(BedBlock.PART) == BedPart.FOOT) { foundFoot = true; break; } facing = facing.rotateY(); if (facing == Direction.NORTH) { // Got back to north, break out to avoid infinite loop. break; } } if (foundFoot) { Block footBedBlock = bedFoot.getBlock(); BuildBlock bed = Structure.createBuildBlockFromBlockState(bedFoot, footBedBlock, currentPos.offset(facing), originalPos); buildBlock.setSubBlock(bed); } } else { // Don't process foot of bed, it was already done. continue; } } scannedStructure.getBlocks().add(buildBlock); TileEntity tileEntity = world.getTileEntity(currentPos); if (tileEntity != null) { // Don't write data for empty tile entities. if ((tileEntity instanceof ChestTileEntity && ((ChestTileEntity) tileEntity).isEmpty()) || (tileEntity instanceof FurnaceTileEntity && ((FurnaceTileEntity) tileEntity).isEmpty())) { continue; } ResourceLocation resourceLocation = ForgeRegistries.TILE_ENTITIES.getKey(tileEntity.getType()); CompoundNBT tagCompound = new CompoundNBT(); tileEntity.write(tagCompound); BuildTileEntity buildTileEntity = new BuildTileEntity(); assert resourceLocation != null; buildTileEntity.setEntityDomain(resourceLocation.getNamespace()); buildTileEntity.setEntityName(resourceLocation.getPath()); buildTileEntity.setStartingPosition(Structure.getStartingPositionFromOriginalAndCurrentPosition(currentPos, originalPos)); buildTileEntity.setEntityNBTData(tagCompound); scannedStructure.tileEntities.add(buildTileEntity); } } int x_radiusRangeBegin = Math.min(cornerPos1.getX(), cornerPos2.getX()); int x_radiusRangeEnd = Math.max(cornerPos1.getX(), cornerPos2.getX()); int y_radiusRangeBegin = Math.min(cornerPos1.getY(), cornerPos2.getY()); int y_radiusRangeEnd = Math.max(cornerPos1.getY(), cornerPos2.getY()); int z_radiusRangeBegin = Math.min(cornerPos1.getZ(), cornerPos2.getZ()); int z_radiusRangeEnd = Math.max(cornerPos1.getZ(), cornerPos2.getZ()); AxisAlignedBB axis = new AxisAlignedBB(cornerPos1, cornerPos2); for (Entity entity : world.getEntitiesWithinAABBExcludingEntity(null, axis)) { // TODO: This was the "getPosition" method. BlockPos entityPos = entity.getPosition(); if (entityPos.getX() >= x_radiusRangeBegin && entityPos.getX() <= x_radiusRangeEnd && entityPos.getZ() >= z_radiusRangeBegin && entityPos.getZ() <= z_radiusRangeEnd && entityPos.getY() >= y_radiusRangeBegin && entityPos.getY() <= y_radiusRangeEnd) { BuildEntity buildEntity = new BuildEntity(); buildEntity.setEntityResourceString(ForgeRegistries.ENTITIES.getKey(entity.getType())); buildEntity.setStartingPosition(Structure.getStartingPositionFromOriginalAndCurrentPosition(entityPos, originalPos)); // The function calls below get the following fields from the "entity" class. posX, posY, posZ. // This will probably have to change when the mappings get updated. buildEntity.entityXAxisOffset = entityPos.getX() - entity.getPosX(); buildEntity.entityYAxisOffset = entityPos.getY() - entity.getPosY(); buildEntity.entityZAxisOffset = entityPos.getZ() - entity.getPosZ(); if (entity instanceof ItemFrameEntity) { buildEntity.entityYAxisOffset = buildEntity.entityYAxisOffset * -1; } if (entity instanceof HangingEntity) { buildEntity.entityFacing = entity.getHorizontalFacing(); } CompoundNBT entityTagCompound = new CompoundNBT(); entity.writeUnlessRemoved(entityTagCompound); buildEntity.setEntityNBTData(entityTagCompound); scannedStructure.entities.add(buildEntity); } } Structure.CreateStructureFile(scannedStructure, fileLocation); } /** * Creates a build block from the current block state. * * @param currentState The block state. * @param currentBlock The current block. * @param currentPos The current position. * @return A new Build block object. */ public static BuildBlock createBuildBlockFromBlockState(BlockState currentState, Block currentBlock, BlockPos currentPos, BlockPos originalPos) { BuildBlock buildBlock = new BuildBlock(); buildBlock.setBlockDomain(currentBlock.getRegistryName().getNamespace()); buildBlock.setBlockName(currentBlock.getRegistryName().getPath()); buildBlock.setStartingPosition(Structure.getStartingPositionFromOriginalAndCurrentPosition(currentPos, originalPos)); buildBlock.blockPos = currentPos; Collection<Property<?>> properties = currentState.getProperties(); for (Property<?> entry : properties) { BuildProperty property = new BuildProperty(); property.setName(entry.getName()); Comparable<?> value = currentState.get(entry); try { if (currentBlock instanceof RotatedPillarBlock && property.getName().equals("axis")) { property.setValue(((Direction.Axis) value).getString()); } else if (currentBlock instanceof CarpetBlock && property.getName().equals("color")) { DyeColor dyeColor = (DyeColor) value; property.setValue(dyeColor.getString()); } else if (value instanceof IStringSerializable) { IStringSerializable stringSerializable = (IStringSerializable) value; property.setValue(stringSerializable.getString()); } else { property.setValue(value.toString()); } } catch (Exception ex) { Prefab.LOGGER.error("Unable to set property [" + property.getName() + "] to value [" + value + "] for Block [" + buildBlock.getBlockDomain() + ":" + buildBlock.getBlockName() + "]."); throw ex; } buildBlock.getProperties().add(property); } return buildBlock; } public static PositionOffset getStartingPositionFromOriginalAndCurrentPosition(BlockPos currentPos, BlockPos originalPos) { // if (currentPos.getX() > originalPos.getX()). currentPos is "East" // of hitBlock // if (currentPos.getZ() > originalPos.getZ()). currentPos is // "South" of hitBlock PositionOffset positionOffSet = new PositionOffset(); if (currentPos.getX() > originalPos.getX()) { positionOffSet.setEastOffset(currentPos.getX() - originalPos.getX()); } else { positionOffSet.setWestOffset(originalPos.getX() - currentPos.getX()); } if (currentPos.getZ() > originalPos.getZ()) { positionOffSet.setSouthOffset(currentPos.getZ() - originalPos.getZ()); } else { positionOffSet.setNorthOffset(originalPos.getZ() - currentPos.getZ()); } positionOffSet.setHeightOffset(currentPos.getY() - originalPos.getY()); return positionOffSet; } public String getName() { return this.name; } public void setName(String value) { this.name = value; } public BuildClear getClearSpace() { return this.clearSpace; } public void setClearSpace(BuildClear value) { this.clearSpace = value; } public ArrayList<BuildBlock> getBlocks() { return this.blocks; } public void setBlocks(ArrayList<BuildBlock> value) { this.blocks = value; } public void Initialize() { this.name = ""; this.clearSpace = new BuildClear(); this.blocks = new ArrayList<>(); } /** * This is the main building method for this structure. * * @param configuration The configuration the user updated. * @param world The current world. * @param originalPos The block the user clicked on. * @param assumedNorth This should always be "NORTH" when the file is based on a scan. * @param player The player requesting the structure. * @return True if the build can occur, otherwise false. */ public boolean BuildStructure(StructureConfiguration configuration, ServerWorld world, BlockPos originalPos, Direction assumedNorth, PlayerEntity player) { BlockPos startBlockPos = this.clearSpace.getStartingPosition().getRelativePosition(originalPos, this.clearSpace.getShape().getDirection(), configuration.houseFacing); BlockPos endBlockPos = startBlockPos.offset(configuration.houseFacing.rotateYCCW(), this.clearSpace.getShape().getWidth() - 1) .offset(configuration.houseFacing.getOpposite(), this.clearSpace.getShape().getWidth() - 1) .offset(Direction.UP, this.clearSpace.getShape().getHeight()); // Make sure this structure can be placed here. Triple<Boolean, BlockState, BlockPos> checkResult = BuildingMethods.CheckBuildSpaceForAllowedBlockReplacement(world, startBlockPos, endBlockPos, player); if (!checkResult.getFirst()) { // Send a message to the player saying that the structure could not // be built. TranslationTextComponent message = new TranslationTextComponent( GuiLangKeys.GUI_STRUCTURE_NOBUILD, checkResult.getSecond().getBlock().getRegistryName().toString(), checkResult.getThird().getX(), checkResult.getThird().getY(), checkResult.getThird().getZ()); message.setStyle(Style.EMPTY.setFormatting(TextFormatting.GREEN)); player.sendMessage(message, player.getUniqueID()); return false; } if (!this.BeforeBuilding(configuration, world, originalPos, assumedNorth, player)) { // First, clear the area where the structure will be built. this.ClearSpace(configuration, world, originalPos, assumedNorth); boolean blockPlacedWithCobbleStoneInstead = false; // Now place all of the blocks. for (BuildBlock block : this.getBlocks()) { Block foundBlock = ForgeRegistries.BLOCKS.getValue(block.getResourceLocation()); if (foundBlock != null) { BlockState blockState = foundBlock.getDefaultState(); BuildBlock subBlock = null; // Check if water should be replaced with cobble. if (!this.WaterReplacedWithCobbleStone(configuration, block, world, originalPos, assumedNorth, foundBlock, blockState, player) && !this.CustomBlockProcessingHandled(configuration, block, world, originalPos, assumedNorth, foundBlock, blockState, player)) { block = BuildBlock.SetBlockState(configuration, world, originalPos, assumedNorth, block, foundBlock, blockState, this); if (block.getSubBlock() != null) { foundBlock = ForgeRegistries.BLOCKS.getValue(block.getSubBlock().getResourceLocation()); blockState = foundBlock.getDefaultState(); subBlock = BuildBlock.SetBlockState(configuration, world, originalPos, assumedNorth, block.getSubBlock(), foundBlock, blockState, this); } if (subBlock != null) { block.setSubBlock(subBlock); } boolean priorityThreeBlock = foundBlock instanceof TorchBlock || foundBlock instanceof AbstractSignBlock || foundBlock instanceof LeverBlock || foundBlock instanceof AbstractButtonBlock || foundBlock instanceof BedBlock || foundBlock instanceof CarpetBlock || foundBlock instanceof FlowerPotBlock || foundBlock instanceof SugarCaneBlock || foundBlock instanceof AbstractPressurePlateBlock || foundBlock instanceof DoorBlock || foundBlock instanceof LadderBlock || foundBlock instanceof VineBlock || foundBlock instanceof RedstoneWireBlock || foundBlock instanceof RedstoneDiodeBlock || foundBlock instanceof AbstractBannerBlock || foundBlock instanceof LanternBlock || foundBlock instanceof MushroomBlock; if (!block.getHasFacing()) { if (subBlock != null) { block.setSubBlock(subBlock); } if (priorityThreeBlock) { this.priorityThreeBlocks.add(block); } else if (foundBlock instanceof AirBlock) { this.airBlocks.add(block); } else if (foundBlock instanceof ITileEntityProvider) { this.priorityTwoBlocks.add(block); } else { this.priorityOneBlocks.add(block); } } else { // These blocks may be attached to other facing blocks and must be done later. if (priorityThreeBlock) { this.priorityThreeBlocks.add(block); } else { this.priorityTwoBlocks.add(block); } } } } else { // Cannot find this block in the registry. This can happen if a structure file has a mod block that // no longer exists. // In this case, print an informational message and replace it with cobblestone. String blockTypeNotFound = block.getResourceLocation().toString(); block = BuildBlock.SetBlockState(configuration, world, originalPos, assumedNorth, block, Blocks.COBBLESTONE, Blocks.COBBLESTONE.getDefaultState(), this); this.priorityOneBlocks.add(block); if (!blockPlacedWithCobbleStoneInstead) { blockPlacedWithCobbleStoneInstead = true; Prefab.LOGGER .warn("A Block was in the structure, but it is not registred. This block was replaced with vanilla cobblestone instead. Block type not found: [" + blockTypeNotFound + "]"); } } } this.configuration = configuration; this.world = world; this.assumedNorth = assumedNorth; this.originalPos = originalPos; if (StructureEventHandler.structuresToBuild.containsKey(player)) { StructureEventHandler.structuresToBuild.get(player).add(this); } else { ArrayList<Structure> structures = new ArrayList<Structure>(); structures.add(this); StructureEventHandler.structuresToBuild.put(player, structures); } } return true; } /** * This method is to process before a clear space block is set to air. * * @param pos The block position being processed. */ public void BeforeClearSpaceBlockReplaced(BlockPos pos) { } public void BeforeHangingEntityRemoved(HangingEntity hangingEntity) { } public BlockState getStainedGlassBlock(DyeColor color) { switch (color) { case BLACK: { return Blocks.BLACK_STAINED_GLASS.getDefaultState(); } case BLUE: { return Blocks.BLUE_STAINED_GLASS.getDefaultState(); } case BROWN: { return Blocks.BROWN_STAINED_GLASS.getDefaultState(); } case GRAY: { return Blocks.GRAY_STAINED_GLASS.getDefaultState(); } case GREEN: { return Blocks.GREEN_STAINED_GLASS.getDefaultState(); } case LIGHT_BLUE: { return Blocks.LIGHT_BLUE_STAINED_GLASS.getDefaultState(); } case LIGHT_GRAY: { return Blocks.LIGHT_GRAY_STAINED_GLASS.getDefaultState(); } case LIME: { return Blocks.LIME_STAINED_GLASS.getDefaultState(); } case MAGENTA: { return Blocks.MAGENTA_STAINED_GLASS.getDefaultState(); } case ORANGE: { return Blocks.ORANGE_STAINED_GLASS.getDefaultState(); } case PINK: { return Blocks.PINK_STAINED_GLASS.getDefaultState(); } case PURPLE: { return Blocks.PURPLE_STAINED_GLASS.getDefaultState(); } case RED: { return Blocks.RED_STAINED_GLASS.getDefaultState(); } case WHITE: { return Blocks.WHITE_STAINED_GLASS.getDefaultState(); } case YELLOW: { return Blocks.YELLOW_STAINED_GLASS.getDefaultState(); } default: { return Blocks.CYAN_STAINED_GLASS.getDefaultState(); } } } public BlockState getStainedGlassPaneBlock(DyeColor color) { switch (color) { case BLACK: { return Blocks.BLACK_STAINED_GLASS_PANE.getDefaultState(); } case BLUE: { return Blocks.BLUE_STAINED_GLASS_PANE.getDefaultState(); } case BROWN: { return Blocks.BROWN_STAINED_GLASS_PANE.getDefaultState(); } case GRAY: { return Blocks.GRAY_STAINED_GLASS_PANE.getDefaultState(); } case GREEN: { return Blocks.GREEN_STAINED_GLASS_PANE.getDefaultState(); } case LIGHT_BLUE: { return Blocks.LIGHT_BLUE_STAINED_GLASS_PANE.getDefaultState(); } case LIGHT_GRAY: { return Blocks.LIGHT_GRAY_STAINED_GLASS_PANE.getDefaultState(); } case LIME: { return Blocks.LIME_STAINED_GLASS_PANE.getDefaultState(); } case MAGENTA: { return Blocks.MAGENTA_STAINED_GLASS_PANE.getDefaultState(); } case ORANGE: { return Blocks.ORANGE_STAINED_GLASS_PANE.getDefaultState(); } case PINK: { return Blocks.PINK_STAINED_GLASS_PANE.getDefaultState(); } case PURPLE: { return Blocks.PURPLE_STAINED_GLASS_PANE.getDefaultState(); } case RED: { return Blocks.RED_STAINED_GLASS_PANE.getDefaultState(); } case WHITE: { return Blocks.WHITE_STAINED_GLASS_PANE.getDefaultState(); } case YELLOW: { return Blocks.YELLOW_STAINED_GLASS_PANE.getDefaultState(); } default: { return Blocks.CYAN_STAINED_GLASS_PANE.getDefaultState(); } } } /** * This method is used before any building occurs to check for things or possibly pre-build locations. Note: This is * even done before blocks are cleared. * * @param configuration The structure configuration. * @param world The current world. * @param originalPos The original position clicked on. * @param assumedNorth The assumed northern direction. * @param player The player which initiated the construction. * @return False if processing should continue, otherwise true to cancel processing. */ protected boolean BeforeBuilding(StructureConfiguration configuration, World world, BlockPos originalPos, Direction assumedNorth, PlayerEntity player) { return false; } /** * This method is used after the main building is build for any additional structures or modifications. * * @param configuration The structure configuration. * @param world The current world. * @param originalPos The original position clicked on. * @param assumedNorth The assumed northern direction. * @param player The player which initiated the construction. */ public void AfterBuilding(StructureConfiguration configuration, ServerWorld world, BlockPos originalPos, Direction assumedNorth, PlayerEntity player) { } protected void ClearSpace(StructureConfiguration configuration, World world, BlockPos originalPos, Direction assumedNorth) { if (this.clearSpace.getShape().getWidth() > 0 && this.clearSpace.getShape().getLength() > 0) { BlockPos startBlockPos = this.clearSpace.getStartingPosition().getRelativePosition(originalPos, this.clearSpace.getShape().getDirection(), configuration.houseFacing); BlockPos endBlockPos = startBlockPos .offset(configuration.houseFacing.getOpposite().rotateY(), this.clearSpace.getShape().getWidth() - 1) .offset(configuration.houseFacing.getOpposite(), this.clearSpace.getShape().getLength() - 1) .offset(Direction.UP, this.clearSpace.getShape().getHeight()); this.clearedBlockPos = new ArrayList<>(); for (BlockPos pos : BlockPos.getAllInBoxMutable(startBlockPos, endBlockPos)) { if (this.BlockShouldBeClearedDuringConstruction(configuration, world, originalPos, assumedNorth, pos)) { this.clearedBlockPos.add(new BlockPos(pos)); this.allBlockPositions.add(new BlockPos(pos)); } } } else { this.clearedBlockPos = new ArrayList<>(); } } protected Boolean CustomBlockProcessingHandled(StructureConfiguration configuration, BuildBlock block, World world, BlockPos originalPos, Direction assumedNorth, Block foundBlock, BlockState blockState, PlayerEntity player) { return false; } protected Boolean BlockShouldBeClearedDuringConstruction(StructureConfiguration configuration, World world, BlockPos originalPos, Direction assumedNorth, BlockPos blockPos) { return true; } /** * Determines if a water block was replaced with cobblestone because this structure was built in the nether or the * end. * * @param configuration The structure configuration. * @param block The build block object. * @param world The workd object. * @param originalPos The original block position this structure was built on. * @param assumedNorth The assumed north direction (typically north). * @param foundBlock The actual block found at the current location. * @param blockState The block state to set for the current block. * @param player The player requesting this build. * @return Returns true if the water block was replaced by cobblestone, otherwise false. */ protected Boolean WaterReplacedWithCobbleStone(StructureConfiguration configuration, BuildBlock block, World world, BlockPos originalPos, Direction assumedNorth, Block foundBlock, BlockState blockState, PlayerEntity player) { // Replace water blocks with cobblestone when this is not the overworld. // TODO: World.field_234918_g_ gets the RegistryKey<World> for the general 'overworld' world. // TODO: world.func_234923_W_ gets the RegistryKey<World> for the current world. if (foundBlock instanceof FlowingFluidBlock && blockState.getMaterial() == Material.WATER && (World.field_234918_g_.compareTo(world.func_234923_W_()) != 0)) { block.setBlockDomain(Blocks.COBBLESTONE.getRegistryName().getNamespace()); block.setBlockName(Blocks.COBBLESTONE.getRegistryName().getPath()); block.setBlockState(Blocks.COBBLESTONE.getDefaultState()); // Add this as a priority 3 block since it should be done at the end. this.priorityThreeBlocks.add(block); return true; } return false; } }
package io.lkr.jacrtadministrationback.po; import java.util.Date; public class Administrator { private Integer administratorId; private String username; private String realName; private String email; private String encryptedPassword; private Byte status; private Date createTime; private String avatarUrl; public Integer getAdministratorId() { return administratorId; } public void setAdministratorId(Integer administratorId) { this.administratorId = administratorId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName == null ? null : realName.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getEncryptedPassword() { return encryptedPassword; } public void setEncryptedPassword(String encryptedPassword) { this.encryptedPassword = encryptedPassword == null ? null : encryptedPassword.trim(); } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getAvatarUrl() { return avatarUrl; } public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl == null ? null : avatarUrl.trim(); } }
package tech.yaog.utils.statemachine; import android.util.Log; /** * Android Logcat 默认Log输出 * Created by ygl_h on 2017/9/10. */ public class LogcatLogger implements Logger { protected String getMessage(String format, Object... args) { String message; if (args.length > 0) { message = String.format(format, args); } else { message = format; } return message; } @Override public void v(String tag, String format, Object... args) { Log.v(tag, getMessage(format, args)); } @Override public void d(String tag, String format, Object... args) { Log.d(tag, getMessage(format, args)); } @Override public void i(String tag, String format, Object... args) { Log.i(tag, getMessage(format, args)); } @Override public void w(String tag, String format, Object... args) { Log.w(tag, getMessage(format, args)); } @Override public void e(String tag, String format, Object... args) { Log.e(tag, getMessage(format, args)); } }
package peng.springframework.circulation; public class Husband { private Wife wife; public String queryWife(){ return "Husband.wife"; } public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } }
package org.asteriskjava.tools; import org.asteriskjava.live.DefaultAsteriskServer; import org.asteriskjava.manager.ManagerEventListener; import org.asteriskjava.manager.event.*; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A diagnostic tool that creates an HTML file showing the state changing events * received from Asterisk on the Manager API.<p> * The following events are shown: * <ul> * <li>NewChannel</li> * <li>NewState</li> * <li>Rename</li> * <li>Dial</li> * <li>Bridge (Link and Unlink)</li> * <li>Hangup</li> * </ul> * Usage: java org.asteriskjava.tools.HtmlEventTracer host username password * * @version $Id$ */ public class HtmlEventTracer implements ManagerEventListener { private String filename = "trace.html"; private PrintWriter writer; private final List<String> uniqueIds; private final List<ManagerEvent> events; private final Map<Class<? extends ManagerEvent>, String> colors; public HtmlEventTracer() { uniqueIds = new ArrayList<String>(); events = new ArrayList<ManagerEvent>(); colors = new HashMap<Class<? extends ManagerEvent>, String>(); colors.put(NewChannelEvent.class, "#7cd300"); // green colors.put(NewStateEvent.class, "#a4b6c8"); colors.put(NewExtenEvent.class, "#efefef"); // grey colors.put(RenameEvent.class, "#ddeeff"); // light blue colors.put(DialEvent.class, "#feec30"); // yellow colors.put(BridgeEvent.class, "#fff8ae"); // light yellow colors.put(HangupEvent.class, "#ff6c17"); // orange try { writer = new PrintWriter(filename); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Usage: java org.asteriskjava.tools.HtmlEventTracer host username password"); System.exit(1); } final HtmlEventTracer tracer; final DefaultAsteriskServer server; tracer = new HtmlEventTracer(); server = new DefaultAsteriskServer(args[0], args[1], args[2]); server.initialize(); server.getManagerConnection().addEventListener(tracer); System.err.println("Event tracer successfully started. Press Ctrl-C to write trace file and exit."); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { tracer.write(); server.shutdown(); } } ); while(true) { Thread.sleep(1000); } } public void onManagerEvent(ManagerEvent event) { events.add(event); System.out.println("> " + event); for (String property : new String[]{"uniqueId", "uniqueId1", "uniqueId2", "srcUniqueId", "destUniqueId"}) { String uniqueId; uniqueId = getProperty(event, property); if (uniqueId != null && !uniqueIds.contains(uniqueId)) { uniqueIds.add(uniqueId); } } } public void write() { writer.append("<table border='1'><tr><td> </td>"); for (String uniqueId : uniqueIds) { writer.append("<td><font size='-2'>"); writer.append(uniqueId.substring(0, uniqueId.lastIndexOf('.') + 1)); writer.append("</font>"); writer.append(uniqueId.substring(uniqueId.lastIndexOf('.') + 1, uniqueId.length())); writer.append("</td>"); } writer.append("</tr>"); writer.println(""); for (ManagerEvent event : events) { boolean print = false; StringBuilder line = new StringBuilder(); line.append("<tr><td>"); line.append(event.getClass().getSimpleName()); line.append("<br><font size='-2'>"); line.append(event.getDateReceived()); line.append("</font></td>"); for (String uniqueId : uniqueIds) { String text; text = getText(uniqueId, event); if (text == null) { line.append("<td> </td>"); } else { String color = getColor(event.getClass()); line.append("<td bgcolor='").append(color).append("'><tt>").append(text).append("</tt></td>"); print = true; } } line.append("</tr>"); if (print) { writer.println(line.toString()); } } writer.append("</table>"); writer.close(); System.err.println("Trace file successfully written to " + filename + "."); } private String getColor(Class<? extends ManagerEvent> clazz) { for (Map.Entry<Class<? extends ManagerEvent>, String> entry : colors.entrySet()) { if (entry.getKey().isAssignableFrom(clazz)) { return entry.getValue(); } } return "#ffffff"; } protected String getProperty(Object obj, String property) { try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) { if (!propertyDescriptor.getName().equals(property)) { continue; } final Object o = propertyDescriptor.getReadMethod().invoke(obj); return o != null ? o.toString() : null; } } catch (Exception e) { System.err.println("Unable to read property '" + property + "' from object " + obj + ": " + e.getMessage()); return null; } return null; } protected String getText(String uniqueId, ManagerEvent event) { String format = null; String[] properties = null; if (uniqueId.equals(getProperty(event, "uniqueId"))) { if (event instanceof NewChannelEvent) { format = "%s<br>%s"; properties = new String[]{"channel", "state"}; } else if (event instanceof NewStateEvent) { format = "%s<br>%s"; properties = new String[]{"channel", "state"}; } else if (event instanceof NewExtenEvent) { format = "%s,%s,%s<br>%s(%s)"; properties = new String[]{"context", "extension", "priority", "application", "appData"}; } else if (event instanceof RenameEvent) { format = "old: %s<br>new: %s"; properties = new String[]{"oldname", "newname"}; } else if (event instanceof HoldEvent) { format = "%s"; properties = new String[]{"status"}; } else if (event instanceof AbstractParkedCallEvent) { format = "exten: %s<br>from: %s"; properties = new String[]{"exten", "from"}; } else if (event instanceof HangupEvent) { format = "%s<br>%s (%s)"; properties = new String[]{"channel", "cause", "causeTxt"}; } else if (event instanceof AntennaLevelEvent) { format = "%s"; properties = new String[]{"signal"}; } else if (event instanceof PausedEvent) { format = "(%s) %s"; properties = new String[]{"header", "extension"}; } else if (event instanceof UnpausedEvent) { format = "(%s) %s"; properties = new String[]{"header", "extension"}; } } if (event instanceof BridgeEvent) { if (uniqueId.equals(getProperty(event, "uniqueId1"))) { format = "%s<br>%s<br>%s"; properties = new String[]{"uniqueId2", "channel2", "bridgeState"}; } else if (uniqueId.equals(getProperty(event, "uniqueId2"))) { format = "%s<br>%s<br>%s"; properties = new String[]{"uniqueId1", "channel1", "bridgeState"}; } } if (event instanceof DialEvent) { if (uniqueId.equals(getProperty(event, "srcUniqueId"))) { format = "To: %s"; properties = new String[]{"destination"}; } else if (uniqueId.equals(getProperty(event, "destUniqueId"))) { format = "From: %s"; properties = new String[]{"src"}; } } if (format != null) { String[] args = new String[properties.length]; for (int i = 0; i < properties.length; i++) { String value; value = getProperty(event, properties[i]); if (value == null) { args[i] = ""; } else { value = value.replace("<", "&lt;"); value = value.replace(">", "&gt;"); args[i] = value; } } return String.format(format, (Object[]) args); } return null; } }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * <p>This source code is licensed under the MIT license found in the LICENSE file in the root * directory of this source tree. */ package pet.myplant.myplantpet; import android.content.Context; import com.facebook.flipper.android.AndroidFlipperClient; import com.facebook.flipper.android.utils.FlipperUtils; import com.facebook.flipper.core.FlipperClient; import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; import com.facebook.flipper.plugins.inspector.DescriptorMapping; import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; import com.facebook.flipper.plugins.react.ReactFlipperPlugin; import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; import com.facebook.react.ReactInstanceManager; import com.facebook.react.bridge.ReactContext; import com.facebook.react.modules.network.NetworkingModule; import okhttp3.OkHttpClient; public class ReactNativeFlipper { public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { if (FlipperUtils.shouldEnableFlipper(context)) { final FlipperClient client = AndroidFlipperClient.getInstance(context); client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); client.addPlugin(new ReactFlipperPlugin()); client.addPlugin(new DatabasesFlipperPlugin(context)); client.addPlugin(new SharedPreferencesFlipperPlugin(context)); client.addPlugin(CrashReporterPlugin.getInstance()); NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); NetworkingModule.setCustomClientBuilder( new NetworkingModule.CustomClientBuilder() { @Override public void apply(OkHttpClient.Builder builder) { builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); } }); client.addPlugin(networkFlipperPlugin); client.start(); // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized // Hence we run if after all native modules have been initialized ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); if (reactContext == null) { reactInstanceManager.addReactInstanceEventListener( new ReactInstanceManager.ReactInstanceEventListener() { @Override public void onReactContextInitialized(ReactContext reactContext) { reactInstanceManager.removeReactInstanceEventListener(this); reactContext.runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { client.addPlugin(new FrescoFlipperPlugin()); } }); } }); } else { client.addPlugin(new FrescoFlipperPlugin()); } } } }
/* * SMASH * * This file was automatically generated for the SMASH API by SMASH, INC ( https://smashlabs.io ). */ package SMASH.models; import java.util.*; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; public class DataModel extends BaseModel implements java.io.Serializable { private static final long serialVersionUID = 4671515605445585593L; private String result; private String content; private String id; /** GETTER * TODO: Write general description for this method */ @JsonGetter("result") public String getResult ( ) { return this.result; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("result") public void setResult (String value) { this.result = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("content") public String getContent ( ) { return this.content; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("content") public void setContent (String value) { this.content = value; } /** GETTER * TODO: Write general description for this method */ @JsonGetter("id") public String getId ( ) { return this.id; } /** SETTER * TODO: Write general description for this method */ @JsonSetter("id") public void setId (String value) { this.id = value; } }
package org.opensha.oaf.aafs; /** * Common base class for server components. * Author: Michael Barall 06/23/2018. */ public class ServerComponent { //----- Constant definitions ----- // // These constants are known to every server component. // Opcodes. public static final int OPCODE_MIN = 1; // Minimum allowed opcode public static final int OPCODE_NO_OP = 1; // No operation public static final int OPCODE_SHUTDOWN = 2; // Shut down the server public static final int OPCODE_CON_MESSAGE = 3; // Write message to console public static final int OPCODE_GEN_FORECAST = 4; // Generate forecast public static final int OPCODE_GEN_PDL_REPORT = 5; // Generate delayed forecast report to PDL public static final int OPCODE_GEN_EXPIRE = 6; // Stop generation, mark the timeline expired public static final int OPCODE_INTAKE_SYNC = 7; // Intake an event, from sync public static final int OPCODE_INTAKE_PDL = 8; // Intake an event, from PDL public static final int OPCODE_ANALYST_INTERVENE = 9; // Analyst intervention public static final int OPCODE_UNKNOWN = 10; // Unknown operation public static final int OPCODE_ALIAS_SPLIT = 11; // Notification of alias timeline split public static final int OPCODE_ALIAS_STOP = 12; // Notification of alias timeline stop public static final int OPCODE_ALIAS_REVIVE = 13; // Notification of alias timeline revive public static final int OPCODE_INTAKE_POLL = 14; // Intake an event, from poll public static final int OPCODE_POLL_COMCAT_RUN = 15; // Run a poll of Comcat to discover events public static final int OPCODE_POLL_COMCAT_START = 16; // Start polling Comcat to discover events public static final int OPCODE_POLL_COMCAT_STOP = 17; // Stop polling Comcat to discover events public static final int OPCODE_NEXT_TIMELINE_OP = 18; // Issue next delayed operation for a timeline public static final int OPCODE_CLEANUP_PDL_START = 19; // Start cleaning up old forecasts in PDL public static final int OPCODE_CLEANUP_PDL_STOP = 20; // Stop cleaning up old forecasts in PDL public static final int OPCODE_SET_RELAY_MODE = 21; // Set server relay mode public static final int OPCODE_ANALYST_SELECTION = 22; // Analyst selection of options public static final int OPCODE_MAX = 22; // Maximum allowed opcode // Return a string describing an opcode. public String get_opcode_as_string (int x) { switch (x) { case OPCODE_NO_OP: return "OPCODE_NO_OP"; case OPCODE_SHUTDOWN: return "OPCODE_SHUTDOWN"; case OPCODE_CON_MESSAGE: return "OPCODE_CON_MESSAGE"; case OPCODE_GEN_FORECAST: return "OPCODE_GEN_FORECAST"; case OPCODE_GEN_PDL_REPORT: return "OPCODE_GEN_PDL_REPORT"; case OPCODE_GEN_EXPIRE: return "OPCODE_GEN_EXPIRE"; case OPCODE_INTAKE_SYNC: return "OPCODE_INTAKE_SYNC"; case OPCODE_INTAKE_PDL: return "OPCODE_INTAKE_PDL"; case OPCODE_ANALYST_INTERVENE: return "OPCODE_ANALYST_INTERVENE"; case OPCODE_UNKNOWN: return "OPCODE_UNKNOWN"; case OPCODE_ALIAS_SPLIT: return "OPCODE_ALIAS_SPLIT"; case OPCODE_ALIAS_STOP: return "OPCODE_ALIAS_STOP"; case OPCODE_ALIAS_REVIVE: return "OPCODE_ALIAS_REVIVE"; case OPCODE_INTAKE_POLL: return "OPCODE_INTAKE_POLL"; case OPCODE_POLL_COMCAT_RUN: return "OPCODE_POLL_COMCAT_RUN"; case OPCODE_POLL_COMCAT_START: return "OPCODE_POLL_COMCAT_START"; case OPCODE_POLL_COMCAT_STOP: return "OPCODE_POLL_COMCAT_STOP"; case OPCODE_NEXT_TIMELINE_OP: return "OPCODE_NEXT_TIMELINE_OP"; case OPCODE_CLEANUP_PDL_START: return "OPCODE_CLEANUP_PDL_START"; case OPCODE_CLEANUP_PDL_STOP: return "OPCODE_CLEANUP_PDL_STOP"; case OPCODE_SET_RELAY_MODE: return "OPCODE_SET_RELAY_MODE"; case OPCODE_ANALYST_SELECTION: return "OPCODE_ANALYST_SELECTION"; } return "OPCODE_INVALID(" + x + ")"; } // Special execution times. public static final long EXEC_TIME_ACTIVE = 0L; // Task is active public static final long EXEC_TIME_MIN_WAITING = 1L; // Minimum execution time for waiting tasks public static final long EXEC_TIME_MIN_PROMPT = 10000000L; // Minimum execution time for prompt tasks, 10^7 ~ 2.8 hours public static final long EXEC_TIME_MAX_PROMPT = 19000000L; // Maximum execution time for prompt tasks public static final long EXEC_TIME_SHUTDOWN = 20000000L; // Execution time for shutdown task, 2*10^7 ~ 5.6 hours public static final long EXEC_TIME_FAR_FUTURE = 1000000000000000L; // 10^15 ~ 30,000 years // Result codes. public static final int RESCODE_MIN_NORMAL = 1; // Minimum known normal result code public static final int RESCODE_SUCCESS = 1; // Task completed successfully public static final int RESCODE_TASK_CORRUPT = 2; // Task entry or payload was corrupted, task discarded public static final int RESCODE_TIMELINE_CORRUPT = 3; // Timeline entry or payload was corrupted, task discarded public static final int RESCODE_TIMELINE_NOT_FOUND = 4; // Timeline entry not found, task discarded public static final int RESCODE_TIMELINE_NOT_ACTIVE = 5; // Timeline entry not active, task discarded public static final int RESCODE_TIMELINE_TASK_MISMATCH = 6; // Timeline entry has lag values that do not match the forecast task public static final int RESCODE_TIMELINE_COMCAT_FAIL = 7; // Timeline stopped due to ComCat failure public static final int RESCODE_TIMELINE_WITHDRAW = 8; // Timeline stopped due to event not passing intake filter public static final int RESCODE_TIMELINE_FORESHOCK = 9; // Timeline stopped because event was found to be a foreshock public static final int RESCODE_TIMELINE_NOT_PDL_PEND = 10; // Timeline entry does not have a PDL report pending, task discarded public static final int RESCODE_TIMELINE_PDL_FAIL = 11; // Timeline attempt to send PDL report failed, sending abandoned public static final int RESCODE_TIMELINE_EXISTS = 12; // Timeline already exists, task discarded public static final int RESCODE_TASK_RETRY_SUCCESS = 13; // Task completed on task dispatcher retry public static final int RESCODE_TIMELINE_STATE_UPDATE = 14; // Timeline state was updated public static final int RESCODE_INTAKE_COMCAT_FAIL = 15; // Event intake failed due to ComCat failure public static final int RESCODE_TIMELINE_ANALYST_SET = 16; // Timeline analyst data was set public static final int RESCODE_TIMELINE_ANALYST_FAIL = 17; // Timeline analyst intervention failed due to bad state public static final int RESCODE_TIMELINE_ANALYST_NONE = 18; // Timeline analyst intervention not done public static final int RESCODE_ALIAS_TIMELINE_NOT_FOUND = 19; // Timeline ID not found in the alias table public static final int RESCODE_ALIAS_STOPPED = 20; // Timeline ID refers to a stopped timeline in the alias table public static final int RESCODE_ALIAS_NEW_EVENT = 21; // Event ID does not appear in the alias table, can be a new timeline public static final int RESCODE_ALIAS_EVENT_NOT_IN_COMCAT = 22; // Event ID is not known to Comcat, cannot query the alias table public static final int RESCODE_INTAKE_FILTERED = 23; // Event intake dropped because event did not pass intake filter public static final int RESCODE_FORECAST_STALE = 24; // Forecast skipped because it would be stale public static final int RESCODE_FORECAST_INTAKE_FILTERED = 25; // Forecast skipped because event did not pass intake filter public static final int RESCODE_FORECAST_ANALYST_BLOCKED = 26; // Forecast skipped because analyst blocked it public static final int RESCODE_FORECAST_SHADOWED = 27; // Forecast skipped because the event is shadowed public static final int RESCODE_FORECAST_FORESHOCK = 28; // Forecast skipped because event was found to be a foreshock public static final int RESCODE_INTAKE_AGED = 29; // Event intake dropped because event was outside age range public static final int RESCODE_TIMELINE_EVENT_REMOVED = 30; // Timeline stopped due to event removed or merged in Comcat public static final int RESCODE_TIMELINE_PDL_NO_FORECAST = 31; // PDL send failed because unable to locate forecast in timeline public static final int RESCODE_TIMELINE_PDL_BAD_FORECAST = 32; // PDL send failed because unable to interpret forecast in timeline public static final int RESCODE_TIMELINE_PDL_NO_CATALOG = 33; // PDL send failed because unable to locate catalog snapshot public static final int RESCODE_TIMELINE_PDL_BAD_CATALOG = 34; // PDL send failed because unable to interpret catalog snapshot public static final int RESCODE_TIMELINE_PDL_CAT_MISMATCH = 35; // PDL send failed because of catalog snapshot parameter mismatch public static final int RESCODE_TIMELINE_ID_INVALID = 36; // Timeline ID does not have a valid form public static final int RESCODE_PDL_SECONDARY = 37; // PDL operation skipped because this is a secondary server public static final int RESCODE_FORECAST_CANCELED = 38; // Forecast canceled due to secondary-to-primary transition public static final int RESCODE_PDL_CANCELED = 39; // PDL send canceled due to secondary-to-primary transition public static final int RESCODE_EXPIRE_CANCELED = 40; // Expire operation canceled due to secondary-to-primary transition public static final int RESCODE_PDL_CONFIRMED = 41; // PDL operation on other server is confirmed public static final int RESCODE_ANALYST_OPTIONS_STALE = 42; // Analyst options were already set or superseded public static final int RESCODE_ANALYST_OPTIONS_BAD = 43; // Analyst options are invalid public static final int RESCODE_MAX_NORMAL = 43; // Maximum known normal result code public static final int RESCODE_DELETE = 101; // Delete current task (without logging it) public static final int RESCODE_DELETE_TIMELINE_EXISTS = 102; // Delete current task (without logging it), because timeline already exists public static final int RESCODE_DELETE_INTAKE_FILTERED = 103; // Delete current task (without logging it), because event did not pass intake filter public static final int RESCODE_DELETE_INTAKE_AGED = 104; // Delete current task (without logging it), because event intake was outside age range public static final int RESCODE_DELETE_TIMELINE_NO_ALIAS = 105; // Delete current task (without logging it), because timeline has no active alias public static final int RESCODE_DELETE_TIMELINE_BAD_STATE = 106; // Delete current task (without logging it), because timeline state does not permit operation public static final int RESCODE_DELETE_NOT_IN_COMCAT = 107; // Delete current task (without logging it), because event is not in Comcat public static final int RESCODE_DELETE_INTAKE_BLOCKED = 108; // Delete current task (without logging it), because event intake is blocked public static final int RESCODE_STAGE = 201; // Stage current task (execute it again) public static final int RESCODE_STAGE_COMCAT_RETRY = 202; // Stage current task (execute it again), to retry a failed Comcat operation public static final int RESCODE_STAGE_PDL_RETRY = 203; // Stage current task (execute it again), to retry a failed PDL send public static final int RESCODE_STAGE_EVENT_ID = 204; // Stage current task (execute it again), to insert event ID public static final int RESCODE_STAGE_TIMELINE_ID = 205; // Stage current task (execute it again), to insert timeline ID public static final int RESCODE_STAGE_TOO_SOON = 206; // Stage current task (execute it again), because it is too soon for the operation public static final int RESCODE_STAGE_REPEATING_TASK = 207; // Stage current task (execute it again), because it is a repeating task // Return a string describing a result code. public String get_rescode_as_string (int x) { switch (x) { case RESCODE_SUCCESS: return "RESCODE_SUCCESS"; case RESCODE_TASK_CORRUPT: return "RESCODE_TASK_CORRUPT"; case RESCODE_TIMELINE_CORRUPT: return "RESCODE_TIMELINE_CORRUPT"; case RESCODE_TIMELINE_NOT_FOUND: return "RESCODE_TIMELINE_NOT_FOUND"; case RESCODE_TIMELINE_NOT_ACTIVE: return "RESCODE_TIMELINE_NOT_ACTIVE"; case RESCODE_TIMELINE_TASK_MISMATCH: return "RESCODE_TIMELINE_TASK_MISMATCH"; case RESCODE_TIMELINE_COMCAT_FAIL: return "RESCODE_TIMELINE_COMCAT_FAIL"; case RESCODE_TIMELINE_WITHDRAW: return "RESCODE_TIMELINE_WITHDRAW"; case RESCODE_TIMELINE_FORESHOCK: return "RESCODE_TIMELINE_FORESHOCK"; case RESCODE_TIMELINE_NOT_PDL_PEND: return "RESCODE_TIMELINE_NOT_PDL_PEND"; case RESCODE_TIMELINE_PDL_FAIL: return "RESCODE_TIMELINE_PDL_FAIL"; case RESCODE_TIMELINE_EXISTS: return "RESCODE_TIMELINE_EXISTS"; case RESCODE_TASK_RETRY_SUCCESS: return "RESCODE_TASK_RETRY_SUCCESS"; case RESCODE_TIMELINE_STATE_UPDATE: return "RESCODE_TIMELINE_STATE_UPDATE"; case RESCODE_INTAKE_COMCAT_FAIL: return "RESCODE_INTAKE_COMCAT_FAIL"; case RESCODE_TIMELINE_ANALYST_SET: return "RESCODE_TIMELINE_ANALYST_SET"; case RESCODE_TIMELINE_ANALYST_FAIL: return "RESCODE_TIMELINE_ANALYST_FAIL"; case RESCODE_TIMELINE_ANALYST_NONE: return "RESCODE_TIMELINE_ANALYST_NONE"; case RESCODE_ALIAS_TIMELINE_NOT_FOUND: return "RESCODE_ALIAS_TIMELINE_NOT_FOUND"; case RESCODE_ALIAS_STOPPED: return "RESCODE_ALIAS_STOPPED"; case RESCODE_ALIAS_NEW_EVENT: return "RESCODE_ALIAS_NEW_EVENT"; case RESCODE_ALIAS_EVENT_NOT_IN_COMCAT: return "RESCODE_ALIAS_EVENT_NOT_IN_COMCAT"; case RESCODE_INTAKE_FILTERED: return "RESCODE_INTAKE_FILTERED"; case RESCODE_FORECAST_STALE: return "RESCODE_FORECAST_STALE"; case RESCODE_FORECAST_INTAKE_FILTERED: return "RESCODE_FORECAST_INTAKE_FILTERED"; case RESCODE_FORECAST_ANALYST_BLOCKED: return "RESCODE_FORECAST_ANALYST_BLOCKED"; case RESCODE_FORECAST_SHADOWED: return "RESCODE_FORECAST_SHADOWED"; case RESCODE_FORECAST_FORESHOCK: return "RESCODE_FORECAST_FORESHOCK"; case RESCODE_INTAKE_AGED: return "RESCODE_INTAKE_AGED"; case RESCODE_TIMELINE_EVENT_REMOVED: return "RESCODE_TIMELINE_EVENT_REMOVED"; case RESCODE_TIMELINE_PDL_NO_FORECAST: return "RESCODE_TIMELINE_PDL_NO_FORECAST"; case RESCODE_TIMELINE_PDL_BAD_FORECAST: return "RESCODE_TIMELINE_PDL_BAD_FORECAST"; case RESCODE_TIMELINE_PDL_NO_CATALOG: return "RESCODE_TIMELINE_PDL_NO_CATALOG"; case RESCODE_TIMELINE_PDL_BAD_CATALOG: return "RESCODE_TIMELINE_PDL_BAD_CATALOG"; case RESCODE_TIMELINE_PDL_CAT_MISMATCH: return "RESCODE_TIMELINE_PDL_CAT_MISMATCH"; case RESCODE_TIMELINE_ID_INVALID: return "RESCODE_TIMELINE_ID_INVALID"; case RESCODE_PDL_SECONDARY: return "RESCODE_PDL_SECONDARY"; case RESCODE_FORECAST_CANCELED: return "RESCODE_FORECAST_CANCELED"; case RESCODE_PDL_CANCELED: return "RESCODE_PDL_CANCELED"; case RESCODE_EXPIRE_CANCELED: return "RESCODE_EXPIRE_CANCELED"; case RESCODE_PDL_CONFIRMED: return "RESCODE_PDL_CONFIRMED"; case RESCODE_ANALYST_OPTIONS_STALE: return "RESCODE_ANALYST_OPTIONS_STALE"; case RESCODE_ANALYST_OPTIONS_BAD: return "RESCODE_ANALYST_OPTIONS_BAD"; case RESCODE_DELETE: return "RESCODE_DELETE"; case RESCODE_DELETE_TIMELINE_EXISTS: return "RESCODE_DELETE_TIMELINE_EXISTS"; case RESCODE_DELETE_INTAKE_FILTERED: return "RESCODE_DELETE_INTAKE_FILTERED"; case RESCODE_DELETE_INTAKE_AGED: return "RESCODE_DELETE_INTAKE_AGED"; case RESCODE_DELETE_TIMELINE_NO_ALIAS: return "RESCODE_DELETE_TIMELINE_NO_ALIAS"; case RESCODE_DELETE_TIMELINE_BAD_STATE: return "RESCODE_DELETE_TIMELINE_BAD_STATE"; case RESCODE_DELETE_NOT_IN_COMCAT: return "RESCODE_DELETE_NOT_IN_COMCAT"; case RESCODE_DELETE_INTAKE_BLOCKED: return "RESCODE_DELETE_INTAKE_BLOCKED"; case RESCODE_STAGE: return "RESCODE_STAGE"; case RESCODE_STAGE_COMCAT_RETRY: return "RESCODE_STAGE_COMCAT_RETRY"; case RESCODE_STAGE_PDL_RETRY: return "RESCODE_STAGE_PDL_RETRY"; case RESCODE_STAGE_EVENT_ID: return "RESCODE_STAGE_EVENT_ID"; case RESCODE_STAGE_TIMELINE_ID: return "RESCODE_STAGE_TIMELINE_ID"; case RESCODE_STAGE_TOO_SOON: return "RESCODE_STAGE_TOO_SOON"; case RESCODE_STAGE_REPEATING_TASK: return "RESCODE_STAGE_REPEATING_TASK"; } return "RESCODE_INVALID(" + x + ")"; } // Special event ids. public static final String EVID_SHUTDOWN = "===shutdown==="; // Shutdown task public static final String EVID_UNKNOWN = "===unknown==="; // Unknown event ID public static final String EVID_ERROR = "===error==="; // Error status public static final String EVID_ANALYST = "===analyst==="; // Used for analyst-selected shadowing public static final String EVID_POLL = "===poll==="; // Used for polling tasks public static final String EVID_CLEANUP = "===cleanup==="; // Used for cleanup tasks public static final String EVID_RELAY = "===relay==="; // Used for server relay tasks // Special submit ids. public static final String SUBID_AAFS = "AAFS"; // Automatic system // Special stage values. public static final int STAGE_CANCEL = -1; // Operation is being canceled // Special durations, in milliseconds. public static final long DURATION_DAY = 86400000L; // 1 day public static final long DURATION_YEAR = 31536000000L; // 1 year (365 days) public static final long DURATION_HUGE = 1000000000000000L; // 10^15 ~ 30,000 years // Logging. public static final String LOG_SEPARATOR_LINE = "------------------------------"; // Used to separate log entries // MongoDB related. public static final int MONGO_DUP_INTAKE_CLEANUP = 20; // Maxmimum duplicate intake commands to remove in a single transaction //----- Component access ----- // Server group. // This provides access to other server components. protected ServerGroup sg; //----- Construction ----- // Default constructor. public ServerComponent () { this.sg = null; } // Set up this component by linking to the server group. // A subclass may override this to perform additional setup operations. public void setup (ServerGroup the_sg) { this.sg = the_sg; return; } }
/* * Copyright (c) 2014. Pokevian 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.pokevian.app.smartfleet.model; import com.pokevian.caroo.common.smart.model.SmartCarModel; import com.pokevian.lib.obd2.defs.FuelType; import org.apache.log4j.Logger; import java.io.Serializable; public class VehicleModel implements Serializable, Cloneable { private static final long serialVersionUID = 1L; private long modelId; private String makerCode; private String makerName; private String typeCode; private String typeName; private String modelCode; private String modelName; private String fuelCode; private String engineName; private String engineCode; private int displacement; private float fuelEconomy; private int releaseYear; private int discontinuedYear; public VehicleModel() { } public long getModelId() { return modelId; } public void setModelId(long modelId) { this.modelId = modelId; } public String getMakerCode() { return makerCode; } public void setMakerCode(String makerCode) { this.makerCode = makerCode; } public String getMakerName() { return makerName; } public void setMakerName(String makerName) { this.makerName = makerName; } public String getTypeCode() { return typeCode; } public void setTypeCode(String typeCode) { this.typeCode = typeCode; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getModelCode() { return modelCode; } public void setModelCode(String modelCode) { this.modelCode = modelCode; } public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; } public String getFuelCode() { return fuelCode; } public void setFuelCode(String fuelCode) { this.fuelCode = fuelCode; } public String getEngineName() { return engineName; } public void setEngineName(String engineName) { this.engineName = engineName; } public String getEngineCode() { return engineCode; } public void setEngineCode(String engineCode) { this.engineCode = engineCode; } public int getDisplacement() { return displacement; } public void setDisplacement(int engineDisplacement) { this.displacement = engineDisplacement; } public float getFuelEconomy() { return fuelEconomy; } public void setFuelEconomy(float fuelEconomy) { this.fuelEconomy = fuelEconomy; } public int getReleaseYear() { return releaseYear; } public void setReleaseYear(int releaseYear) { this.releaseYear = releaseYear; } public int getDiscontinuedYear() { return discontinuedYear; } public void setDiscontinuedYear(int discontinuedYear) { this.discontinuedYear = discontinuedYear; } @Override public VehicleModel clone() { return new VehicleModel(this); } @Override public String toString() { return "VehicleModel{" + "modelId=" + modelId + ", makerCode='" + makerCode + '\'' + ", typeCode='" + typeCode + '\'' + ", modelCode='" + modelCode + '\'' + ", fuelCode='" + fuelCode + '\'' + ", engineCode='" + engineCode + '\'' + ", displacement=" + displacement + ", releaseYear=" + releaseYear + ", discontinuedYear=" + discontinuedYear + '}'; } public VehicleModel(VehicleModel other) { this.modelId = other.modelId; this.makerCode = other.makerCode; this.makerName = other.makerName; this.typeCode = other.typeCode; this.typeName = other.typeName; this.modelCode = other.modelCode; this.modelName = other.modelName; this.fuelCode = other.fuelCode; this.engineCode = other.engineCode; this.engineName = other.engineName; this.displacement = other.displacement; this.fuelEconomy = other.fuelEconomy; this.releaseYear = other.releaseYear; this.discontinuedYear = other.discontinuedYear; } public VehicleModel(SmartCarModel scm) { if (scm != null) { modelId = scm.getCarModelNo(); makerCode = scm.getCarMakerCd(); makerName = scm.getCarMakerName(); typeCode = scm.getCarTypeCd(); typeName = scm.getCarTypeName(); modelCode = scm.getCarModelNameCd(); modelName = scm.getCarModelName(); engineCode = scm.getCarSrcCd(); engineName = scm.getCarSrcName(); fuelCode = scm.getCarFuelCd(); displacement = scm.getEngineDisplacement(); fuelEconomy = scm.getFuelEconomy(); releaseYear = scm.getReleaseYear(); discontinuedYear = scm.getDiscontinuedYear(); } } public FuelType getFuelType() { if ("diesel".equals(fuelCode)) { return FuelType.DIESEL; } else if ("lpg".equals(fuelCode)) { return FuelType.LPG; } else if ("electric".equals(fuelCode)) { return FuelType.ELECTRIC; } else { // gasoline return FuelType.GASOLINE; } } }
package com.ulyssesss.leetcode.solution; import com.ulyssesss.leetcode.common.TreeNode; /** * 226. 翻转二叉树 * * 翻转一棵二叉树。 * * 示例: * * 输入: * * 4 * / \ * 2 7 * / \ / \ * 1 3 6 9 * 输出: * * 4 * / \ * 7 2 * / \ / \ * 9 6 3 1 * 备注: * 这个问题是受到 Max Howell 的 原问题 启发的 : * * 谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。 * */ public class _0226 { public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } TreeNode temp = root.left; root.left = invertTree(root.right); root.right = invertTree(temp); return root; } }
/* * 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.iceberg; public class MockFileScanTask extends BaseFileScanTask { private final long length; public MockFileScanTask(long length) { super(null, null, null, null, null); this.length = length; } @Override public long length() { return length; } @Override public String toString() { return "Mock Scan Task Size: " + length; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MockFileScanTask that = (MockFileScanTask) o; return length == that.length; } @Override public int hashCode() { return (int) (length ^ (length >>> 32)); } }
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0. package com.amazonaws.s3.model; import java.lang.String; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.aws.sdk.crt.annotations.Generated; @Generated("software.amazon.smithy.crt.java.EnumGenerator") public enum Permission { FULL_CONTROL("software.amazon.smithy.crt.codegen.Field@4932344b"), WRITE("software.amazon.smithy.crt.codegen.Field@4932344b"), WRITE_ACP("software.amazon.smithy.crt.codegen.Field@4932344b"), READ("software.amazon.smithy.crt.codegen.Field@4932344b"), READ_ACP("software.amazon.smithy.crt.codegen.Field@4932344b"), UNKNOWN_TO_SDK_VERSION(null); String value; private Permission(String value) { this.value = value; } public static Permission fromValue(String value) { if (value == null) { return null; } return Stream.of(com.amazonaws.s3.model.Permission.values()).filter(e -> e.toString().equals(value)).findFirst().orElse(UNKNOWN_TO_SDK_VERSION); } public static Set<Permission> knownValues() { return Stream.of(values()).filter(v -> v != UNKNOWN_TO_SDK_VERSION).collect(Collectors.toSet()); } public String value() { return value; } public void setValue(final String value) { this.value = value; } }
package com.mc.onmusic_relase.adapters; import android.annotation.SuppressLint; import android.app.Activity; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.graphics.Palette; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.transition.Transition; import com.mc.onmusic_relase.R; import com.mc.onmusic_relase.models.LocalModel; import com.mc.onmusic_relase.utils.YTutils; import java.io.File; import java.util.ArrayList; public class LocalAdapter extends RecyclerView.Adapter<LocalAdapter.LocalHolder> { Activity context; boolean isAlbumAdapter; ArrayList<LocalModel> models; private static final String TAG = "LocalAdapter"; SingleClickListener singleClickListener; LongClickListener longClickListener; public LocalAdapter(Activity context, ArrayList<LocalModel> models,boolean albumAdapter) { this.context = context; this.models = models; this.isAlbumAdapter = albumAdapter; } @NonNull @Override public LocalHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.artist_item, viewGroup, false); return new LocalHolder(v); } @Override public int getItemViewType(int position) { return position; } @SuppressLint("StaticFieldLeak") @Override public void onBindViewHolder(@NonNull LocalHolder localHolder, int i) { final LocalModel model = models.get(i); if (isAlbumAdapter) localHolder.aAlbumText.setVisibility(View.GONE); else { int s = model.getAlbumCount(); if (s==1) localHolder.aAlbumText.setText("1 album"); else localHolder.aAlbumText.setText(s+" albums"); } localHolder.aTitle.setText(model.getTitle()); if (model.getSongList().size()==1) localHolder.aSongText.setText("1 song"); else localHolder.aSongText.setText(model.getSongList().size()+" songs"); localHolder.cardView.setOnClickListener(view -> singleClickListener.onSingleClick(view,model,i)); localHolder.moreButton.setOnClickListener(view -> longClickListener.onLongClick(view,model,i)); if (model.getTitle().equals("Unknown artist")||model.getTitle().equals("Unknown album")) return; new AsyncTask<Void,Void,Void>() { String imageUri; @Override protected void onPostExecute(Void aVoid) { if (isAlbumAdapter) { if (model.getSongList().size()>0) { try { String line = model.getSongList().get(0); String filePath = line.split("\\|")[0]; File f = new File(filePath); MediaMetadataRetriever mmr = new MediaMetadataRetriever(); mmr.setDataSource(context, Uri.fromFile(f)); byte[] data = mmr.getEmbeddedPicture(); if (data!=null) { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); localHolder.aImage.setImageBitmap(bitmap); Palette.from(bitmap).generate(palette -> { int color = palette.getVibrantColor(context.getResources().getColor(R.color.background)); localHolder.cardView.setBackgroundTintList(ColorStateList.valueOf(color)); }); } }catch (Exception e) { Log.e(TAG, "onPostExecute: "+e.getMessage()); } } }else if (imageUri!=null) { Glide.with(context).asBitmap().load(imageUri).into(new CustomTarget<Bitmap>() { @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { localHolder.aImage.setImageBitmap(resource); Palette.from(resource).generate(palette -> { int color = palette.getVibrantColor(context.getResources().getColor(R.color.background)); localHolder.cardView.setBackgroundTintList(ColorStateList.valueOf(color)); }); } @Override public void onLoadCleared(@Nullable Drawable placeholder) { } }); } super.onPostExecute(aVoid); } @Override protected Void doInBackground(Void... voids) { if (isAlbumAdapter) { return null; } imageUri = YTutils.getLocalArtworkImage(context,model); return null; } }.execute(); } public interface LongClickListener { void onLongClick(View view, LocalModel model, int position); } public interface SingleClickListener { void onSingleClick(View view, LocalModel model, int position); } public void setSingleClickListener(SingleClickListener singleClickListener) { this.singleClickListener = singleClickListener; } public void setLongClickListener(LongClickListener longClickListener) { this.longClickListener = longClickListener; } @Override public int getItemCount() { return models.size(); } public class LocalHolder extends RecyclerView.ViewHolder { CardView cardView; TextView aTitle, aSongText,aAlbumText; ImageView moreButton, aImage; public LocalHolder(@NonNull View itemView) { super(itemView); cardView = itemView.findViewById(R.id.cardView); aTitle = itemView.findViewById(R.id.aTitle); aSongText = itemView.findViewById(R.id.aSongCount); aAlbumText = itemView.findViewById(R.id.aAlbumText); moreButton = itemView.findViewById(R.id.aMoreButton); aImage = itemView.findViewById(R.id.aImage); } } }
package org.everit.json.schema.loader; import static org.everit.json.schema.JSONMatcher.sameJsonAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.net.URI; import java.net.URISyntaxException; import org.everit.json.schema.ResourceLoader; import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.json.JSONObject; import org.junit.Test; public class ConfigurationPropagationTest { private static final ResourceLoader LOADER = new ResourceLoader("/org/everit/jsonvalidator/config-propagation/"); @Test public void configurationPropagationTest() throws URISyntaxException { SchemaLoader loader = SchemaLoader.builder() .schemaClient(SchemaClient.classPathAwareClient()) .nullableSupport(true) .useDefaults(true) .registerSchemaByURI(new URI("urn:uuid:85946d9c-b896-496c-a7ac-6835f4b59f63"), LOADER.readObj("schema-by-urn.json")) .addFormatValidator(new CustomFormatValidatorTest.EvenCharNumValidator()) .schemaJson(LOADER.readObj("schema.json")) .build(); Schema actual = loader.load().build(); JSONObject instance = LOADER.readObj("instance.json"); try { actual.validate(instance); fail("did not throw validation exception"); } catch (ValidationException e) { assertThat(e.toJSON(), sameJsonAs(LOADER.readObj("expected-exception.json"))); } assertEquals(42, instance.get("propWithDefault")); } }
/** * Copyright 2006-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.generator.codegen.mybatis3.javamapper.elements; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.Interface; import org.mybatis.generator.api.dom.java.JavaVisibility; import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.Parameter; /** * * @author Jeff Butler * */ public class SelectByPrimaryKeyMethodGenerator extends AbstractJavaMapperMethodGenerator { private boolean isSimple; public SelectByPrimaryKeyMethodGenerator(boolean isSimple) { super(); this.isSimple = isSimple; } @Override public void addInterfaceElements(Interface interfaze) { Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>(); Method method = new Method(); method.setVisibility(JavaVisibility.PUBLIC); FullyQualifiedJavaType returnType = introspectedTable.getRules() .calculateAllFieldsClass(); method.setReturnType(returnType); importedTypes.add(returnType); method.setName(introspectedTable.getSelectByPrimaryKeyStatementId()); if (!isSimple && introspectedTable.getRules().generatePrimaryKeyClass()) { FullyQualifiedJavaType type = new FullyQualifiedJavaType( introspectedTable.getPrimaryKeyType()); importedTypes.add(type); method.addParameter(new Parameter(type, "key")); //$NON-NLS-1$ } else { // no primary key class - fields are in the base class // if more than one PK field, then we need to annotate the // parameters // for MyBatis3 List<IntrospectedColumn> introspectedColumns = introspectedTable .getPrimaryKeyColumns(); boolean annotate = introspectedColumns.size() > 1; if (annotate) { importedTypes.add(new FullyQualifiedJavaType( "org.apache.ibatis.annotations.Param")); //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(); for (IntrospectedColumn introspectedColumn : introspectedColumns) { FullyQualifiedJavaType type = introspectedColumn .getFullyQualifiedJavaType(); importedTypes.add(type); Parameter parameter = new Parameter(type, introspectedColumn .getJavaProperty()); if (annotate) { sb.setLength(0); sb.append("@Param(\""); //$NON-NLS-1$ sb.append(introspectedColumn.getJavaProperty()); sb.append("\")"); //$NON-NLS-1$ parameter.addAnnotation(sb.toString()); } method.addParameter(parameter); } } addMapperAnnotations(interfaze, method); context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable); if (context.getPlugins().clientSelectByPrimaryKeyMethodGenerated( method, interfaze, introspectedTable)) { interfaze.addImportedTypes(importedTypes); interfaze.addMethod(method); } } public void addMapperAnnotations(Interface interfaze, Method method) { } }
/* * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.lang.System; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Properties; import java.util.stream.Collectors; import org.testng.Assert; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /* * @test * @bug 4463345 4244670 8030781 8265989 * @summary Simple test of System getProperty, setProperty, clearProperty, * getProperties, and setProperties * @run testng/othervm PropertyTest */ @Test public class PropertyTest { @DataProvider(name = "requiredProperties") static Object[][] requiredProperties() { return new Object[][]{ {"java.version"}, {"java.version.date"}, {"java.vendor"}, {"java.vendor.url"}, {"java.home"}, {"java.vm.specification.version"}, {"java.vm.specification.vendor"}, {"java.vm.specification.name"}, {"java.vm.version"}, {"java.vm.vendor"}, {"java.vm.name"}, {"java.specification.version"}, {"java.specification.vendor"}, {"java.specification.name"}, {"java.class.version"}, {"java.class.path"}, {"java.library.path"}, {"java.io.tmpdir"}, {"os.arch"}, {"os.version"}, {"file.separator"}, {"path.separator"}, {"line.separator"}, {"user.name"}, {"user.home"}, {"user.dir"}, {"java.runtime.version"}, {"java.runtime.name"}, {"native.encoding"}, }; } @Test static void getTest() { System.setProperty("blah", "blech"); Assert.assertEquals(System.getProperty("blah"), "blech"); try { System.getProperty(null); Assert.fail("Failed: expected NullPointerException"); } catch (NullPointerException npe) { // Correct result } try { System.getProperty(""); Assert.fail("Failed: expected IllegalArgumentException"); } catch (IllegalArgumentException iae) { // Correct result } } @Test static void clearTest() { System.setProperty("blah", "blech"); Assert.assertEquals(System.getProperty("blah"), "blech"); System.clearProperty("blah"); Assert.assertNull(System.getProperty("blah")); try { System.clearProperty(null); Assert.fail("Failed: expected NullPointerException"); } catch (NullPointerException npe) { // Correct result } try { System.clearProperty(""); Assert.fail("Failed: expected IllegalArgumentException"); } catch (IllegalArgumentException iae) { // Correct result } } @Test static void setTest() { System.setProperty("blah", "blech"); Assert.assertEquals(System.getProperty("blah"), "blech"); System.setProperty("blah", ""); Assert.assertEquals(System.getProperty("blah"), ""); try { System.setProperty(null, null); Assert.fail("Failed: expected NullPointerException"); } catch (NullPointerException npe) { // Correct result } try { System.setProperty("blah", null); Assert.fail("Failed: expected NullPointerException"); } catch (NullPointerException npe) { // Correct result } try { System.setProperty(null, "blech"); Assert.fail("Failed: expected NullPointerException"); } catch (NullPointerException npe) { // Correct result } try { System.setProperty("", "blech"); Assert.fail("Failed: expected IllegalArgumentException"); } catch (IllegalArgumentException iae) { // Correct result } try { System.setProperty("", ""); Assert.fail("Failed: expected IllegalArgumentException"); } catch (IllegalArgumentException iae) { // Correct result } } @Test static void replaceSetProperties() { Properties oldProps = System.getProperties(); Properties newProps = new Properties(); oldProps.forEach( (k,v) -> newProps.put(k,v)); System.setProperties(newProps); Assert.assertSame(System.getProperties(), newProps, "getProperties not the same as setProperties"); final String KEY = "blah"; final String VALUE = "blech"; // Set via Property instance; get via System methods newProps.setProperty(KEY, VALUE); Assert.assertEquals(System.getProperty(KEY), VALUE, KEY); String s = (String)newProps.remove(KEY); Assert.assertEquals(s, VALUE); Assert.assertNull(System.getProperty(KEY), KEY); // Set via System methods; Get via Property instance; System.setProperty(KEY, VALUE); Assert.assertEquals(newProps.getProperty(KEY), VALUE); String t = System.clearProperty(KEY); Assert.assertEquals(t, VALUE, KEY); Assert.assertNull(newProps.getProperty(KEY), KEY); } @Test static void setNullProperties() { Properties oldProps = System.getProperties(); Properties savedProps = new Properties(); oldProps.forEach((k,v) -> { if (v == null) { throw new RuntimeException("null value, key: " + k); } savedProps.put(k,v); }); // Re-initialize properties System.setProperties(null); Properties newProps = System.getProperties(); Object[][] propnames = requiredProperties(); for (Object[] p : propnames) { String name = (String)p[0]; Assert.assertEquals(System.getProperty(name), savedProps.getProperty(name), name); Assert.assertEquals(newProps.getProperty(name), savedProps.getProperty(name), name); } } // Verify all the required properties have values from System.getProperty and // System.getProperties() @Test(dataProvider = "requiredProperties") static void checkRequiredProperties(String name) { Assert.assertNotNull(System.getProperty(name), name); Properties props = System.getProperties(); Assert.assertNotNull(props.getProperty(name), name); } @SuppressWarnings("raw_types") @Test(enabled=false) public static void main(String[] args) { TestListenerAdapter tla = new TestListenerAdapter(); Class<?>[] testclass = {PropertyTest.class}; TestNG testng = new TestNG(); testng.setTestClasses(testclass); testng.addListener(tla); if (args.length > 0) { IMethodInterceptor intercept = (m, c) -> { List<IMethodInstance> x = m.stream() .filter(m1 -> m1.getMethod().getMethodName().contains(args[0])) .collect(Collectors.toList()); return x; }; testng.setMethodInterceptor(intercept); } testng.run(); tla.getPassedTests() .stream().forEach(t -> System.out.printf("Passed: %s%s%n", t.getName(), List.of(t.getParameters()))); tla.getFailedTests() .stream().forEach(t -> System.out.printf("Failed: %s%s%n", t.getName(), List.of(t.getParameters()))); } }
// Copyright 2017 Intelligent Robotics Group, NASA ARC package gov.nasa.arc.astrobee.internal; import gov.nasa.arc.astrobee.PendingResult; import gov.nasa.arc.astrobee.types.Mat33f; import gov.nasa.arc.astrobee.types.Point; import gov.nasa.arc.astrobee.types.Quaternion; import gov.nasa.arc.astrobee.types.Vec3d; import gov.nasa.arc.astrobee.types.ActionType; import gov.nasa.arc.astrobee.types.CameraMode; import gov.nasa.arc.astrobee.types.CameraName; import gov.nasa.arc.astrobee.types.CameraResolution; import gov.nasa.arc.astrobee.types.FlashlightLocation; import gov.nasa.arc.astrobee.types.FlightMode; import gov.nasa.arc.astrobee.types.LocalizationMode; import gov.nasa.arc.astrobee.types.PlannerType; import gov.nasa.arc.astrobee.types.PoweredComponent; import gov.nasa.arc.astrobee.types.TelemetryType; public abstract class BaseRobotImpl extends AbstractRobot implements BaseRobot { @Override public PendingResult grabControl(String cookie) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("grabControl") .addArgument("cookie", cookie); return publish(builder.build()); } @Override public PendingResult requestControl() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("requestControl"); return publish(builder.build()); } @Override public PendingResult fault() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("fault"); return publish(builder.build()); } @Override public PendingResult initializeBias() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("initializeBias"); return publish(builder.build()); } @Override public PendingResult loadNodelet(String nodeletName, String managerName, String type, String bondId) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("loadNodelet") .addArgument("nodeletName", nodeletName) .addArgument("managerName", managerName) .addArgument("type", type) .addArgument("bondId", bondId); return publish(builder.build()); } @Override public PendingResult noOp() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("noOp"); return publish(builder.build()); } @Override public PendingResult reacquirePosition() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("reacquirePosition"); return publish(builder.build()); } @Override public PendingResult resetEkf() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("resetEkf"); return publish(builder.build()); } @Override public PendingResult switchLocalization(LocalizationMode mode) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("switchLocalization") .addArgument("mode", mode); return publish(builder.build()); } @Override public PendingResult unloadNodelet(String nodeletName, String managerName) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("unloadNodelet") .addArgument("nodeletName", nodeletName) .addArgument("managerName", managerName); return publish(builder.build()); } @Override public PendingResult unterminate() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("unterminate"); return publish(builder.build()); } @Override public PendingResult wake(int berthNumber) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("wake") .addArgument("berthNumber", berthNumber); return publish(builder.build()); } @Override public PendingResult wakeSafe(int berthNumber) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("wakeSafe") .addArgument("berthNumber", berthNumber); return publish(builder.build()); } @Override public PendingResult armPanAndTilt(float pan, float tilt, ActionType which) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("armPanAndTilt") .addArgument("pan", pan) .addArgument("tilt", tilt) .addArgument("which", which); return publish(builder.build()); } @Override public PendingResult deployArm() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("deployArm"); return publish(builder.build()); } @Override public PendingResult gripperControl(boolean open) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("gripperControl") .addArgument("open", open); return publish(builder.build()); } @Override public PendingResult stopArm() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("stopArm"); return publish(builder.build()); } @Override public PendingResult stowArm() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("stowArm"); return publish(builder.build()); } @Override public PendingResult setDataToDisk() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setDataToDisk"); return publish(builder.build()); } @Override public PendingResult startRecording(String description) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("startRecording") .addArgument("description", description); return publish(builder.build()); } @Override public PendingResult stopRecording() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("stopRecording"); return publish(builder.build()); } @Override public PendingResult customGuestScience(String apkName, String command) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("customGuestScience") .addArgument("apkName", apkName) .addArgument("command", command); return publish(builder.build()); } @Override public PendingResult startGuestScience(String apkName) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("startGuestScience") .addArgument("apkName", apkName); return publish(builder.build()); } @Override public PendingResult stopGuestScience(String apkName) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("stopGuestScience") .addArgument("apkName", apkName); return publish(builder.build()); } @Override public PendingResult autoReturn() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("autoReturn"); return publish(builder.build()); } @Override public PendingResult dock(int berthNumber) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("dock") .addArgument("berthNumber", berthNumber); return publish(builder.build()); } @Override public PendingResult idlePropulsion() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("idlePropulsion"); return publish(builder.build()); } @Override public PendingResult perch() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("perch"); return publish(builder.build()); } @Override public PendingResult prepare() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("prepare"); return publish(builder.build()); } @Override public PendingResult simpleMove6DOF(String referenceFrame, Point xyz, Vec3d xyzTolerance, Quaternion rot) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("simpleMove6DOF") .addArgument("referenceFrame", referenceFrame) .addArgument("xyz", xyz) .addArgument("xyzTolerance", xyzTolerance) .addArgument("rot", rot); return publish(builder.build()); } @Override public PendingResult stopAllMotion() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("stopAllMotion"); return publish(builder.build()); } @Override public PendingResult undock() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("undock"); return publish(builder.build()); } @Override public PendingResult unperch() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("unperch"); return publish(builder.build()); } @Override public PendingResult pausePlan() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("pausePlan"); return publish(builder.build()); } @Override public PendingResult runPlan() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("runPlan"); return publish(builder.build()); } @Override public PendingResult setPlan() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setPlan"); return publish(builder.build()); } @Override public PendingResult skipPlanStep() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("skipPlanStep"); return publish(builder.build()); } @Override public PendingResult wait(float duration) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("wait") .addArgument("duration", duration); return publish(builder.build()); } @Override public PendingResult powerOffItem(PoweredComponent which) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("powerOffItem") .addArgument("which", which); return publish(builder.build()); } @Override public PendingResult powerOnItem(PoweredComponent which) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("powerOnItem") .addArgument("which", which); return publish(builder.build()); } @Override public PendingResult setCamera(CameraName cameraName, CameraMode cameraMode, CameraResolution resolution, float frameRate, float bandwidth) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setCamera") .addArgument("cameraName", cameraName) .addArgument("cameraMode", cameraMode) .addArgument("resolution", resolution) .addArgument("frameRate", frameRate) .addArgument("bandwidth", bandwidth); return publish(builder.build()); } @Override public PendingResult setCameraRecording(CameraName cameraName, boolean record) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setCameraRecording") .addArgument("cameraName", cameraName) .addArgument("record", record); return publish(builder.build()); } @Override public PendingResult setCameraStreaming(CameraName cameraName, boolean stream) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setCameraStreaming") .addArgument("cameraName", cameraName) .addArgument("stream", stream); return publish(builder.build()); } @Override public PendingResult setCheckObstacles(boolean checkObstacles) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setCheckObstacles") .addArgument("checkObstacles", checkObstacles); return publish(builder.build()); } @Override public PendingResult setCheckZones(boolean checkZones) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setCheckZones") .addArgument("checkZones", checkZones); return publish(builder.build()); } @Override public PendingResult setEnableAutoReturn(boolean enableAutoReturn) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setEnableAutoReturn") .addArgument("enableAutoReturn", enableAutoReturn); return publish(builder.build()); } @Override public PendingResult setEnableImmediate(boolean enableImmediate) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setEnableImmediate") .addArgument("enableImmediate", enableImmediate); return publish(builder.build()); } @Override public PendingResult setEnableReplan(boolean enableReplan) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setEnableReplan") .addArgument("enableReplan", enableReplan); return publish(builder.build()); } @Override public PendingResult setFlashlightBrightness(FlashlightLocation which, float brightness) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setFlashlightBrightness") .addArgument("which", which) .addArgument("brightness", brightness); return publish(builder.build()); } @Override public PendingResult setHolonomicMode(boolean enableHolonomic) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setHolonomicMode") .addArgument("enableHolonomic", enableHolonomic); return publish(builder.build()); } @Override public PendingResult setInertia(String name, float mass, Vec3d centerOfMass, Mat33f matrix) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setInertia") .addArgument("name", name) .addArgument("mass", mass) .addArgument("centerOfMass", centerOfMass) .addArgument("matrix", matrix); return publish(builder.build()); } @Override public PendingResult setOperatingLimits(String profileName, FlightMode flightMode, float targetLinearVelocity, float targetLinearAcceleration, float targetAngularVelocity, float targetAngularAcceleration, float collisionDistance) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setOperatingLimits") .addArgument("profileName", profileName) .addArgument("flightMode", flightMode) .addArgument("targetLinearVelocity", targetLinearVelocity) .addArgument("targetLinearAcceleration", targetLinearAcceleration) .addArgument("targetAngularVelocity", targetAngularVelocity) .addArgument("targetAngularAcceleration", targetAngularAcceleration) .addArgument("collisionDistance", collisionDistance); return publish(builder.build()); } @Override public PendingResult setPlanner(PlannerType planner) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setPlanner") .addArgument("planner", planner); return publish(builder.build()); } @Override public PendingResult setTelemetryRate(TelemetryType telemetryName, float rate) { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setTelemetryRate") .addArgument("telemetryName", telemetryName) .addArgument("rate", rate); return publish(builder.build()); } @Override public PendingResult setZones() { final CommandBuilder builder = makeCommandBuilder(); builder.setName("setZones"); return publish(builder.build()); } }
package IT.Algorithmen.codeTabelle; public class CodeTabelle { public String[][] codeTabelle; public CodeTabelle(String[][] codeTabelle) { this.codeTabelle = codeTabelle; } public void transpose() { String[][] transposed = new String[colCount()][rowCount()]; for (int i = 0; i < rowCount(); i++) for (int j = 0; j < codeTabelle[i].length; j++) transposed[j][i] = codeTabelle[i][j]; codeTabelle = transposed; } public void mirror(boolean vertically) { String[][] mirrored = new String[rowCount()][colCount()]; for (int i = 0; i < rowCount(); i++) for (int j = 0; j < codeTabelle[i].length; j++) mirrored[i][j] = vertically ? codeTabelle[i][colCount() - j - 1] : codeTabelle[rowCount() - i - 1][j]; codeTabelle = mirrored; } public void rotate(boolean clockwise) { transpose(); mirror(clockwise); } public int rowCount() { return codeTabelle.length; } public int colCount() { return codeTabelle[0].length; } @Override public String toString() { String[] rows = new String[codeTabelle.length]; for (int i = 0; i < codeTabelle.length; i++) { rows[i] = " ["; rows[i] += String.join(",", codeTabelle[i]); rows[i] += "]"; } return "[\n" + String.join(",\n", rows) + "\n]"; } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.refactoring.changeSignature; import com.intellij.java.refactoring.JavaRefactoringBundle; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.changeSignature.CallerChooserBase; import com.intellij.refactoring.changeSignature.ChangeSignatureDialogBase; import com.intellij.refactoring.changeSignature.ExceptionsTableModel; import com.intellij.refactoring.changeSignature.ThrownExceptionInfo; import com.intellij.refactoring.ui.CodeFragmentTableCellRenderer; import com.intellij.refactoring.ui.JavaCodeFragmentTableCellEditor; import com.intellij.refactoring.ui.VisibilityPanelBase; import com.intellij.refactoring.util.CanonicalTypes; import com.intellij.ui.ToolbarDecorator; import com.intellij.ui.table.JBTable; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle; import org.jetbrains.plugins.groovy.refactoring.ui.GroovyComboboxVisibilityPanel; import javax.swing.*; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author Max Medvedev */ public class GrChangeSignatureDialog extends ChangeSignatureDialogBase<GrParameterInfo, PsiMethod, String, GrMethodDescriptor, GrParameterTableModelItem, GrParameterTableModel > { private static final Logger LOG = Logger.getInstance(GrChangeSignatureDialog.class); private static final String INDENT = " "; private ExceptionsTableModel myExceptionsModel; public GrChangeSignatureDialog(Project project, GrMethodDescriptor method, boolean allowDelegation, PsiElement defaultValueContext) { super(project, method, allowDelegation, defaultValueContext); } @Override protected LanguageFileType getFileType() { return GroovyFileType.GROOVY_FILE_TYPE; } @NotNull @Override protected GrParameterTableModel createParametersInfoModel(@NotNull GrMethodDescriptor method) { final PsiParameterList parameterList = method.getMethod().getParameterList(); return new GrParameterTableModel(parameterList, myDefaultValueContext, this); } @Override protected BaseRefactoringProcessor createRefactoringProcessor() { final CanonicalTypes.Type type = getReturnType(); final ThrownExceptionInfo[] exceptionInfos = myExceptionsModel.getThrownExceptions(); final GrChangeInfoImpl info = new GrChangeInfoImpl(myMethod.getMethod(), getVisibility(), type, getMethodName(), getParameters(), exceptionInfos, isGenerateDelegate()); return new GrChangeSignatureProcessor(myProject, info); } @Override protected @NotNull List<Pair<@NlsContexts.TabTitle String, JPanel>> createAdditionalPanels() { // this method is invoked before constructor body myExceptionsModel = new ExceptionsTableModel(myMethod.getMethod().getThrowsList()); myExceptionsModel.setTypeInfos(myMethod.getMethod()); final JBTable table = new JBTable(myExceptionsModel); table.setShowGrid(false); table.setRowHeight(20); table.getColumnModel().getColumn(0).setCellRenderer(new CodeFragmentTableCellRenderer(myProject)); final JavaCodeFragmentTableCellEditor cellEditor = new JavaCodeFragmentTableCellEditor(myProject); cellEditor.addDocumentListener(new DocumentListener() { @Override public void documentChanged(@NotNull DocumentEvent e) { final int row = table.getSelectedRow(); final int col = table.getSelectedColumn(); myExceptionsModel.setValueAt(cellEditor.getCellEditorValue(), row, col); updateSignature(); } }); table.getColumnModel().getColumn(0).setCellEditor(cellEditor); table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getSelectionModel().setSelectionInterval(0, 0); table.setSurrendersFocusOnKeystroke(true); /* myPropExceptionsButton = new AnActionButton( //todo propagate parameters RefactoringBundle.message("changeSignature.propagate.exceptions.title"), null, PlatformIcons.NEW_EXCEPTION) { @Override public void actionPerformed(AnActionEvent e) { final Ref<JavaCallerChooser> chooser = new Ref<JavaCallerChooser>(); Consumer<Set<PsiMethod>> callback = new Consumer<Set<PsiMethod>>() { @Override public void consume(Set<PsiMethod> psiMethods) { myMethodsToPropagateExceptions = psiMethods; myExceptionPropagationTree = chooser.get().getTree(); } }; chooser.set(new JavaCallerChooser(myMethod.getMethod(), myProject, RefactoringBundle.message("changeSignature.exception.caller.chooser"), myExceptionPropagationTree, callback)); chooser.get().show(); } }; myPropExceptionsButton.setShortcut(CustomShortcutSet.fromString("alt X"));*/ final JPanel panel = ToolbarDecorator.createDecorator(table).createPanel(); //.addExtraAction(myPropExceptionsButton).createPanel(); panel.setBorder(JBUI.Borders.empty()); myExceptionsModel.addTableModelListener(mySignatureUpdater); final ArrayList<Pair<String, JPanel>> result = new ArrayList<>(); final String message = JavaRefactoringBundle.message("changeSignature.exceptions.panel.border.title"); result.add(Pair.create(message, panel)); return result; } @Nullable private CanonicalTypes.Type getReturnType() { PsiType returnType = null; try { if (myReturnTypeCodeFragment != null) { returnType = ((PsiTypeCodeFragment)myReturnTypeCodeFragment).getType(); } } catch (PsiTypeCodeFragment.TypeSyntaxException | PsiTypeCodeFragment.NoTypeException ignored) { } return returnType == null ? null : CanonicalTypes.createTypeWrapper(returnType); } @Override protected PsiCodeFragment createReturnTypeCodeFragment() { final JavaCodeFragmentFactory factory = JavaCodeFragmentFactory.getInstance(myProject); return factory.createTypeCodeFragment(myMethod.getReturnTypeText(), myMethod.getMethod(), true, JavaCodeFragmentFactory.ALLOW_VOID); } @Nullable @Override protected CallerChooserBase<PsiMethod> createCallerChooser(String title, Tree treeToReuse, Consumer<Set<PsiMethod>> callback) { return null; //todo next iteration } private boolean isGroovyMethodName(String name) { String methodText = "def " + name + "(){}"; try { final GrMethod method = GroovyPsiElementFactory.getInstance(getProject()).createMethodFromText(methodText); return method != null; } catch (Throwable e) { return false; } } private static boolean checkType(PsiTypeCodeFragment typeCodeFragment, boolean allowEllipsis) { try { final PsiType type = typeCodeFragment.getType(); return allowEllipsis || !(type instanceof PsiEllipsisType); } catch (PsiTypeCodeFragment.TypeSyntaxException e) { return false; } catch (PsiTypeCodeFragment.NoTypeException e) { return true; //Groovy accepts methods and parameters without explicit type } } @Nullable @Override protected String validateAndCommitData() { if (myReturnTypeCodeFragment != null && !checkType((PsiTypeCodeFragment)myReturnTypeCodeFragment, true)) { return GroovyRefactoringBundle.message("return.type.is.wrong"); } List<GrParameterTableModelItem> parameterInfos = myParametersTableModel.getItems(); int newParameterCount = parameterInfos.size(); for (int i = 0; i < newParameterCount; i++) { GrParameterTableModelItem item = parameterInfos.get(i); String name = item.parameter.getName(); if (!StringUtil.isJavaIdentifier(name)) { return GroovyRefactoringBundle.message("name.is.wrong", name); } if (!checkType((PsiTypeCodeFragment)item.typeCodeFragment, i == newParameterCount - 1)) { return GroovyRefactoringBundle.message("type.for.parameter.is.incorrect", name); } try { item.parameter.setType(((PsiTypeCodeFragment)item.typeCodeFragment).getType()); } catch (PsiTypeCodeFragment.TypeSyntaxException e) { LOG.error(e); } catch (PsiTypeCodeFragment.NoTypeException e) { item.parameter.setType(null); } String defaultValue = item.defaultValueCodeFragment.getText(); final String initializer = item.initializerCodeFragment.getText(); if (item.parameter.getOldIndex() < 0 && defaultValue.trim().isEmpty() && initializer.trim().isEmpty()) { return GroovyRefactoringBundle.message("specify.default.value", name); } item.parameter.setInitializer(initializer); item.parameter.setDefaultValue(defaultValue); } ThrownExceptionInfo[] exceptionInfos = myExceptionsModel.getThrownExceptions(); PsiTypeCodeFragment[] typeCodeFragments = myExceptionsModel.getTypeCodeFragments(); for (int i = 0; i < exceptionInfos.length; i++) { ThrownExceptionInfo exceptionInfo = exceptionInfos[i]; PsiTypeCodeFragment typeCodeFragment = typeCodeFragments[i]; try { PsiType type = typeCodeFragment.getType(); if (!(type instanceof PsiClassType)) { return GroovyRefactoringBundle.message("changeSignature.wrong.type.for.exception", typeCodeFragment.getText()); } PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory(); PsiClassType throwable = factory.createTypeByFQClassName("java.lang.Throwable", myMethod.getMethod().getResolveScope()); if (!throwable.isAssignableFrom(type)) { return GroovyRefactoringBundle.message("changeSignature.not.throwable.type", typeCodeFragment.getText()); } exceptionInfo.setType((PsiClassType)type); } catch (PsiTypeCodeFragment.TypeSyntaxException e) { return GroovyRefactoringBundle.message("changeSignature.wrong.type.for.exception", typeCodeFragment.getText()); } catch (PsiTypeCodeFragment.NoTypeException e) { return GroovyRefactoringBundle.message("changeSignature.no.type.for.exception"); } } return null; } private static String generateParameterText(GrParameterInfo info) { StringBuilder builder = new StringBuilder(); String typeText = info.getTypeText(); if (typeText.isEmpty()) typeText = GrModifier.DEF; builder.append(typeText).append(' '); builder.append(info.getName()); String initializer = info.getDefaultInitializer(); if (!StringUtil.isEmpty(initializer)) { builder.append(" = ").append(initializer); } return builder.toString(); } @Override protected String calculateSignature() { String type = myReturnTypeCodeFragment != null ? myReturnTypeCodeFragment.getText().trim() : ""; StringBuilder builder = new StringBuilder(); builder.append(myVisibilityPanel.getVisibility()).append(' '); if (!type.isEmpty()) { builder.append(type).append(' '); } builder.append(GrChangeSignatureUtil.getNameWithQuotesIfNeeded(getMethodName(), getProject())); builder.append('('); final List<GrParameterInfo> infos = getParameters(); if (!infos.isEmpty()) { final List<String> paramsText = ContainerUtil.map(infos, info -> generateParameterText(info)); builder.append("\n").append(INDENT); builder.append(StringUtil.join(paramsText, ",\n" + INDENT)); builder.append('\n'); } builder.append(')'); final PsiTypeCodeFragment[] exceptions = myExceptionsModel.getTypeCodeFragments(); if (exceptions.length > 0) { builder.append("\nthrows\n"); final List<String> exceptionNames = ContainerUtil.map(exceptions, fragment -> fragment.getText()); builder.append(INDENT).append(StringUtil.join(exceptionNames, ",\n" + INDENT)); } return builder.toString(); } @Override protected VisibilityPanelBase<String> createVisibilityControl() { return new GroovyComboboxVisibilityPanel(); } }
package com.softicar.platform.emf.attribute.display; import com.softicar.platform.dom.element.IDomElement; import com.softicar.platform.dom.elements.DomDiv; import java.util.Optional; @FunctionalInterface public interface IEmfAttributeValueDisplayFactory<V> { /** * Creates an {@link IDomElement} to display the given value. * * @param value * the value to display (may be <i>null</i>) * @return an {@link IDomElement} to display the given value (never * <i>null</i>) */ IDomElement createDisplay(V value); default IDomElement createDisplay(Optional<V> value) { if (value.isPresent()) { return createDisplay(value.get()); } else { return new DomDiv(); } } }
package br.edu.utfpr.cp.emater.midmipsystem.repository.pulverisation; import org.springframework.data.jpa.repository.JpaRepository; import br.edu.utfpr.cp.emater.midmipsystem.entity.pulverisation.Target; public interface TargetRepository extends JpaRepository<Target, Long>{ }
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2017, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 com.samsungxr.jassimp; import java.nio.ByteBuffer; /** * Interface to allow custom resource loaders for jassimp.<p> * * The design is based on passing the file wholly in memory, * because Java inputstreams do not have to support seek. <p> * * Writing files from Java is unsupported. * * * @author Jesper Smith * */ public interface AiIOStream { /** * Read all data into buffer. <p> * * The whole stream should be read into the buffer. * No support is provided for partial reads. * * @param buffer Target buffer for the model data * * @return true if successful, false if an error occurred. */ boolean read(ByteBuffer buffer); /** * The total size of this stream. <p> * * @return total size of this stream */ int getFileSize(); }