hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
0a2e824cefb023bb2aeb3e701b2ea7824984e75f
13,365
package in.skdv.skdvinbackend.service.impl; import com.auth0.client.mgmt.ManagementAPI; import com.auth0.client.mgmt.RolesEntity; import com.auth0.client.mgmt.UsersEntity; import com.auth0.exception.Auth0Exception; import com.auth0.json.mgmt.Role; import com.auth0.json.mgmt.RolesPage; import com.auth0.json.mgmt.users.User; import com.auth0.json.mgmt.users.UsersPage; import com.auth0.net.Request; import in.skdv.skdvinbackend.model.common.user.UserListResult; import in.skdv.skdvinbackend.model.dto.RoleDTO; import in.skdv.skdvinbackend.model.dto.UserDTO; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.test.util.ReflectionTestUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; class Auth0UserServiceTest { private ManagementAPI managementAPI; private Auth0UserService auth0UserService; @BeforeEach void setUp() { managementAPI = Mockito.mock(ManagementAPI.class); auth0UserService = new Auth0UserService(managementAPI); } @Test void testGetUsers() throws Auth0Exception { // Arrange List<User> userList = createMockUserList(); Request<UsersPage> usersRequest = (Request<UsersPage>) Mockito.mock(Request.class); Request<RolesPage> rolesRequest1 = (Request<RolesPage>) Mockito.mock(Request.class); Request<RolesPage> rolesRequest2 = (Request<RolesPage>) Mockito.mock(Request.class); UsersEntity usersEntity = Mockito.mock(UsersEntity.class); UsersPage usersPage = Mockito.mock(UsersPage.class); RolesPage rolesPage1 = Mockito.mock(RolesPage.class); RolesPage rolesPage2 = Mockito.mock(RolesPage.class); when(managementAPI.users()).thenReturn(usersEntity); when(usersEntity.list(any())).thenReturn(usersRequest); when(usersEntity.listRoles(anyString(), any())).thenReturn(rolesRequest1).thenReturn(rolesRequest2); when(usersRequest.execute()).thenReturn(usersPage); when(rolesRequest1.execute()).thenReturn(rolesPage1); when(rolesRequest2.execute()).thenReturn(rolesPage2); when(usersPage.getItems()).thenReturn(userList); when(rolesPage1.getItems()).thenReturn(createRolesForUser(1)); when(rolesPage2.getItems()).thenReturn(createRolesForUser(2)); // Act UserListResult userListResult = auth0UserService.getUsers(0, 10); var users = userListResult.getUsers(); // Assert assertNotNull(users); assertEquals(2, users.size()); assertEquals("1", users.get(0).getUserId()); assertEquals("foo@bar.com", users.get(0).getEmail()); assertEquals(2, users.get(0).getRoles().size()); assertEquals("2", users.get(1).getUserId()); assertEquals("baz@bar.com", users.get(1).getEmail()); assertEquals(1, users.get(1).getRoles().size()); } @Test void testGetUsers_ExceptionRetrievingRoles() throws Auth0Exception { // Arrange List<User> userList = createMockUserList(); Request<UsersPage> usersRequest = (Request<UsersPage>) Mockito.mock(Request.class); Request<RolesPage> rolesRequest1 = (Request<RolesPage>) Mockito.mock(Request.class); Request<RolesPage> rolesRequest2 = (Request<RolesPage>) Mockito.mock(Request.class); UsersEntity usersEntity = Mockito.mock(UsersEntity.class); UsersPage usersPage = Mockito.mock(UsersPage.class); when(managementAPI.users()).thenReturn(usersEntity); when(usersEntity.list(any())).thenReturn(usersRequest); when(usersEntity.listRoles(anyString(), any())).thenReturn(rolesRequest1).thenReturn(rolesRequest2); when(usersRequest.execute()).thenReturn(usersPage); when(rolesRequest1.execute()).thenThrow(new Auth0Exception("Auth0 not available")); when(usersPage.getItems()).thenReturn(userList); // Act RuntimeException exception = assertThrows(RuntimeException.class, () -> auth0UserService.getUsers(0, 10)); // Assert assertEquals("Error retrieving roles from auth0", exception.getMessage()); } @Test void testGetUsers_ExceptionRetrievingUsers() throws Auth0Exception { // Arrange List<User> userList = createMockUserList(); Request<UsersPage> usersRequest = (Request<UsersPage>) Mockito.mock(Request.class); UsersEntity usersEntity = Mockito.mock(UsersEntity.class); when(managementAPI.users()).thenReturn(usersEntity); when(usersEntity.list(any())).thenReturn(usersRequest); when(usersRequest.execute()).thenThrow(new Auth0Exception("Auth0 not available")); // Act RuntimeException exception = assertThrows(RuntimeException.class, () -> auth0UserService.getUsers(0, 10)); // Assert assertEquals("Error retrieving users from auth0", exception.getMessage()); } @Test void testUpdateUser() throws Auth0Exception { // Arrange UserDTO newDTO = new UserDTO("1", "foo@example.com", new ArrayList<>(Arrays.asList( new RoleDTO("2", "VIDEOFLYER"), new RoleDTO("3", "MANIFEST")) ) ); Request<RolesPage> rolesRequest = (Request<RolesPage>) Mockito.mock(Request.class); UsersEntity usersEntity = Mockito.mock(UsersEntity.class); RolesPage rolesPage = Mockito.mock(RolesPage.class); Request addRolesRequest = Mockito.mock(Request.class); Request removeRolesRequest = Mockito.mock(Request.class); when(managementAPI.users()).thenReturn(usersEntity); when(usersEntity.listRoles(anyString(), any())).thenReturn(rolesRequest); when(usersEntity.addRoles(anyString(), any())).thenReturn(addRolesRequest); when(usersEntity.removeRoles(anyString(), any())).thenReturn(removeRolesRequest); when(rolesRequest.execute()).thenReturn(rolesPage); when(rolesPage.getItems()).thenReturn(createRolesForUser(1)); when(addRolesRequest.execute()).thenReturn(null); when(removeRolesRequest.execute()).thenReturn(null); // Act auth0UserService.updateUser(newDTO); // Assert verify(usersEntity).addRoles("1", Collections.singletonList("3")); verify(usersEntity).removeRoles("1", Collections.singletonList("1")); verify(addRolesRequest).execute(); verify(removeRolesRequest).execute(); } @Test void testUpdateUser_NoChanges() throws Auth0Exception { // Arrange UserDTO newDTO = new UserDTO("1", "foo@example.com", new ArrayList<>(Arrays.asList( new RoleDTO("1", "TANDEMMASTER"), new RoleDTO("2", "VIDEOFLYER")) ) ); Request<RolesPage> rolesRequest = (Request<RolesPage>) Mockito.mock(Request.class); UsersEntity usersEntity = Mockito.mock(UsersEntity.class); RolesPage rolesPage = Mockito.mock(RolesPage.class); when(managementAPI.users()).thenReturn(usersEntity); when(usersEntity.listRoles(anyString(), any())).thenReturn(rolesRequest); when(rolesRequest.execute()).thenReturn(rolesPage); when(rolesPage.getItems()).thenReturn(createRolesForUser(1)); // Act auth0UserService.updateUser(newDTO); // Assert verify(usersEntity, never()).addRoles(any(), any()); verify(usersEntity, never()).removeRoles(any(), any()); } @Test void testUpdateUser_ExceptionUpdatingRoles() throws Auth0Exception { // Arrange UserDTO newDTO = new UserDTO("1", "foo@example.com", new ArrayList<>(Arrays.asList( new RoleDTO("2", "VIDEOFLYER"), new RoleDTO("3", "MANIFEST")) ) ); Request<RolesPage> rolesRequest = (Request<RolesPage>) Mockito.mock(Request.class); UsersEntity usersEntity = Mockito.mock(UsersEntity.class); RolesPage rolesPage = Mockito.mock(RolesPage.class); Request addRolesRequest = Mockito.mock(Request.class); when(managementAPI.users()).thenReturn(usersEntity); when(usersEntity.listRoles(anyString(), any())).thenReturn(rolesRequest); when(usersEntity.addRoles(anyString(), any())).thenReturn(addRolesRequest); when(rolesRequest.execute()).thenReturn(rolesPage); when(rolesPage.getItems()).thenReturn(createRolesForUser(1)); when(addRolesRequest.execute()).thenReturn(null); when(addRolesRequest.execute()).thenThrow(new Auth0Exception("Auth0 not available")); // Act RuntimeException exception = assertThrows(RuntimeException.class, () -> auth0UserService.updateUser(newDTO)); // Assert assertEquals("Error updating roles from auth0", exception.getMessage()); } @Test void testFindRolesToAdd() { ArrayList<RoleDTO> updatedRoles = new ArrayList<>(Arrays.asList( new RoleDTO("1", "TANDEMMASTER"), new RoleDTO("2", "VIDEOFLYER")) ); ArrayList<RoleDTO> currentRoles = new ArrayList<>(Collections.singletonList(new RoleDTO("1", "TANDEMMASTER"))); List<String> roleIdsToAdd = auth0UserService.findRolesToAdd(currentRoles, updatedRoles); assertEquals(2, updatedRoles.size()); assertEquals(1, currentRoles.size()); assertEquals("TANDEMMASTER", currentRoles.get(0).getName()); assertEquals(1, roleIdsToAdd.size()); assertEquals("2", roleIdsToAdd.get(0)); } @Test void testFindRolesToRemove() { ArrayList<RoleDTO> updatedRoles = new ArrayList<>(Collections.singletonList(new RoleDTO("1", "TANDEMMASTER"))); ArrayList<RoleDTO> currentRoles = new ArrayList<>(Arrays.asList( new RoleDTO("1", "TANDEMMASTER"), new RoleDTO("2", "VIDEOFLYER")) ); List<String> roleIdsToRemove = auth0UserService.findRolesToRemove(currentRoles, updatedRoles); assertEquals(1, updatedRoles.size()); assertEquals(2, currentRoles.size()); assertEquals("TANDEMMASTER", updatedRoles.get(0).getName()); assertEquals(1, roleIdsToRemove.size()); assertEquals("2", roleIdsToRemove.get(0)); } @Test void testGetRoles() throws Auth0Exception { // Arrange Request<RolesPage> rolesRequest = (Request<RolesPage>) Mockito.mock(Request.class); RolesEntity rolesEntity = Mockito.mock(RolesEntity.class); RolesPage rolesPage = Mockito.mock(RolesPage.class); when(managementAPI.roles()).thenReturn(rolesEntity); when(rolesEntity.list(any())).thenReturn(rolesRequest); when(rolesRequest.execute()).thenReturn(rolesPage); when(rolesPage.getItems()).thenReturn(createRolesForUser(1)); // Act List<RoleDTO> roles = auth0UserService.getRoles(); // Assert assertNotNull(roles); assertEquals(2, roles.size()); assertEquals("1", roles.get(0).getId()); assertEquals("TANDEMMASTER",roles.get(0).getName()); assertEquals("2", roles.get(1).getId()); assertEquals("VIDEOFLYER", roles.get(1).getName()); } @Test void testGetRoles_ExceptionRetrievingRoles() throws Auth0Exception { // Arrange Request<RolesPage> rolesRequest = (Request<RolesPage>) Mockito.mock(Request.class); RolesEntity rolesEntity = Mockito.mock(RolesEntity.class); RolesPage rolesPage = Mockito.mock(RolesPage.class); when(managementAPI.roles()).thenReturn(rolesEntity); when(rolesEntity.list(any())).thenReturn(rolesRequest); when(rolesRequest.execute()).thenThrow(new Auth0Exception("Auth0 not available")); when(rolesPage.getItems()).thenReturn(createRolesForUser(1)); // Act RuntimeException exception = assertThrows(RuntimeException.class, () -> auth0UserService.getRoles()); // Assert assertEquals("Error retrieving roles from auth0", exception.getMessage()); } private List<User> createMockUserList() { User user1 = new User(); user1.setId("1"); user1.setEmail("foo@bar.com"); User user2 = new User(); user2.setId("2");user2.setEmail("baz@bar.com"); return new ArrayList<>(Arrays.asList(user1, user2)); } private List<Role> createRolesForUser(int i) { if (i == 1) { Role role1 = new Role(); ReflectionTestUtils.setField(role1, "id", "1"); role1.setName("TANDEMMASTER"); Role role2 = new Role(); ReflectionTestUtils.setField(role2, "id", "2"); role2.setName("VIDEOFLYER"); return Arrays.asList(role1, role2); } if (i == 2) { Role role1 = new Role(); ReflectionTestUtils.setField(role1, "id", "3"); role1.setName("MANIFEST"); return Collections.singletonList(role1); } return Collections.emptyList(); } }
41.896552
119
0.662626
fa152a8f429e6199437e87f09b2f5bb44b9c9657
2,154
/* * * * Copyright 2018 Symphony Communication Services, LLC. * * Licensed to The Symphony Software Foundation (SSF) 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.symphony.oss.canon.runtime.jjwt; import java.security.Key; import io.jsonwebtoken.Claims; /** * An example JwtAutheticator which returns the subject claim as a String as the Authentication context. * * This implementation has a default value which is returned in the case where a valid token has no subject claim. * In a real implementation one would probably throw a NotAuthenticatedException to return an HTTP 401 in that case. * * @author Bruce Skingle * */ public class JwtSubjectAuthenticator extends JwtAuthenticator<String> { private String defaultSubject_; /** * Constructor. * * @param key Key to be used to validate signature. * @param maxAge Maximum acceptable age of JWT. * @param defaultSubject Value to return if there is no subject claim. * @param algorithm Signature algorithm which is acceptable. */ public JwtSubjectAuthenticator(Key key, Long maxAge, String defaultSubject, String algorithm) { super(key, maxAge, algorithm); defaultSubject_ = defaultSubject; } @Override protected String extractAuth(Claims claims) { String subject = claims.getSubject(); if(subject == null) return defaultSubject_; return subject; } }
31.676471
116
0.725162
394d6cd74a048aebea60c01c843f52b6ccea03dd
6,024
package xsmeral.semnet.scraper; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.openrdf.model.Statement; import xsmeral.semnet.crawler.HostManager; import xsmeral.semnet.crawler.model.EntityDescriptor; import xsmeral.semnet.crawler.model.EntityDocument; import xsmeral.pipe.LocalObjectFilter; import xsmeral.pipe.LocalObjectSource; import xsmeral.pipe.ObjectProcessorException; import xsmeral.pipe.ProcessorStoppedException; import xsmeral.pipe.context.FromContext; import xsmeral.pipe.interfaces.ObjectProcessorInterface; import xsmeral.semnet.manager.Configuration; /** * This processor works as a router, dispatching entity documents to scrapers. * The scrapers are configured from a HostManager instance and pre-instantiated * at post-context initialization. * * @fromContext hostManager A HostManager instance, used to instantiate scrapers * @author Ron Šmeral (xsmeral@fi.muni.cz) * @see HostManager */ @ObjectProcessorInterface(in = EntityDocument.class, out = Statement.class) public class ScraperWrapper extends LocalObjectFilter<EntityDocument, Statement> { @FromContext private HostManager hostManager; /** * Map of scraper threads (by their Runnables), for starting and stopping. */ private Map<AbstractScraper, Thread> scraperMap; /** * Map of DocumentSources associated with scraper configuration for a given entity. * For correct routing in:entityDoc(w/ entDesc) -> docSource(s) -> scraper(s) -> out:statement */ private Map<EntityDescriptor, Collection<DocumentSource>> sourceMap; /** * Cache of document sources, mapped by corresponding scraper configurations. */ private Map<Configuration, DocumentSource> confCache; public ScraperWrapper() { sourceMap = new HashMap<EntityDescriptor, Collection<DocumentSource>>(); scraperMap = new HashMap<AbstractScraper, Thread>(); confCache = new HashMap<Configuration, DocumentSource>(); } /** * Instantiates scrapers. */ @Override protected void initPostContext() { try { for (int hostId : hostManager.getHostIds()) { for (EntityDescriptor entDesc : hostManager.getHostDescriptor(hostId).getEntityDescriptors()) { Collection<Configuration> scrapers = entDesc.getScrapers(); for (Configuration scraperConf : scrapers) { DocumentSource src; if (!confCache.containsKey(scraperConf)) { Class cls = scraperConf.getClazz(); src = new DocumentSource(); AbstractScraper scraper = (AbstractScraper) cls.newInstance(); src.next(scraper); scraper.setOutBuffer(this.getOutBuffer()); scraper.setNext(this.getNext()); scraper.initialize(scraperConf.getParams()); Thread t = new Thread(scraper, cls.getSimpleName()); Collection<DocumentSource> sources = sourceMap.get(entDesc); if (sources == null) { sourceMap.put(entDesc, new ArrayList<DocumentSource>()); } scraperMap.put(scraper, t); confCache.put(scraperConf, src); } else { src = confCache.get(scraperConf); } sourceMap.get(entDesc).add(src); } } } for (AbstractScraper s : scraperMap.keySet()) { s.setContext(getContext()); } for (AbstractScraper s : scraperMap.keySet()) { s.initContext(); } } catch (InstantiationException ex) { failStart("Can't instantiate a scraper", ex); } catch (IllegalAccessException ex) { failStart("Can't instantiate a scraper", ex); } catch (ObjectProcessorException ex) { failStart("Scraper failed to start", ex); } } private class DocumentSource extends LocalObjectSource<EntityDocument> { public DocumentSource() { status = Status.RUNNING; } public void addDoc(EntityDocument doc) throws ProcessorStoppedException { write(doc); } public void doStop() { stop(); } } /** * Starts scrapers. */ @Override protected void preRun() throws ProcessorStoppedException { for (Thread t : scraperMap.values()) { t.start(); } } @Override protected void process() throws ProcessorStoppedException { EntityDocument doc = read(); for (DocumentSource src : sourceMap.get(doc.getEntityDescriptor())) { src.addDoc(doc); } } @Override public boolean canStart() { boolean allCanStart = true; for (Iterator<AbstractScraper> it = scraperMap.keySet().iterator(); it.hasNext() && allCanStart; allCanStart = allCanStart && it.next().canStart()); return allCanStart; } private void stopAll() { for (DocumentSource src : confCache.values()) { src.doStop(); } for (Thread t : scraperMap.values()) { try { t.join(); } catch (InterruptedException ex1) { Logger.getLogger(ScraperWrapper.class.getName()).log(Level.SEVERE, null, ex1); } } stop(); } @Override protected void handleStoppedSink() { stopAll(); } @Override protected void handleStoppedSource() { stopAll(); } }
35.435294
111
0.595784
74a2b5ba12025a643c3101fdb246cc1b1386f9fc
1,072
package java.practice.examples.datatypes; public class JavaDataypesFloatDouble { public static void main(String[] args) { boolean b = true; System.out.println(b); // boolean b1 = 0; System.out.println(b1); //Type mismatch: cannot convert from int to boolean // boolean b2 = True; System.out.println(b2); //True cannot be resolved to a variable // boolean b3 = "True"; System.out.println(b3); //Type mismatch: cannot convert from String to boolean int x =0; // if(x) {System.out.println("hello"); } //Type mismatch: cannot convert from int to boolean // else {System.out.println("hi"); } // // while(1) {System.out.println("hello");} //Type mismatch: cannot convert from int to boolean } } //Floating point data types: //1. float // * if we want 5 to 6 decimal points // * Single precision // * 4 bytes // * -3.4e38 to 3.4e38 //2. double // * if we want 14 to 15 decimal points // * double precision // * size : 8 bytes // * range : -1.7e38 to 1.e38 //3. boolean // * size = not applicable [vm dependent] // * range : NA // * Allowed values : true and false
34.580645
103
0.675373
6cbe3d2a4401a5d99d35698e85fb89be5258035b
9,770
package com.oberasoftware.jasdb.entitymapper; import com.oberasoftware.jasdb.api.entitymapper.*; import com.oberasoftware.jasdb.api.entitymapper.annotations.Id; import com.oberasoftware.jasdb.api.entitymapper.annotations.JasDBEntity; import com.oberasoftware.jasdb.api.entitymapper.annotations.JasDBProperty; import com.oberasoftware.jasdb.api.exceptions.JasDBStorageException; import com.oberasoftware.jasdb.api.exceptions.RuntimeJasDBException; import com.oberasoftware.jasdb.api.session.Entity; import com.oberasoftware.jasdb.api.session.Property; import com.oberasoftware.jasdb.core.SimpleEntity; import com.oberasoftware.jasdb.core.utils.StringUtils; import org.slf4j.Logger; import org.springframework.stereotype.Component; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static com.oberasoftware.jasdb.core.utils.AnnotationUtils.getAnnotation; import static com.oberasoftware.jasdb.core.utils.AnnotationUtils.getOptionalAnnotation; import static com.oberasoftware.jasdb.entitymapper.types.TypeMapperFactory.getTypeMapper; import static org.slf4j.LoggerFactory.getLogger; /** * @author Renze de Vries */ @Component public class AnnotationEntityMapper implements EntityMapper { private static final Logger LOG = getLogger(AnnotationEntityMapper.class); private ConcurrentMap<String, EntityMetadata> cachedEntityMetadata = new ConcurrentHashMap<>(); @Override public MapResult mapTo(Object mappableObject) throws JasDBStorageException { LOG.debug("Mapping entity: {}", mappableObject); Class<?> entityClass = mappableObject.getClass(); EntityMetadata metadata = getEntityMetadata(entityClass); Optional<PropertyMetadata> keyProperty = metadata.getKeyProperty(); SimpleEntity entity = new SimpleEntity(); if(keyProperty.isPresent()) { Object keyValue = EntityUtils.getValue(mappableObject, keyProperty.get()); if(keyValue != null) { String id = getTypeMapper(String.class).mapToRawType(keyValue); if (EntityUtils.toValidUUID(id) != null) { LOG.debug("Setting entity id to: {}", id); entity.setInternalId(id); } else { LOG.warn("Entity marked with an @Id {} field, but invalid UUID, ignoring", id); } } else { LOG.debug("No UUID specified in field marked with @Id, generating during insert"); } } metadata.getProperties().forEach((k, v) -> { try { Property property = EntityUtils.map(mappableObject, v); if(property != null) { entity.addProperty(property); } else if(!v.isNullable()) { throw new RuntimeJasDBException("Unable to map property: " + v + " value is null"); } } catch (JasDBStorageException e) { throw new RuntimeJasDBException("Unable to map property: " + v, e); } }); return new MapResultImpl(metadata, entity, mappableObject, metadata.getBagName()); } @Override public Object updateId(String id, Object mappableObject) throws JasDBStorageException { LOG.debug("Setting ID: {} on mappable object: {}", id, mappableObject); Class<?> entityClass = mappableObject.getClass(); EntityMetadata metadata = getEntityMetadata(entityClass); Optional<PropertyMetadata> optionalKeyProperty = metadata.getKeyProperty(); if(optionalKeyProperty.isPresent()) { PropertyMetadata keyProperty = optionalKeyProperty.get(); setValue(mappableObject, id, keyProperty); } return mappableObject; } @Override public <T> T mapFrom(Class<T> targetType, Entity entity) throws JasDBStorageException { try { if(entity != null) { Object instance = targetType.newInstance(); EntityMetadata metadata = getEntityMetadata(targetType); metadata.getProperties().forEach((k, v) -> { if(v.isKey()) { setValue(instance, entity.getInternalId(), v); } else { Property property = entity.getProperty(k); if (property != null) { Object value = v.getTypeMapper().mapFromProperty(v, property); setValue(instance, value, v); } else if (!v.isNullable()) { throw new RuntimeJasDBException("Unable to map property: " + v + " value was null"); } else { Object emptyValue = v.getTypeMapper().mapToEmptyValue(); setValue(instance, emptyValue, v); } } }); return targetType.cast(instance); } else { return null; } } catch(IllegalAccessException | InstantiationException e) { throw new JasDBStorageException("Unable to create instance of entity, missing constructor or inaccessible: " + targetType, e); } } private void setValue(Object instance, Object value, PropertyMetadata v) { try { v.getWriteMethod().invoke(instance, value); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeJasDBException("Unable to set field value on entity: " + instance.getClass(), e); } } @Override public EntityMetadata getEntityMetadata(Class<?> entityClass) throws JasDBStorageException { String entityClassName = entityClass.getName(); if(!cachedEntityMetadata.containsKey(entityClassName)) { LOG.debug("Entity: {} metadata not cached, loading now", entityClassName); cachedEntityMetadata.putIfAbsent(entityClassName, loadEntityMetadata(entityClass)); } return cachedEntityMetadata.get(entityClassName); } private EntityMetadata loadEntityMetadata(Class<?> entityClass) throws JasDBStorageException { JasDBEntity annotationEntity = getAnnotation(entityClass, JasDBEntity.class); String bagName = annotationEntity.bagName(); Map<String, PropertyMetadata> propertyMetadatas = loadProperties(entityClass); Optional<PropertyMetadata> keyProperty = propertyMetadatas.values().stream().filter(PropertyMetadata::isKey).findFirst(); LOG.debug("Found key property: {}", keyProperty); return new EntityMetadataImpl(entityClass, bagName, keyProperty, propertyMetadatas); } private Map<String, PropertyMetadata> loadProperties(Class<?> entityClass) throws JasDBStorageException { try { BeanInfo beanInfo = Introspector.getBeanInfo(entityClass); Map<String, PropertyMetadata> propertyMetadatas = new HashMap<>(); for(PropertyDescriptor p : beanInfo.getPropertyDescriptors()) { PropertyMetadata propertyMetadata = loadProperty(p); if(propertyMetadata != null) { propertyMetadatas.put(propertyMetadata.getPropertyName(), propertyMetadata); } } LOG.debug("Mapped: {} properties to entity: {}", propertyMetadatas.size(), entityClass); return propertyMetadatas; } catch(IntrospectionException e) { throw new JasDBStorageException("Unable to map entity: " + entityClass); } } private PropertyMetadata loadProperty(PropertyDescriptor propertyDescriptor) throws JasDBStorageException { Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); if(readMethod != null && writeMethod != null) { Optional<JasDBProperty> readAnnotation = getOptionalAnnotation(readMethod, JasDBProperty.class); Optional<JasDBProperty> writeAnnotation = getOptionalAnnotation(writeMethod, JasDBProperty.class); Optional<Id> idAnnotation = getOptionalAnnotation(readMethod, Id.class); if (readAnnotation.isPresent() || writeAnnotation.isPresent()) { TypeMapper typeMapper = getTypeMapper(readMethod); //here a number of override for the property name, first check read method, next write else default to property bean name String propertyName = readAnnotation.isPresent() ? readAnnotation.get().name() : ""; propertyName = StringUtils.stringEmpty(propertyName) ? writeAnnotation.isPresent() ? writeAnnotation.get().name() : "" : propertyName; propertyName = StringUtils.stringEmpty(propertyName) ? propertyDescriptor.getName() : propertyName; boolean nullable = readAnnotation.isPresent() ? readAnnotation.get().nullable() : writeAnnotation.get().nullable(); LOG.debug("Found Entity property: {} nullable: {}", propertyDescriptor.getName(), nullable); return new PropertyMetadataImpl(typeMapper, readMethod, writeMethod, propertyName, idAnnotation.isPresent(), nullable); } } else { LOG.debug("Read or Write method not defined for property: {}", propertyDescriptor.getName()); } return null; } }
46.52381
150
0.655374
3b4c1be138f27f21ef726c223ea541723b75fcc6
1,647
package com.tiny.demo.firstlinecode.ui.model; import com.tiny.demo.firstlinecode.ui.bean.MultiItem1; import com.tiny.demo.firstlinecode.ui.bean.MultiItemBravh; import java.util.ArrayList; import java.util.List; /** * Desc: * Created by tiny on 2017/12/13. * Version: */ public class RecyclerViewDataServer { public static List<MultiItem1> getMultiItem1List() { List<MultiItem1> list = new ArrayList<>(); for (int m = 0; m < 10; m++) { for (int n = 0; n < 3; n++) { MultiItem1 multiItem1 = new MultiItem1(); int i = n % 3; multiItem1.type = String.valueOf(i); multiItem1.name = "王蛋蛋" + m + n; multiItem1.gender = "小母猫" + m + n; list.add(multiItem1); } } return list; } public static List<MultiItemBravh> getMultiItemBravh(int size) { List<MultiItemBravh> list = new ArrayList<>(); for (int j = 0; j < size; j++) { list.add(new MultiItemBravh("王蛋蛋" + j, MultiItemBravh.TYPE1, MultiItemBravh.SPAN_1)); list.add(new MultiItemBravh("王蛋蛋" + j, MultiItemBravh.TYPE1, MultiItemBravh.SPAN_1)); list.add(new MultiItemBravh("王蛋蛋" + j, MultiItemBravh.TYPE1, MultiItemBravh.SPAN_1)); list.add(new MultiItemBravh("王蛋蛋" + (j + 1), MultiItemBravh.TYPE2, MultiItemBravh.SPAN_2)); list.add(new MultiItemBravh("王蛋蛋" + (j + 1), MultiItemBravh.TYPE1, MultiItemBravh.SPAN_1)); list.add(new MultiItemBravh("王蛋蛋" + (j + 2), MultiItemBravh.TYPE3, MultiItemBravh.SPAN_3)); } return list; } }
37.431818
103
0.600486
ac014cd819730acf74d47159c3f2e170709bcc5e
2,682
package com.genie.es.util; import com.genie.es.config.ElasticSearchProperties; import com.genie.es.repository.ElasticSearchOperations; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; /** * 测试工具类 */ public class ESTestUtil { public static ElasticSearchProperties createElasticSearchProperties(){ ElasticSearchProperties elasticSearchProperties = new ElasticSearchProperties(); elasticSearchProperties.setBatchSize(50); elasticSearchProperties.setFlushTime(1000); return elasticSearchProperties; } public static ElasticSearchProperties createElasticSearchProperties(String clusterName, String clusterNodes) { ElasticSearchProperties elasticSearchProperties = new ElasticSearchProperties(); elasticSearchProperties.setClusterName(clusterName); elasticSearchProperties.setClusterNodes(clusterNodes); elasticSearchProperties.setBatchSize(10); elasticSearchProperties.setFlushTime(1000); return elasticSearchProperties; } public static ElasticSearchOperations createElasticSearchOperations(Client client) throws UnknownHostException { return new ElasticSearchOperations(client); } public static ElasticSearchOperations createElasticSearchOperations(ElasticSearchProperties elasticSearchProperties) throws UnknownHostException { TransportClient client; Settings settings = Settings.builder() .put("cluster.name", elasticSearchProperties.getClusterName()) .build(); TransportAddress transportAddress = transportAddress(elasticSearchProperties); client = new PreBuiltTransportClient(settings).addTransportAddress(transportAddress); return new ElasticSearchOperations(client); } private static TransportAddress transportAddress(ElasticSearchProperties elasticSearchProperties) throws UnknownHostException { String[] host = elasticSearchProperties.getClusterNodes().split(":"); Integer port = Integer.parseInt(host[1]); InetAddress addr = InetAddress.getByName(host[0]); InetSocketAddress ip = new InetSocketAddress(addr, port); TransportAddress transportAddress = new InetSocketTransportAddress(ip); return transportAddress; } }
41.90625
150
0.779269
75eb6fdb7a0a7fa8f9b2ef8a9d4a8d660c150540
1,389
package io.github.nblxa.cons; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test; import static io.github.nblxa.cons.ConsList.*; import static org.assertj.core.api.Assertions.assertThat; public class DoubleConsListEqualsTest { @Test public void equalsHashCode_doubleConsList() { EqualsVerifier.forClass(DoubleConsListImpl.class) .withPrefabValues(DoubleConsList.class, doubleList(1.1d, 2.1d, 3.1d), doubleList(100.1d, 200.1d)) .verify(); } @Test public void equalsHashCode_doubleConsListWithNil() { EqualsVerifier.forClass(DoubleConsListImpl.class) .withPrefabValues(DoubleConsList.class, doubleList(1.1d, 2.1d, 3.1d), nil()) .verify(); } @Test public void equalsHashCode_doubleConsListWithBoxedCons() { EqualsVerifier.forClass(ConsList.class) .withPrefabValues(ConsList.class, doubleList(1.1d, 2.1d, 3.1d), list(100.1d, 200.1d)) .verify(); } @Test public void equalsHashCode_doubleConsListWithEqualBoxedCons() { DoubleConsList<Double> dl = doubleList(1.1d, 2.1d, 3.1d); ConsList<Double> l = list(1.1d, 2.1d, 3.1d); assertThat(dl.equals(l)) .isTrue(); assertThat(l.equals(dl)) .isTrue(); assertThat(dl.hashCode() == l.hashCode()) .isTrue(); } }
31.568182
109
0.650108
678317aa6da3417301372a2e35a6c9c73794b986
6,027
/** * Copyright 2017 Syncleus, Inc. * with portions copyright 2004-2017 Bo Zimmerman * * 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.syncleus.aethermud.game.Abilities.Properties; import com.syncleus.aethermud.game.Abilities.interfaces.Ability; import com.syncleus.aethermud.game.Abilities.interfaces.TriggeredAffect; import com.syncleus.aethermud.game.Areas.interfaces.Area; import com.syncleus.aethermud.game.Common.interfaces.CMMsg; import com.syncleus.aethermud.game.Exits.interfaces.Exit; import com.syncleus.aethermud.game.Items.interfaces.Armor; import com.syncleus.aethermud.game.Items.interfaces.Food; import com.syncleus.aethermud.game.Items.interfaces.Item; import com.syncleus.aethermud.game.Items.interfaces.Weapon; import com.syncleus.aethermud.game.Locales.interfaces.Room; import com.syncleus.aethermud.game.MOBS.interfaces.MOB; import com.syncleus.aethermud.game.core.CMClass; import com.syncleus.aethermud.game.core.CMLib; import com.syncleus.aethermud.game.core.CMParms; import com.syncleus.aethermud.game.core.Directions; import com.syncleus.aethermud.game.core.interfaces.Drink; import com.syncleus.aethermud.game.core.interfaces.Environmental; import com.syncleus.aethermud.game.core.interfaces.Rideable; public class Prop_Transporter extends Property implements TriggeredAffect { protected int transCode = -1; protected String roomID = "START"; protected boolean sendEnter = false; @Override public String ID() { return "Prop_Transporter"; } @Override public String name() { return "Room entering adjuster"; } @Override protected int canAffectCode() { return Ability.CAN_EXITS | Ability.CAN_ROOMS; } @Override public void setMiscText(String newMiscText) { roomID = "START"; sendEnter = false; super.setMiscText(newMiscText); int x = newMiscText.indexOf(';'); if (x < 0) { roomID = newMiscText; } else { roomID = newMiscText.substring(0, x); String vars = newMiscText.substring(x + 1); sendEnter = CMParms.getParmBool(vars, "SENDENTER", false); } } @Override public String accountForYourself() { return "Zap them elsewhere"; } @Override public int triggerMask() { return TriggeredAffect.TRIGGER_DROP_PUTIN; } public int transCode() { if (transCode >= 0) return transCode; if (affected == null) return -1; if (affected instanceof Drink) transCode = CMMsg.TYP_DRINK; else if (affected instanceof Food) transCode = CMMsg.TYP_EAT; else if (affected instanceof Rideable) { transCode = CMMsg.TYP_MOUNT; switch (((Rideable) affected).rideBasis()) { case Rideable.RIDEABLE_ENTERIN: transCode = CMMsg.TYP_ENTER; break; case Rideable.RIDEABLE_SIT: case Rideable.RIDEABLE_TABLE: transCode = CMMsg.TYP_SIT; break; case Rideable.RIDEABLE_SLEEP: transCode = CMMsg.TYP_SLEEP; break; } } else if (affected instanceof MOB) transCode = CMMsg.TYP_SPEAK; else if (affected instanceof Weapon) transCode = CMMsg.TYP_WEAPONATTACK; else if (affected instanceof Armor) transCode = CMMsg.TYP_WEAR; else if (affected instanceof Item) transCode = CMMsg.TYP_GET; else if (affected instanceof Room) transCode = CMMsg.TYP_ENTER; else if (affected instanceof Area) transCode = CMMsg.TYP_ENTER; else if (affected instanceof Exit) transCode = CMMsg.TYP_ENTER; return transCode; } protected Exit getAnyExit(final Room R) { for (int d = 0; d < Directions.NUM_DIRECTIONS(); d++) { Exit E2 = R.getExitInDir(d); if (E2 != null) return E2; } return null; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if ((transCode() >= 0) && ((msg.targetMinor() == transCode()) || (msg.sourceMinor() == transCode())) && (msg.amITarget(affected) || (msg.tool() == affected)) && (roomID.length() > 0)) { final Room prevRoom = msg.source().location(); final Room otherRoom = CMLib.map().getRoom(roomID); if (otherRoom == null) msg.source().tell(L("You are whisked nowhere at all, since '@x1' is nowhere to be found.", roomID)); else if (prevRoom != otherRoom) { otherRoom.bringMobHere(msg.source(), true); if (sendEnter && (CMLib.map().getRoom(msg.source().location()) == CMLib.map().getRoom(otherRoom))) otherRoom.send(msg.source(), CMClass.getMsg(msg.source(), otherRoom, getAnyExit(otherRoom), CMMsg.MSG_ENTER, null)); CMLib.commands().postLook(msg.source(), true); if (affected instanceof Rideable) msg.addTrailerMsg(CMClass.getMsg(msg.source(), affected, CMMsg.TYP_DISMOUNT, null)); if ((affected instanceof Item) && (prevRoom.isContent((Item) affected))) prevRoom.delItem((Item) affected); } } super.executeMsg(myHost, msg); } }
38.14557
136
0.631823
ab603a5445619925d42d389b91ef32380db50460
502
package co.dporn.gmd.shared; import java.util.List; import java.util.Map; public class BlogEntryListResponse { private List<BlogEntry> entries; private Map<String, AccountInfo> infoMap; public Map<String, AccountInfo> getInfoMap() { return infoMap; } public List<BlogEntry> getBlogEntries() { return entries; } public void setBlogEntries(List<BlogEntry> entries) { this.entries = entries; } public void setInfoMap(Map<String, AccountInfo> infoMap) { this.infoMap = infoMap; } }
19.307692
59
0.743028
a979dff70831a243cef9a32d26a02b52210e65ca
1,989
package com.baeldung.annotations; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; 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.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @Controller @RequestMapping(value = "/vehicles", method = RequestMethod.GET) public class VehicleController { @CrossOrigin @ResponseBody @RequestMapping("/hello") public String hello() { return "Hello World!"; } @RequestMapping("/home") public String home() { return "home"; } @PostMapping("/save") public void saveVehicle(@RequestBody Vehicle vehicle) { } @RequestMapping("/{id}") public Vehicle getVehicle(@PathVariable("id") long id) { return null; } @RequestMapping public Vehicle getVehicleByParam(@RequestParam("id") long id) { return null; } @RequestMapping("/buy") public Car buyCar(@RequestParam(defaultValue = "5") int seatCount) { return null; } @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public void onIllegalArgumentException(IllegalArgumentException exception) { } @PostMapping("/assemble") public void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicle) { } @ModelAttribute("vehicle") public Vehicle getVehicle() { return null; } }
29.686567
80
0.740573
59c4f261e9a357c5a7afda0e5474599968ab12a8
415
package com.zkzong.override; /** * Created by Zong on 2016/12/4. */ class Base { } class Agg extends Base { public String getFields() { String name = "Agg"; return name; } } public class Avf { public static void main(String[] args) { Base a = new Agg(); System.out.println(((Agg) a).getFields()); // System.out.println(a.getFields()); // 编译错误,父类中无此方法 } }
18.043478
60
0.575904
02a744b79d89df71b131364a9d43390e499388fa
6,627
/* * Copyright 2021 Guardtime, Inc. * * This file is part of the KSI-HLF integration toolkit. * * 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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * "Guardtime" and "KSI" are trademarks or registered trademarks of * Guardtime, Inc., and no license to trademarks is granted; Guardtime * reserves and retains all trademark rights. */ package org.guardtime.ksi.hlf.util; import java.util.logging.Logger; import java.util.List; import java.util.logging.Level; import java.util.Iterator; import com.guardtime.ksi.hashing.DataHash; import com.guardtime.ksi.publication.PublicationData; import com.guardtime.ksi.unisignature.KSISignature; import com.guardtime.ksi.unisignature.verifier.PolicyVerificationResult; import com.guardtime.ksi.unisignature.verifier.VerificationResult; import com.guardtime.ksi.unisignature.verifier.VerificationResultCode; import com.guardtime.ksi.unisignature.verifier.policies.ContextAwarePolicy; import com.guardtime.ksi.unisignature.verifier.policies.ContextAwarePolicyAdapter; import com.guardtime.ksi.SignatureVerifier; import org.apache.commons.cli.CommandLine; import org.guardtime.ksi.hlf.contract.api.KsiContractApi; import org.guardtime.ksi.hlf.wrapper.KsiWrapper; import org.guardtime.ksi.hlf.contract.api.BlockHelper; class ToolTaskVerify extends ToolTask { ContextAwarePolicy policy; public ToolTaskVerify(Conf c, Logger log, CommandLine cmd) throws Exception { super(c, log, cmd); /* Create verification policy: */ if (cmd.hasOption("ver-int")) { policy = ContextAwarePolicyAdapter.createInternalPolicy(); } else if (cmd.hasOption("ver-cal")) { policy = ContextAwarePolicyAdapter.createCalendarPolicy(c.getExtender()); } else if (cmd.hasOption("ver-key")) { policy = ContextAwarePolicyAdapter.createKeyPolicy(c.getPubHandler()); } else if (cmd.hasOption("ver-pub") && cmd.hasOption("pub-str")) { PublicationData pubStr = new PublicationData(cmd.getOptionValue("pub-str")); if (cmd.hasOption("x")) { policy = ContextAwarePolicyAdapter.createUserProvidedPublicationPolicy(pubStr, c.getExtender()); } else { policy = ContextAwarePolicyAdapter.createUserProvidedPublicationPolicy(pubStr); } } else if (cmd.hasOption("ver-pub")) { if (cmd.hasOption("x")) { policy = ContextAwarePolicyAdapter.createPublicationsFilePolicy(c.getPubHandler(), c.getExtender()); } else { policy = ContextAwarePolicyAdapter.createPublicationsFilePolicy(c.getPubHandler()); } } else { policy = ContextAwarePolicyAdapter.createDefaultPolicy(c.getPubHandler(), c.getExtender()); } } @Override public void doTask(KsiContractApi ksicontract, BlockHelper bh, int blockNr, KsiWrapper sig) throws Exception { if (sig == null) { log.log(Level.INFO, " Unsigned block! Skipping verification."); return; } KSISignature ksig = sig.getKsi(); log.log(Level.INFO, " Verifying:"); log.log(Level.INFO, " Sig time : " + ksig.getAggregationTime()); if (sig.isExtended()) { log.log(Level.INFO, " Sig extended : " + ksig.getPublicationTime()); } else { log.log(Level.INFO, " Sig extended : -"); } log.log(Level.INFO, " Sig in hash : " + ksig.getInputHash()); try { log.log(Level.INFO, " Block hash : " + bh.getRootHash()); } catch (Exception e) { ; // TODO: Handle exception. } verifyBlock(sig, bh, this.getConf()); } private void compareRecordHashes(KsiWrapper sig, BlockHelper bh) throws Exception { DataHash[] sigRecHash = sig.getRecordHash(); DataHash[] blockRecHash = bh.getRecordHashes(); int loopSize = sigRecHash.length; if (sigRecHash.length != blockRecHash.length) { if (sigRecHash.length > blockRecHash.length) loopSize = blockRecHash.length; log.log(Level.INFO, "Signature and block contains different amount of record hashes!"); } String msg = "["; String res = "ok "; for (int i = 0; i < loopSize; i++) { if (!sigRecHash[i].equals(blockRecHash[i])) { msg += "x"; res = "fail"; } else { msg += "."; } } msg += "]"; log.log(Level.INFO, " Rec hash " + res + ": " + msg); return; } private void verifyBlock(KsiWrapper sig, BlockHelper bh, Conf c) { try { SignatureVerifier verifier = new SignatureVerifier(); KSISignature ksig = sig.getKsi(); /* Compare the record hashes. */ compareRecordHashes(sig, bh); /* Verify KSI signature and the root of the local aggregation. */ VerificationResult verificationResult = verifier.verify(ksig, bh.getRootHash(), (long) bh.getLevel(), this.policy); List<PolicyVerificationResult> rl = verificationResult.getPolicyVerificationResults(); Iterator<PolicyVerificationResult> rli = rl.iterator(); while (rli.hasNext()) { PolicyVerificationResult r = rli.next(); VerificationResultCode rps = r.getPolicyStatus(); if (rps.equals(VerificationResultCode.OK)) { log.log(Level.INFO, " OK: " + r.getPolicy().getName()); return; } else if (rps.equals(VerificationResultCode.FAIL)) { log.log(Level.INFO, "X FAILED: " + r.getPolicy().getName()); return; } } log.log(Level.INFO, " Verifying NA!"); } catch (Exception e) { log.log(Level.INFO, " Failure during verification!"); log.log(Level.INFO, e.toString()); log.log(Level.INFO, e.getMessage()); } } }
41.41875
116
0.626226
9d22b5f21da8f9a505fcf9ed2b053fbe00dc06c6
772
package top.inger.JpaDemo.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import top.inger.JpaDemo.domain.User; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> { //检验用户名是否存在 boolean existsUserByUserUsName(String userusname); // 通过用户名检验用户是否存在 // Optional<User> findByUserUsName(String userusname); //通过用户名查找用户 Optional<User> findUserByUserUsName(String userusname); //通过用户名和邮箱验证用户是否存在 Optional<User> findUserByUserUsNameAndUserEmail(String userusname, String useremail); }
32.166667
103
0.783679
fc17cc36f1528dbe285a55ed997441d05258117c
30,075
package com.softicar.platform.dom.elements.popup.compositor; import com.softicar.platform.common.core.i18n.IDisplayString; import com.softicar.platform.common.core.interfaces.INullaryVoidFunction; import com.softicar.platform.common.core.interfaces.IStaticObject; import com.softicar.platform.common.testing.AbstractTest; import com.softicar.platform.dom.document.CurrentDomDocument; import com.softicar.platform.dom.document.DomBody; import com.softicar.platform.dom.elements.DomDiv; import com.softicar.platform.dom.elements.button.DomButton; import com.softicar.platform.dom.elements.popup.DomPopup; import com.softicar.platform.dom.elements.popup.DomPopupFrame; import com.softicar.platform.dom.elements.popup.DomPopupMarker; import com.softicar.platform.dom.elements.popup.configuration.DomPopupConfiguration; import com.softicar.platform.dom.elements.popup.modal.DomModalPopupBackdrop; import com.softicar.platform.dom.elements.testing.engine.IDomTestExecutionEngine; import com.softicar.platform.dom.elements.testing.engine.IDomTestExecutionEngineMethods; import com.softicar.platform.dom.elements.testing.engine.document.DomDocumentTestExecutionEngine; import com.softicar.platform.dom.elements.testing.node.tester.DomNodeTester; import com.softicar.platform.dom.node.IDomNode; import com.softicar.platform.dom.parent.IDomParentElement; import java.util.List; import java.util.stream.Collectors; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; public class DomDefaultPopupCompositorTest extends AbstractTest implements IDomTestExecutionEngineMethods { private static final IStaticObject POPUP1 = Mockito.mock(IStaticObject.class); private static final IStaticObject POPUP2 = Mockito.mock(IStaticObject.class); private static final IStaticObject POPUP3 = Mockito.mock(IStaticObject.class); private static final String TEST_TEXT = "Some text in the element-under-test"; @Rule public IDomTestExecutionEngine engine = new DomDocumentTestExecutionEngine(); private final DomDefaultPopupCompositor compositor; private final TestDiv testDiv; private final DomPopupConfiguration popup1Config; private final DomPopupConfiguration popup2Config; private final DomPopupConfiguration popup3Config; private final DomPopup popup1; private final DomPopup popup2; private final DomPopup popup3; public DomDefaultPopupCompositorTest() { this.compositor = new DomDefaultPopupCompositor(); this.testDiv = new TestDiv(); this.testDiv.appendText(TEST_TEXT); this.popup1Config = new DomPopupConfiguration(); this.popup2Config = new DomPopupConfiguration(); this.popup3Config = new DomPopupConfiguration(); this.popup1 = new DomPopup().setConfiguration(popup1Config); this.popup1.addMarker(POPUP1); this.popup2 = new DomPopup().setConfiguration(popup2Config); this.popup2.addMarker(POPUP2); this.popup3 = new DomPopup().setConfiguration(popup3Config); this.popup3.addMarker(POPUP3); setNodeSupplier(() -> testDiv); } @Override public IDomTestExecutionEngine getEngine() { return engine; } // -------------------------------- open -------------------------------- // @Test public void testOpenWithDraggablePopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); // assert initial state assertNone(POPUP1); assertNoBackdrop(); assertBodyText(); // execute openPopup1Button.click(); // assert result assertOne(POPUP1); assertNoBackdrop(); assertBodyText(); } @Test public void testOpenWithDraggablePopupFromMaximizedPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); // assert initial state assertNone(POPUP1); assertOne(POPUP2); assertNone(POPUP3); assertNoBackdrop(); assertNoBodyText(); // execute openPopup3Button.click(); // assert result assertNone(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertNoBackdrop(); assertNoBodyText(); } @Test public void testOpenWithDraggablePopupReplacingDraggablePopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); var openPopup2Button = appendButton(popup1, () -> { compositor.open(popup2); compositor.close(popup1); }); // assert initial state assertOne(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); // execute openPopup2Button.click(); // assert result assertNone(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testOpenWithMaximizedPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); // assert initial state assertOne(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); // execute openPopup2Button.click(); // assert result assertNone(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertNoBodyText(); } @Test public void testOpenWithModalPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); // assert initial state assertOne(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); // execute openPopup2Button.click(); // assert result assertOne(POPUP1); assertOne(POPUP2); assertBackdrop(); assertBodyText(); assertAscendingZIndexes(popup1, findBackdrop(), popup2); // TODO PLAT-847 assert focus } @Test public void testOpenWithModalPopupFromModalPopup() { // setup popup1Config.setDisplayModeDraggableModal(); var openPopup1Button = appendButton(() -> compositor.open(popup1)); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); // assert initial state assertNone(POPUP1); assertNone(POPUP2); assertNone(POPUP3); assertNoBackdrop(); assertBodyText(); // execute openPopup1Button.click(); openPopup2Button.click(); openPopup3Button.click(); // assert result assertOne(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertBackdrops(2); assertBodyText(); List<IDomNode> backdrops = findBackdrops(); assertAscendingZIndexes(backdrops.get(0), popup1, backdrops.get(1), popup2, popup3); } @Test public void testOpenWithModalPopupFromBody() { // setup popup1Config.setDisplayModeDraggableModal(); DomBody body = CurrentDomDocument.get().getBody(); DomNodeTester openPopup1Button = asTester(body.appendChild(new DomButton().setClickCallback(() -> compositor.open(popup1)))); // assert initial state assertNone(POPUP1); assertNoBackdrop(); assertBodyText(); // execute openPopup1Button.click(); // assert result assertOne(POPUP1); assertBackdropOnBody(); assertBodyText(); } @Test public void testOpenWithPopoverFromModalPopup() { // setup popup1Config.setDisplayModeDraggableModal(); var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModePopover(); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); // assert initial state assertOne(POPUP1); assertNone(POPUP2); assertBackdrop(); assertBodyText(); // execute openPopup2Button.click(); // assert result assertOne(POPUP1); assertOne(POPUP2); assertBackdrops(true, false); assertBodyText(); } @Test public void testOpenWithOpenPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); // assert initial state assertNone(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); // execute openPopup1Button.click(); openPopup2Button.click(); openPopup1Button.click(); // assert result assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); assertAscendingZIndexes(popup2, popup1); } // -------------------------------- close -------------------------------- // @Test public void testCloseWithDraggablePopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); var closePopup1Button = appendButton(() -> compositor.close(popup1)); openPopup1Button.click(); // assert initial state assertOne(POPUP1); assertNoBackdrop(); assertBodyText(); // execute closePopup1Button.click(); // assert result assertNone(POPUP1); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseWithDraggablePopupAndChildRetention() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); var closePopup1Button = appendButton(() -> compositor.close(popup1)); openPopup1Button.click(); openPopup2Button.click(); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); // execute closePopup1Button.click(); // assert result assertNone(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseWithDraggablePopupAndChildClosing() { // setup popup1Config.setChildClosingModeInteractiveAll(); var openPopup1Button = appendButton(() -> compositor.open(popup1)); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); var closePopup1Button = appendButton(() -> compositor.close(popup1)); openPopup1Button.click(); openPopup2Button.click(); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); // execute closePopup1Button.click(); // assert result assertNone(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseWithMaximizedPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.close(popup2)); // assert initial state assertNone(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertNoBodyText(); // execute closePopup2Button.click(); // assert result assertOne(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseWithMaximizedPopupAndChild() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); popup2Config.setChildClosingModeInteractiveAll(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); openPopup3Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.close(popup2)); // assert initial state assertNone(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertNoBackdrop(); assertNoBodyText(); // execute closePopup2Button.click(); // assert result assertOne(POPUP1); assertNone(POPUP2); assertNone(POPUP3); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseWithModalPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.close(popup2)); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertBackdrop(); assertBodyText(); // execute closePopup2Button.click(); // assert result assertOne(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseWithModalPopupAndChild() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); openPopup3Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.close(popup2)); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertBackdrop(); assertBodyText(); // execute closePopup2Button.click(); // assert result assertOne(POPUP1); assertNone(POPUP2); assertNone(POPUP3); assertNoBackdrop(); assertBodyText(); } // -------------------------------- closeAll -------------------------------- // @Test public void testCloseAll() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); var openPopup2Button = appendButton(() -> compositor.open(popup2)); var closeAllButton = appendButton(() -> compositor.closeAll()); openPopup1Button.click(); openPopup2Button.click(); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); // execute closeAllButton.click(); // assert result assertNone(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseAllWithMaximizedPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var closeAllButton = appendButton(popup2, () -> compositor.closeAll()); // assert initial state assertNone(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertNoBodyText(); // execute closeAllButton.click(); // assert result assertNone(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseAllWithMaximizedPopupAndChild() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); openPopup3Button.click(); var closeAllButton = appendButton(popup2, () -> compositor.closeAll()); // assert initial state assertNone(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertNoBackdrop(); assertNoBodyText(); // execute closeAllButton.click(); // assert result assertNone(POPUP1); assertNone(POPUP2); assertNone(POPUP3); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseAllWithModalPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var closeAllButton = appendButton(popup2, () -> compositor.closeAll()); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertBackdrop(); assertBodyText(); // execute closeAllButton.click(); // assert result assertNone(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseAllWithModalPopupAndChild() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); openPopup3Button.click(); var closeAllButton = appendButton(popup2, () -> compositor.closeAll()); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertBackdrop(); assertBodyText(); // execute closeAllButton.click(); // assert result assertNone(POPUP1); assertNone(POPUP2); assertNone(POPUP3); assertNoBackdrop(); assertBodyText(); } // -------------------------------- closeInteractively -------------------------------- // @Test public void testCloseInteractivelyWithDraggablePopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); var closePopup1Button = appendButton(() -> compositor.closeInteractively(popup1)); openPopup1Button.click(); // assert initial state assertOne(POPUP1); assertNoBackdrop(); assertBodyText(); // execute closePopup1Button.click(); // assert result assertNone(POPUP1); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithDraggablePopupAndChildRetention() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); var closePopup1Button = appendButton(() -> compositor.closeInteractively(popup1)); openPopup1Button.click(); openPopup2Button.click(); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); // execute closePopup1Button.click(); // assert result assertNone(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithDraggablePopupAndChildClosingConfirmedAll() { // setup popup1Config.setChildClosingModeInteractiveOptional(); var openPopup1Button = appendButton(() -> compositor.open(popup1)); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); var closePopup1Button = appendButton(() -> compositor.closeInteractively(popup1)); openPopup1Button.click(); openPopup2Button.click(); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); // execute closePopup1Button.click(); findButton(DomPopupCompositorDialogMarker.BUTTON_CLOSE_ALL).click(); // assert result assertNone(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithDraggablePopupAndChildClosingConfirmedParentOnly() { // setup popup1Config.setChildClosingModeInteractiveOptional(); var openPopup1Button = appendButton(() -> compositor.open(popup1)); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); var closePopup1Button = appendButton(() -> compositor.closeInteractively(popup1)); openPopup1Button.click(); openPopup2Button.click(); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); // execute closePopup1Button.click(); findButton(DomPopupCompositorDialogMarker.BUTTON_CLOSE_PARENT_ONLY).click(); // assert result assertNone(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithDraggablePopupAndChildClosingCancelled() { // setup popup1Config.setChildClosingModeInteractiveOptional(); var openPopup1Button = appendButton(() -> compositor.open(popup1)); var openPopup2Button = appendButton(popup1, () -> compositor.open(popup2)); var closePopup1Button = appendButton(() -> compositor.closeInteractively(popup1)); openPopup1Button.click(); openPopup2Button.click(); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); // execute closePopup1Button.click(); findButton(DomPopupCompositorDialogMarker.BUTTON_CANCEL).click(); // assert result assertOne(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithMaximizedPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.closeInteractively(popup2)); // assert initial state assertNone(POPUP1); assertOne(POPUP2); assertNoBackdrop(); assertNoBodyText(); // execute closePopup2Button.click(); // assert result assertOne(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithMaximizedPopupAndChildClosingConfirmed() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); openPopup3Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.closeInteractively(popup2)); // assert initial state assertNone(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertNoBackdrop(); assertNoBodyText(); // execute closePopup2Button.click(); findButton(DomPopupCompositorDialogMarker.BUTTON_CLOSE_ALL).click(); // assert result assertOne(POPUP1); assertNone(POPUP2); assertNone(POPUP3); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithMaximizedPopupAndChildClosingCancelled() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeMaximized(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); openPopup3Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.closeInteractively(popup2)); // assert initial state assertNone(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertNoBackdrop(); assertNoBodyText(); // execute closePopup2Button.click(); findButton(DomPopupCompositorDialogMarker.BUTTON_CANCEL).click(); // assert result assertNone(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertNoBackdrop(); assertNoBodyText(); } @Test public void testCloseInteractivelyWithModalPopup() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.closeInteractively(popup2)); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertBackdrop(); assertBodyText(); // execute closePopup2Button.click(); // assert result assertOne(POPUP1); assertNone(POPUP2); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithModalPopupAndChildClosingConfirmed() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); openPopup3Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.closeInteractively(popup2)); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertBackdrop(); assertBodyText(); // execute closePopup2Button.click(); findButton(DomPopupCompositorDialogMarker.BUTTON_CLOSE_ALL).click(); // assert result assertOne(POPUP1); assertNone(POPUP2); assertNone(POPUP3); assertNoBackdrop(); assertBodyText(); } @Test public void testCloseInteractivelyWithModalPopupAndChildClosingCancelled() { // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); popup2Config.setDisplayModeDraggableModal(); var openPopup2Button = appendButton(() -> compositor.open(popup2)); openPopup2Button.click(); var openPopup3Button = appendButton(popup2, () -> compositor.open(popup3)); openPopup3Button.click(); var closePopup2Button = appendButton(popup2, () -> compositor.closeInteractively(popup2)); // assert initial state assertOne(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertBackdrop(); assertBodyText(); // execute closePopup2Button.click(); findButton(DomPopupCompositorDialogMarker.BUTTON_CANCEL).click(); // assert result assertOne(POPUP1); assertOne(POPUP2); assertOne(POPUP3); assertBackdrop(); assertBodyText(); } // -------------------------------- focus -------------------------------- // @Ignore @Test public void testFocus() { // TODO PLAT-847 must be implemented before this test can be written. } // -------------------------------- refreshFrame -------------------------------- // @Test public void testRefreshFrame() { // setup popup1Config.setCaption(IDisplayString.create("aaa")); popup1Config.setSubCaption(IDisplayString.create("bbb")); // setup var openPopup1Button = appendButton(() -> compositor.open(popup1)); openPopup1Button.click(); var refreshFramePopup1Button = appendButton(() -> compositor.refreshFrame(popup1)); popup1Config.setCaption(IDisplayString.create("xxx")); popup1Config.setSubCaption(IDisplayString.create("yyy")); // assert initial state assertOne(POPUP1); assertNoBackdrop(); assertBodyText(); findNode(DomPopupMarker.FRAME_HEADER).assertContainsText("aaa"); findNode(DomPopupMarker.FRAME_HEADER).assertContainsText("bbb"); findBody().assertContainsText(TEST_TEXT); // execute refreshFramePopup1Button.click(); // assert results assertOne(POPUP1); assertNoBackdrop(); assertBodyText(); findNode(DomPopupMarker.FRAME_HEADER).assertContainsText("xxx"); findNode(DomPopupMarker.FRAME_HEADER).assertContainsText("yyy"); findBody().assertContainsText(TEST_TEXT); } // -------------------------------- private -------------------------------- // private void assertNone(IStaticObject marker) { findNodes(marker).assertNone(); } private DomNodeTester assertOne(IStaticObject marker) { return findNodes(marker).assertOne(); } private List<DomNodeTester> assertCount(IStaticObject marker, int count) { return findNodes(marker).assertSize(count); } private void assertNoBackdrop() { assertNone(DomPopupMarker.BACKDROP); } private void assertBackdrop() { var backdrop = assertOne(DomPopupMarker.BACKDROP); assertBackdropParent(backdrop, testDiv); } private void assertBackdropOnBody() { var backdrop = assertOne(DomPopupMarker.BACKDROP); assertBackdropParent(backdrop, CurrentDomDocument.get().getBody()); } private void assertBackdrops(int count) { assertCount(DomPopupMarker.BACKDROP, count).forEach(it -> assertBackdropParent(it, testDiv)); } private void assertBackdropParent(DomNodeTester backdropTester, IDomNode expectedParent) { var backdropNode = backdropTester.getNode(); assertSame(// "Expected backdrop node %s to have a parent of type %s.".formatted(backdropNode.getNodeIdString(), expectedParent.getClass().getSimpleName()), expectedParent, backdropNode.getParent()); } private void assertBackdrops(Boolean...visible) { List<DomModalPopupBackdrop> backdrops = assertCount(DomPopupMarker.BACKDROP, visible.length)// .stream() .map(DomNodeTester::getNode) .map(DomModalPopupBackdrop.class::cast) .collect(Collectors.toList()); for (int i = 0; i < visible.length; i++) { DomModalPopupBackdrop backdrop = backdrops.get(i); assertEquals(visible[i], backdrop.isVisible()); } } private void assertBodyText() { findBody().assertContainsText(TEST_TEXT); } private void assertNoBodyText() { findBody().assertDoesNotContainText(TEST_TEXT); } private void assertAscendingZIndexes(IDomNode...nodes) { for (int i = 0; i < nodes.length - 1; i++) { IDomNode current = nodes[i]; IDomNode next = nodes[i + 1]; assertTrue(// "Expected node %s to be below node %s.".formatted(toString(current), toString(next)), getZIndex(current) < getZIndex(next)); } } private String toString(IDomNode node) { return "%s (z-index %s, %s)".formatted(node.getNodeId(), getZIndex(node), node.getClass().getCanonicalName()); } private DomNodeTester appendButton(INullaryVoidFunction callback) { return appendButton(testDiv, callback); } private DomNodeTester appendButton(IDomParentElement target, INullaryVoidFunction callback) { return asTester(target.appendChild(new DomButton().setClickCallback(callback))); } private IDomNode findBackdrop() { return findNodes(DomPopupMarker.BACKDROP).assertOne().getNode(); } private List<IDomNode> findBackdrops() { return findNodes(DomPopupMarker.BACKDROP).toList().stream().map(DomNodeTester::getNode).collect(Collectors.toList()); } private int getZIndex(IDomNode node) { if (node instanceof DomPopup) { node = new DomParentNodeFinder<>(DomPopupFrame.class).findClosestParent(node).get(); } return asTester(node).getZIndex(); } private static class TestDiv extends DomDiv implements IDomPopupMaximizationContext { // nothing } }
25.53056
145
0.729044
60bda3c9246875acc98d899930711b2d730ff955
1,511
package com.sailthru.android.sdk.impl.event; import com.sailthru.android.sdk.impl.external.gson.Gson; import com.sailthru.android.sdk.impl.external.tape.FileObjectQueue; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; /** * Created by Vijay Penemetsa on 5/28/14. * * Use GSON to serialize classes to bytes. * <p> * Note: This will only work when concrete classes are specified for {@code T}. If you want to specify an interface for * {@code T} then you need to also include the concrete class name in the serialized byte array so that you can * deserialize to the appropriate type. */ class GsonConverter<T> implements FileObjectQueue.Converter<T> { private final Gson gson; private final Class<T> type; public GsonConverter(Gson gson, Class<T> type) { this.gson = gson; this.type = type; } /** * {@inheritDoc} */ @Override public T from(byte[] bytes) { Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes)); return gson.fromJson(reader, type); } /** * {@inheritDoc} */ @Override public void toStream(T object, OutputStream bytes) { try { Writer writer = new OutputStreamWriter(bytes); gson.toJson(object, writer); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
28.509434
119
0.669093
ee06e08cf6c002a807edd4cf76511c271017ee32
1,317
package org.basex.local.single; import java.util.*; import org.basex.*; import org.basex.core.*; import org.basex.core.cmd.*; import org.junit.Test; /** * This test replaces texts in-place and checks if the database text files increase * in size. Currently, the actual test is wrapped in comments. * * @author BaseX Team 2005-17, BSD License * @author Christian Gruen */ public final class ReplaceInPlaceTest extends SandboxTest { /** Number of queries to be run. */ private static final int NQUERIES = 10000; /** Random number generator. */ static final Random RND = new Random(); /** Result counter. */ static int counter; /** * Runs the test. */ @Test public void run() { set(MainOptions.TEXTINDEX, false); set(MainOptions.ATTRINDEX, false); set(MainOptions.AUTOFLUSH, false); // create test database execute(new CreateDB(NAME, "<X>" + "<A>x.xxxxxxxxxxxxxxxxxx</A>" + "<A>x.xxxxxxxxxxxxxxxxxx</A></X>")); // replace texts with random doubles final Random rnd = new Random(); for(int i = 0; i < NQUERIES; i++) { query("for $a in //A return replace node $a/text() with " + rnd.nextDouble()); } // perform final, flushed replacement execute(new Flush()); // Drop database execute(new DropDB(NAME)); } }
25.326923
84
0.650721
844ef2fd62a6b73f6ac81b4bd6ae1949c3017f4a
20,797
package com.hawthorn.framework.generator; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.hawthorn.framework.exception.BizCode; import com.hawthorn.framework.exception.BizException; import com.hawthorn.framework.utils.common.Str2Util; import com.hawthorn.framework.utils.iassert.AssertUtil; import com.hawthorn.framework.utils.resource.YmlUtil; import com.mysql.cj.util.StringUtils; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.util.*; /** * @Copyright: Copyright (c) 2020 andyten * @remark: mybatis-plus 代码生成器 * @author:andy.ten@tom.com * @date:2020/8/16 5:29 下午 * @version v1.0.1 */ @Slf4j public class MPCodeGenerator { private static final String RESOURCE_FILE = "generator.yml"; private static final String JAVA_VM_SUFFIX = ".java.vm"; private static final String OUTPUT_MODULE_NAME = "output.moduleName"; private static final String OUTPUT_PACKAGE_NAME = "output.packageName"; private static final String OUTPUT_PATH = "output.path"; private static final String OUTPUT_DEFINE_CHILDPACKAGE_CONTROLLER = "output.defineChildPackage.controller"; private static final String OUTPUT_DEFINE_CHILDPACKAGE_MAPPER = "output.defineChildPackage.mapper"; private static final String OUTPUT_DEFINE_CHILDPACKAGE_ENTITY = "output.defineChildPackage.entity"; private static final String OUTPUT_DEFINE_CHILDPACKAGE_DTO = "output.defineChildPackage.dto"; private static final String OUTPUT_DEFINE_CHILDPACKAGE_SERVICE = "output.defineChildPackage.service"; private static final String OUTPUT_DEFINE_CHILDPACKAGE_SERVICEIMPL = "output.defineChildPackage.serviceImpl"; /** * @remark: 读取控制台的内容 * @param: tip * @return: java.lang.String * @author: andy.ten@tom.com * @date: 2020/8/16 5:32 下午 * @version: 1.0.1 * Modification History: * Date Author Version Description * ----------------------------------------------------------- * 2020/8/16 andy.ten v1.0.1 init */ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); log.info("请输入" + tip + ": " ); if (scanner.hasNext()) { String ipt = scanner.next(); return AssertUtil.notEmpty(ipt, BizCode.CONSOLE_INPUT_TIP, "tip" ); // if (StrUtil.isNotEmpty(ipt)) // { // return ipt; // } } throw new BizException(BizCode.CONSOLE_INPUT_TIP.getCode(), Str2Util.placeHolder(BizCode.CONSOLE_INPUT_TIP.getMsg(), tip)); } /** * @remark: 代码生成方法 * @param: * @return: void * @author: andy.ten@tom.com * @date: 2020/8/16 6:13 下午 * @version: 1.0.1 * Modification History: * Date Author Version Description * ----------------------------------------------------------- * 2020/8/16 andy.ten v1.0.1 init */ public static void generate() { // 文件目录结构设置 // 加载yml生成配置文件 Properties properties = YmlUtil.yaml2Properties(RESOURCE_FILE); // 输出的模块名 //String moduleName = properties.getProperty(OUTPUT_MODULE_NAME); String moduleName = scanner("模块名" ); properties.setProperty(OUTPUT_MODULE_NAME, moduleName); // 将模块.改为路径:/ String moduleNameDir = moduleName.replaceAll("\\.", "/" ); // 输出目录的一级包名,例如:com.**.admin String packageName = properties.getProperty(OUTPUT_PACKAGE_NAME); // 输出一级包下的controller层子包,例如:com.**.admin.controller String controllerPackage = Str2Util.emptyToDefault(properties.getProperty(OUTPUT_DEFINE_CHILDPACKAGE_CONTROLLER), "controller" ); // 输出一级包下的mapper层子包,例如:com.**.admin.repository String mapperPackage = Str2Util.emptyToDefault(properties.getProperty(OUTPUT_DEFINE_CHILDPACKAGE_MAPPER), "repository" ); // 输出一级包下的model层po子包,例如:com.**.admin.model String entityPackage = Str2Util.emptyToDefault(properties.getProperty(OUTPUT_DEFINE_CHILDPACKAGE_ENTITY), "entity" ); String dtoPackage = Str2Util.emptyToDefault(properties.getProperty(OUTPUT_DEFINE_CHILDPACKAGE_DTO), "dto" ); // 输出一级包下的service层子包,例如:com.**.admin.service String servicePackage = Str2Util.emptyToDefault(properties.getProperty(OUTPUT_DEFINE_CHILDPACKAGE_SERVICE), "service" ); // 输出一级包下的serviceImpl层子包,例如:com.**.admin.service.impl String serviceImplPackage = Str2Util.emptyToDefault(properties.getProperty(OUTPUT_DEFINE_CHILDPACKAGE_SERVICEIMPL), "impl" ); //策略配置 CustomStrategyConfig customConfig = new CustomStrategyConfig(); // 自定义继承的Entity类全称,带包名 customConfig.setSuperEntityClass("com.hawthorn.framework.model.BasePO" ); // 自定义基础的Entity类,公共字段 customConfig.setSuperEntityColumns(new String[]{"CREATED_BY", "CREATED_TIME", "LAST_UPDATED_BY", "LAST_UPDATED_TIME", "VERSION", "DEL_FLAG"}); // 自定义继承的Mapper类全称,带包名 customConfig.setSuperMapperClass("com.hawthorn.framework.repository.DBMapper" ); // 自定义继承的Controller类全称,带包名 //customConfig.setSuperControllerClass("com.hawthorn.framwork.controller"); // 是否移除is前缀(默认 false) customConfig.setEntityBooleanColumnRemoveIsPrefix(false); // 逻辑删除属性名称 customConfig.setLogicDeleteFieldName("DEL_FLAG" ); // 第一步:代码生成器 AutoGenerator mpg = new AutoGenerator(); // 第二步:全局配置 + 数据源配置 + 策略配置 setAutoGeneratorConfig(mpg, properties, customConfig); // 第三步:进行模板配置 setTemplateConfig(mpg, properties); // 第四步:包名配置 PackageConfig packageConfig = new PackageConfig().setParent(packageName); packageConfig.setController(controllerPackage + "." + moduleName); packageConfig.setEntity(entityPackage + "." + moduleName); packageConfig.setService(servicePackage + "." + moduleName); packageConfig.setServiceImpl(servicePackage + "." + moduleName + "." + serviceImplPackage); // 设置mapper类路径,对应模版中的${package.Mapper} // 路径:com.hawthron.admin.repository.SysUserMapper packageConfig.setMapper(mapperPackage); // 路径:com.hawthron.admin.repository.sysuser.SysUserMapper //packageConfig.setMapper(mapperPackage + "." + moduleName); mpg.setPackageInfo(packageConfig); final String dtoPackageStatic = dtoPackage == null ? "model.dto" : dtoPackage; InjectionConfig injectionConfig = new InjectionConfig() { /** * 注入自定义 Map 对象 */ @Override public void initMap() { this.getConfig().getGlobalConfig().getEntityName(); Map<String, Object> map = new HashMap<>(); map.put("packageDto", packageName + (mpg.getPackageInfo().getModuleName() == null ? "" : mpg.getPackageInfo().getModuleName().equals("" ) ? "" : "." + mpg.getPackageInfo().getModuleName()) + "." + dtoPackageStatic + "." + moduleName); map.put("moduleName", moduleNameDir); map.put("packageServiceImplTest", packageName + (mpg.getPackageInfo().getModuleName() == null ? "" : mpg.getPackageInfo().getModuleName().equals("" ) ? "" : "." + mpg.getPackageInfo().getModuleName()) + "." + servicePackage + "." + moduleName); this.setMap(map); } }; List<FileOutConfig> fileOutConfigs = new ArrayList<>(); //进行xml 生成配置 setXmlOutPutConfig(properties, fileOutConfigs); //进行PO 输出配置 setPoOutPutConfig(properties, fileOutConfigs, mpg); //进行DTO 输出配置 setDtoOutPutConfig(properties, fileOutConfigs, mpg); //进行ControllerTest 输出配置 setControllerTestConfig(properties, fileOutConfigs, mpg); //进行ServiceTest 输出配置 setServiceTestConfig(properties, fileOutConfigs, mpg); injectionConfig.setFileOutConfigList(fileOutConfigs); mpg.setCfg(injectionConfig); // 执行生成 mpg.execute(); } // 全局配置 + 数据源配置 + 策略配置 @SuppressWarnings("deprecation" ) private static void setAutoGeneratorConfig(AutoGenerator mpg, Properties properties, CustomStrategyConfig customConfig) { // 文件路径 String outputPath = properties.getProperty(OUTPUT_PATH); File file = new File(outputPath); String path = file.getAbsolutePath(); // 作者 String authorName = properties.getProperty("output.author" ); //table名字 //String[] tables = properties.getProperty("table.tableNames").split(","); //table前缀 String prefix = properties.getProperty("table.tablePrefix" ); //全局配置 mpg.setGlobalConfig( // 全局配置 new GlobalConfig() .setOutputDir(path + "/src/main/java" )//输出目录 .setFileOverride(true)// 是否覆盖文件 .setActiveRecord(false)// 关闭 activeRecord 模式 .setEnableCache(false)// XML 二级缓存 .setBaseResultMap(true)// XML ResultMap .setBaseColumnList(true)// XML columList .setOpen(false)//生成后打开文件夹 .setSwagger2(true)//生成swagger api .setAuthor(authorName) // 自定义文件命名,注意 %s 会自动填充表实体属性! .setMapperName("%sMapper" ) .setXmlName("%sMapper" ) .setEntityName("%sPO" ) .setServiceName("%sService" ) .setServiceImplName("%sServiceImpl" ) .setControllerName("%sController" ) ); //配置数据源 mpg.setDataSource( // 数据源配置 new DataSourceConfig() .setDbType(DbType.MYSQL)// 数据库类型 .setDriverName(properties.getProperty("datasource.driverName" )) .setUsername(properties.getProperty("datasource.username" )) .setPassword(properties.getProperty("datasource.password" )) .setUrl(properties.getProperty("datasource.url" )) //设置mysql数据类型转换 tinyint转为Integer .setTypeConvert(new MySqlTypeConvertConfig()) ); //配置策略 mpg.setStrategy( // 策略配置 new StrategyConfig() .setTablePrefix(prefix)// 此处可以修改为您的表前缀 .setNaming(NamingStrategy.underline_to_camel)// 配置数据表与实体类名之间映射的策略 .setColumnNaming(NamingStrategy.underline_to_camel)// 配置数据表的字段与实体类的属性名之间映射的策略 //.setInclude(tables) // 指定需要生成文件的表名 .setInclude(scanner("表名,多个英文逗号分割" ).split("," )) .setRestControllerStyle(true) // 配置 rest 风格的控制器(@RestController) .setEntityLombokModel(true) // 配置 lombok 模式 //.setExclude(new String[]{"test"}) // 排除生成的表 // 自定义实体父类 // .setSuperEntityClass("com.baomidou.demo.TestEntity") // 自定义实体,公共字段 .setSuperEntityColumns(customConfig.getSuperEntityColumns()) // 公共字段填充 .setTableFillList(null) .setSuperEntityClass(customConfig.getSuperEntityClass()) // 自定义 mapper 父类 .setSuperMapperClass(customConfig.getSuperMapperClass()) // 自定义 service 父类 // .setSuperServiceClass("com.baomidou.demo.TestService") // 自定义 service 实现类父类 // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl") // 自定义 controller 父类 .setSuperControllerClass(customConfig.getSuperControllerClass()) .setEntityBooleanColumnRemoveIsPrefix(customConfig.isEntityBooleanColumnRemoveIsPrefix()) .setLogicDeleteFieldName(customConfig.getLogicDeleteFieldName()) .setVersionFieldName(customConfig.getLogicDeleteFieldName()) // .setRestControllerStyle(true) // .setControllerMappingHyphenStyle(true) ); } private static void setTemplateConfig(AutoGenerator mpg, Properties properties) { String isServiceImplGenerate = properties.getProperty("output.isGeneratePackage.serviceImpl" ); String isControllerGenerate = properties.getProperty("output.isGeneratePackage.controller" ); String isMapperGenerate = properties.getProperty("output.isGeneratePackage.mapper" ); String isServiceGenerate = properties.getProperty("output.isGeneratePackage.service" ); String isEntityGenerate = properties.getProperty("output.isGeneratePackage.entity" ); // 关闭默认 xml 生成,调整生成 至 根目录 TemplateConfig templateConfig = new TemplateConfig().setXml(null); // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置: if (Str2Util.isEmpty(isControllerGenerate) || isControllerGenerate.equals("true" )) { templateConfig.setController("/template/myController.java.vm" ); } else { templateConfig.setController(null); } if (Str2Util.isEmpty(isEntityGenerate) || isEntityGenerate.equals("true" )) { templateConfig.setEntity(null); // 关闭默认的entity生成 //templateConfig.setEntity("/template/myEntity.java.vm" ); } else { templateConfig.setEntity(null); } if (Str2Util.isEmpty(isServiceGenerate) || isServiceGenerate.equals("true" )) { templateConfig.setService("/template/myService.java.vm" ); } else { templateConfig.setService(null); } if (Str2Util.isEmpty(isServiceImplGenerate) || isServiceImplGenerate.equals("true" )) { templateConfig.setServiceImpl("/template/myServiceImpl.java.vm" ); } else { templateConfig.setServiceImpl(null); } if (Str2Util.isEmpty(isMapperGenerate) || isMapperGenerate.equals("true" )) { templateConfig.setMapper("/template/myMapper.java.vm" ); } else { templateConfig.setMapper(null); } mpg.setTemplate(templateConfig); } private static void setXmlOutPutConfig(Properties properties, List<FileOutConfig> fileOutConfigs) { String mapperXmlPackage = properties.getProperty("output.defineChildPackage.mapperXml" ); final String mapperXmlPackageStatic = mapperXmlPackage == null ? "mapper" : mapperXmlPackage; String moduleName = properties.getProperty(OUTPUT_MODULE_NAME); String moduleNameDir = moduleName.replaceAll("\\.", "/" ); //文件路径 String outputPath = properties.getProperty(OUTPUT_PATH); File file = new File(outputPath); String path = file.getAbsolutePath(); FileOutConfig xmlFileConfig = new FileOutConfig("/template/myMapper" + ".xml.vm" ) { /** * 输出文件 * * @param tableInfo */ @Override public String outputFile(TableInfo tableInfo) { return path + "/src/main/resources/" + mapperXmlPackageStatic.replaceAll("\\.", "/" ) + "/" + "/" + tableInfo.getXmlName() + ".xml"; // return path + "/src/main/resources/" + mapperXmlPackageStatic.replaceAll("\\.", "/" ) + "/" + // moduleNameDir // + "/" + Str2Util.firstCharToLowerCase(tableInfo.getEntityName()) // + "Mapper" + // ".xml"; } }; String isMapperXmlGenerate = properties.getProperty("output.isGeneratePackage.mapperXml" ); if (StringUtils.isNullOrEmpty(isMapperXmlGenerate) || isMapperXmlGenerate.equals("true" )) { fileOutConfigs.add(xmlFileConfig); } } // 输出po private static void setPoOutPutConfig(Properties properties, List<FileOutConfig> fileOutConfigs, AutoGenerator mpg) { String poPackage = properties.getProperty(OUTPUT_DEFINE_CHILDPACKAGE_ENTITY); final String poPackageStatic = poPackage == null ? "bean.po" : poPackage; String moduleName = properties.getProperty(OUTPUT_MODULE_NAME); String moduleNameDir = moduleName.replaceAll("\\.", "/" ); //文件路径 String outputPath = properties.getProperty(OUTPUT_PATH); File file = new File(outputPath); String path = file.getAbsolutePath(); FileOutConfig poFileConfig = new FileOutConfig("/template/myEntity" + JAVA_VM_SUFFIX) { /** * 输出文件 * * @param tableInfo */ @Override public String outputFile(TableInfo tableInfo) { return path + "/src/main/java/" + mpg.getPackageInfo().getParent().replaceAll("\\.", "/" ) + "/" + poPackageStatic.replaceAll("\\.", "/" ) //+ ("/" + moduleNameDir) + "/" + tableInfo.getEntityName().substring(0, tableInfo.getEntityName().length() - 2) + "PO.java"; } }; String isPoGenerate = properties.getProperty("output.isGeneratePackage.entity" ); if (StringUtils.isNullOrEmpty(isPoGenerate) || isPoGenerate.equals("true" )) { fileOutConfigs.add(poFileConfig); } } // 输出dto private static void setDtoOutPutConfig(Properties properties, List<FileOutConfig> fileOutConfigs, AutoGenerator mpg) { String dtoPackage = properties.getProperty(OUTPUT_DEFINE_CHILDPACKAGE_DTO); final String dtoPackageStatic = dtoPackage == null ? "bean.dto" : dtoPackage; String moduleName = properties.getProperty(OUTPUT_MODULE_NAME); String moduleNameDir = moduleName.replaceAll("\\.", "/" ); //文件路径 String outputPath = properties.getProperty(OUTPUT_PATH); File file = new File(outputPath); String path = file.getAbsolutePath(); FileOutConfig dtoFileConfig = new FileOutConfig("/template/myDto" + JAVA_VM_SUFFIX) { /** * 输出文件 * * @param tableInfo */ @Override public String outputFile(TableInfo tableInfo) { return path + "/src/main/java/" + mpg.getPackageInfo().getParent().replaceAll("\\.", "/" ) + "/" + dtoPackageStatic.replaceAll("\\.", "/" ) + ("/" + moduleNameDir) + "/" + tableInfo.getEntityName().substring(0, tableInfo.getEntityName().length() - 2) + "DTO.java"; } }; String isDtoGenerate = properties.getProperty("output.isGeneratePackage.dto" ); if (StringUtils.isNullOrEmpty(isDtoGenerate) || isDtoGenerate.equals("true" )) { fileOutConfigs.add(dtoFileConfig); } } private static void setControllerTestConfig(Properties properties, List<FileOutConfig> fileOutConfigs, AutoGenerator mpg) { String controllerTestPackage = properties.getProperty("output.defineChildPackage.controllerTest" ); final String controllerTestPackageStatic = controllerTestPackage == null ? "controller" : controllerTestPackage; String moduleName = properties.getProperty(OUTPUT_MODULE_NAME); String moduleNameDir = moduleName.replaceAll("\\.", "/" ); //文件路径 String outputPath = properties.getProperty(OUTPUT_PATH); File file = new File(outputPath); String path = file.getAbsolutePath(); FileOutConfig controllerTestFileConfig = new FileOutConfig("/template/myControllerTest" + JAVA_VM_SUFFIX) { /** * 输出文件 * * @param tableInfo */ @Override public String outputFile(TableInfo tableInfo) { return path + "/src/test/java/" + mpg.getPackageInfo().getParent().replaceAll("\\.", "/" ) + "/" + controllerTestPackageStatic.replaceAll("\\.", "/" ) + ("/" + moduleNameDir) + "/" + tableInfo .getControllerName () + "Test.java"; } }; String isControllerTestGenerate = properties.getProperty("output.isGeneratePackage.controllerTest" ); if (StringUtils.isNullOrEmpty(isControllerTestGenerate) || isControllerTestGenerate.equals("true" )) { fileOutConfigs.add(controllerTestFileConfig); } } private static void setServiceTestConfig(Properties properties, List<FileOutConfig> fileOutConfigs, AutoGenerator mpg) { String serviceTestPackage = properties.getProperty("output.defineChildPackage.serviceTest" ); final String serviceTestPackageStatic = serviceTestPackage == null ? "service" : serviceTestPackage; String moduleName = properties.getProperty(OUTPUT_MODULE_NAME); String moduleNameDir = moduleName.replaceAll("\\.", "/" ); //文件路径 String outputPath = properties.getProperty(OUTPUT_PATH); File file = new File(outputPath); String path = file.getAbsolutePath(); FileOutConfig serviceImplTestFileConfig = new FileOutConfig("/template/myServiceImplTest" + JAVA_VM_SUFFIX) { /** * 输出文件 * * @param tableInfo */ @Override public String outputFile(TableInfo tableInfo) { return path + "/src/test/java/" + mpg.getPackageInfo().getParent().replaceAll("\\.", "/" ) + "/" + serviceTestPackageStatic.replaceAll("\\.", "/" ) + ("/" + moduleNameDir) + "/" + tableInfo.getServiceImplName() + "Test.java"; } }; String isServiceTestGenerate = properties.getProperty("output.isGeneratePackage.serviceTest" ); if (StringUtils.isNullOrEmpty(isServiceTestGenerate) || isServiceTestGenerate.equals("true" )) { fileOutConfigs.add(serviceImplTestFileConfig); } } public static void main(String[] args) { generate(); } }
39.165725
233
0.671683
417ccc8ef119302fdcbb71b4b4be01a53c92b4ff
2,441
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on 12.05.2004 * @author Andreas Prlic * */ package org.biojava.bio.program.das.dasalignment ; import java.io.IOException; /** * A DAS client that connects to a DAS aligmnent service and * returns a Biojava Alignment object. */ public class DASAlignmentClient { String query ; String serverurl ; /** * Constructs a DASAlignmentClient object. */ public DASAlignmentClient() { query = null; serverurl = "http://127.0.0.1:8080/dazzle/myalig/alignment?query="; } /** * Constructs a DASAlignmentClient object. * * @param url a String ... */ public DASAlignmentClient(String url) { serverurl = url ; query = null ; } /** * Specifies the query. * * @param q a String specifying the query value * * @see #getQuery */ public void setQuery(String q) { query = q ; } /** * Returns the query. * * @return a String representing the query value * * @see #setQuery */ public String getQuery() { return query ; } /** * Returns the alignments. * * @param query_ a String * @return an array of Alignment objects * @throws IOException ... */ public Alignment[] getAlignments(String query_) throws IOException { query = query_ ; return getAlignments() ; } /** * Returns the alignments. * * @return an array of Alignment objects * @throws IOException ... */ public Alignment[] getAlignments() throws IOException { if (query == null) { throw new IOException ("no query specified - call setQuery() first!"); } DASAlignmentCall alicall = new DASAlignmentCall(serverurl); Alignment[] ali = alicall.getAlignments(query); return ali ; } }
20.512605
75
0.610815
bf60e3faf241ffbc1a2f99874e26f21b2df9d25a
2,049
package com.penglecode.xmodule.examples.springboot.dal.model; import com.penglecode.xmodule.common.support.BaseDO; /** * @author pengpeng * @version 1.0 * @since 2021/5/16 16:19 */ public class Product implements BaseDO { private Long productId; private String productName; private Double unitPrice; private String productUrl; private Integer inventory; private String createTime; private String updateTime; public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Double getUnitPrice() { return unitPrice; } public void setUnitPrice(Double unitPrice) { this.unitPrice = unitPrice; } public String getProductUrl() { return productUrl; } public void setProductUrl(String productUrl) { this.productUrl = productUrl; } public Integer getInventory() { return inventory; } public void setInventory(Integer inventory) { this.inventory = inventory; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "{" + "productId=" + productId + ", productName='" + productName + '\'' + ", unitPrice=" + unitPrice + ", productUrl='" + productUrl + '\'' + ", inventory=" + inventory + ", createTime='" + createTime + '\'' + ", updateTime='" + updateTime + '\'' + '}'; } }
21.34375
61
0.591996
1c0dc3915bd6cdc16e8fee3e08d8a38afe573d4e
926
package com.killrvideo.messaging.utils; import killrvideo.common.CommonEvents; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.killrvideo.messaging.utils.MessagingUtils.mapCustomError; import static com.killrvideo.messaging.utils.MessagingUtils.mapError; import static org.junit.jupiter.api.Assertions.*; class MessagingUtilsTest { private static final Logger LOGGER = LoggerFactory.getLogger(MessagingUtils.class); @Test public void testMapError() { Throwable t = new RuntimeException("Something bad happened."); CommonEvents.ErrorEvent event = mapError(t); assertNotNull(event); LOGGER.info(event.toString()); } @Test public void testMapCustomError() { CommonEvents.ErrorEvent event = mapCustomError("Custom error"); assertNotNull(event); LOGGER.info(event.toString()); } }
31.931034
87
0.736501
99868b4b02cdcdc8a88051f8f0dab375f481ce90
310
/** * @author Martin Macko <https://github.com/LinkedList> */ @XmlSchema( namespace = "http://s3.amazonaws.com/doc/2006-03-01/", elementFormDefault = XmlNsForm.QUALIFIED ) package cz.linkedlist.http.xml; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema;
28.181818
62
0.722581
efebc58310eb5d87e3edf1e7b9162819c4bc8743
1,657
package org.enricogiurin.codingchallenges.codeforces.old.c1243; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class CharacterSwap_Easy extends PrintWriter { //this trick improves performances CharacterSwap_Easy() { super(System.out); } public static void main(String[] $) { CharacterSwap_Easy o = new CharacterSwap_Easy(); o.main(); o.flush(); } void main() { Scanner sc = new Scanner(System.in); int count = sc.nextInt(); //use this if just a single test //int count = 1; test: while (count-- > 0) { final int n = sc.nextInt(); final char[] s = sc.next().toCharArray(); final char[] t = sc.next().toCharArray(); if (Arrays.equals(s, t)) { println("yes"); continue test; } char c1S = '!', c2T = '!'; int i1 = 0, i2 = 0; for (int i = 0; i < n; i++) { if (s[i] == t[i]) { continue; } if (c1S == '!') { c1S = s[i]; i1 = i; } else if (c2T == '!') { c2T = t[i]; i2 = i; } else { println("no"); continue test; } } s[i1] = c2T; t[i2] = c1S; if (Arrays.equals(s, t)) { println("yes"); } else { println("no"); } } sc.close(); } }
27.163934
63
0.405552
d76c094851123394a2c967a0b9aa4aaf020be90d
16,868
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ /** * Connection Manager provides south-bound connectivity services. * The APIs are currently focused towards Active-Active Clustering support * wherein the node can connect to any of the Active Controller in the Cluster. * This component can also host the necessary logic for south-bound connectivity * when partial cluster is identified during Partition scenarios. * * But this (and its corresponding implementation) component can also be used for * basic connectivity mechansims for various south-bound plugins. */ package org.opendaylight.controller.connectionmanager.internal; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingQueue; import org.eclipse.osgi.framework.console.CommandInterpreter; import org.eclipse.osgi.framework.console.CommandProvider; import org.opendaylight.controller.clustering.services.ICacheUpdateAware; import org.opendaylight.controller.clustering.services.IClusterGlobalServices; import org.opendaylight.controller.clustering.services.ICoordinatorChangeAware; import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; import org.opendaylight.controller.connectionmanager.IConnectionManager; import org.opendaylight.controller.connectionmanager.scheme.AbstractScheme; import org.opendaylight.controller.connectionmanager.scheme.SchemeFactory; import org.opendaylight.controller.sal.connection.ConnectionConstants; import org.opendaylight.controller.sal.connection.ConnectionLocality; import org.opendaylight.controller.sal.connection.IConnectionListener; import org.opendaylight.controller.sal.connection.IConnectionService; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.core.Property; import org.opendaylight.controller.sal.core.UpdateType; import org.opendaylight.controller.sal.inventory.IInventoryService; import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; import org.opendaylight.controller.sal.utils.Status; import org.opendaylight.controller.sal.utils.StatusCode; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConnectionManager implements IConnectionManager, IConnectionListener, ICoordinatorChangeAware, IListenInventoryUpdates, ICacheUpdateAware<Node, Set<InetAddress>>, CommandProvider { private static final Logger logger = LoggerFactory .getLogger(ConnectionManager.class); private ConnectionMgmtScheme activeScheme = ConnectionMgmtScheme.ANY_CONTROLLER_ONE_MASTER; private IClusterGlobalServices clusterServices; private ConcurrentMap<ConnectionMgmtScheme, AbstractScheme> schemes; private IConnectionService connectionService; private Thread connectionEventThread; private BlockingQueue<ConnectionMgmtEvent> connectionEvents; private IInventoryService inventoryService; public void setClusterServices(IClusterGlobalServices i) { this.clusterServices = i; } public void unsetClusterServices(IClusterGlobalServices i) { if (this.clusterServices == i) { this.clusterServices = null; } } public void setConnectionService(IConnectionService i) { this.connectionService = i; } public void unsetConnectionService(IConnectionService i) { if (this.connectionService == i) { this.connectionService = null; } } public void setInventoryService(IInventoryService service) { logger.trace("Got inventory service set request {}", service); this.inventoryService = service; } public void unsetInventoryService(IInventoryService service) { logger.trace("Got a service UNset request"); this.inventoryService = null; } private void getInventories() { Map<Node, Map<String, Property>> nodeProp = this.inventoryService .getNodeProps(); for (Map.Entry<Node, Map<String, Property>> entry : nodeProp.entrySet()) { Node node = entry.getKey(); logger.debug("getInventories for node:{}", new Object[] { node }); Map<String, Property> propMap = entry.getValue(); Set<Property> props = new HashSet<Property>(); for (Property property : propMap.values()) { props.add(property); } updateNode(node, UpdateType.ADDED, props); } Map<NodeConnector, Map<String, Property>> nodeConnectorProp = this.inventoryService .getNodeConnectorProps(); for (Map.Entry<NodeConnector, Map<String, Property>> entry : nodeConnectorProp .entrySet()) { Map<String, Property> propMap = entry.getValue(); Set<Property> props = new HashSet<Property>(); for (Property property : propMap.values()) { props.add(property); } updateNodeConnector(entry.getKey(), UpdateType.ADDED, props); } } public void started() { connectionEventThread.start(); registerWithOSGIConsole(); notifyClusterViewChanged(); // Should pull the Inventory updates in case we missed it getInventories(); } public void init() { connectionEventThread = new Thread(new EventHandler(), "ConnectionEvent Thread"); this.connectionEvents = new LinkedBlockingQueue<ConnectionMgmtEvent>(); schemes = new ConcurrentHashMap<ConnectionMgmtScheme, AbstractScheme>(); String schemeStr = System.getProperty("connection.scheme"); for (ConnectionMgmtScheme scheme : ConnectionMgmtScheme.values()) { AbstractScheme schemeImpl = SchemeFactory.getScheme(scheme, clusterServices); if (schemeImpl != null) { schemes.put(scheme, schemeImpl); if (scheme.name().equalsIgnoreCase(schemeStr)) { activeScheme = scheme; } } } } public void stopping() { connectionEventThread.interrupt(); Set<Node> localNodes = getLocalNodes(); if (localNodes != null) { AbstractScheme scheme = schemes.get(activeScheme); for (Node localNode : localNodes) { connectionService.disconnect(localNode); if (scheme != null) scheme.removeNode(localNode); } } } @Override public ConnectionMgmtScheme getActiveScheme() { return activeScheme; } @Override public Set<Node> getNodes(InetAddress controller) { AbstractScheme scheme = schemes.get(activeScheme); if (scheme == null) return null; return scheme.getNodes(controller); } @Override public Set<Node> getLocalNodes() { AbstractScheme scheme = schemes.get(activeScheme); if (scheme == null) return null; return scheme.getNodes(); } @Override public boolean isLocal(Node node) { AbstractScheme scheme = schemes.get(activeScheme); if (scheme == null) return false; return scheme.isLocal(node); } @Override public ConnectionLocality getLocalityStatus(Node node) { AbstractScheme scheme = schemes.get(activeScheme); if (scheme == null) return ConnectionLocality.NOT_CONNECTED; return scheme.getLocalityStatus(node); } @Override public void updateNode(Node node, UpdateType type, Set<Property> props) { logger.debug("updateNode: {} type {} props {}", node, type, props); AbstractScheme scheme = schemes.get(activeScheme); if (scheme == null) return; switch (type) { case ADDED: scheme.addNode(node); break; case REMOVED: scheme.removeNode(node); break; default: break; } } @Override public void updateNodeConnector(NodeConnector nodeConnector, UpdateType type, Set<Property> props) { logger.debug("updateNodeConnector: {} type {} props {}", nodeConnector, type, props); AbstractScheme scheme = schemes.get(activeScheme); if (scheme == null) return; switch (type) { case ADDED: scheme.addNode(nodeConnector.getNode()); break; default: break; } } @Override public void coordinatorChanged() { notifyClusterViewChanged(); } @Override public Node connect(String connectionIdentifier, Map<ConnectionConstants, String> params) { if (connectionService == null) return null; Node node = connectionService.connect(connectionIdentifier, params); AbstractScheme scheme = schemes.get(activeScheme); if (scheme != null && node != null) scheme.addNode(node); return node; } @Override public Node connect(String type, String connectionIdentifier, Map<ConnectionConstants, String> params) { if (connectionService == null) return null; Node node = connectionService.connect(type, connectionIdentifier, params); AbstractScheme scheme = schemes.get(activeScheme); if (scheme != null && node != null) scheme.addNode(node); return node; } @Override public Status disconnect(Node node) { if (node == null) return new Status(StatusCode.BADREQUEST); if (connectionService == null) return new Status(StatusCode.NOSERVICE); Status status = connectionService.disconnect(node); if (status.isSuccess()) { AbstractScheme scheme = schemes.get(activeScheme); if (scheme != null) scheme.removeNode(node); } return status; } @Override public void entryCreated(Node key, String cacheName, boolean originLocal) { if (originLocal) return; } /* * Clustering Services doesn't provide the existing states in the cache * update callbacks. Hence, using a scratch local cache to maintain the * existing state. */ private ConcurrentMap<Node, Set<InetAddress>> existingConnections = new ConcurrentHashMap<Node, Set<InetAddress>>(); @Override public void entryUpdated(Node node, Set<InetAddress> newControllers, String cacheName, boolean originLocal) { if (originLocal) return; Set<InetAddress> existingControllers = existingConnections.get(node); if (existingControllers != null) { logger.debug("Processing Update for : {} NewControllers : {} existingControllers : {}", node, newControllers.toString(), existingControllers.toString()); if (newControllers.size() < existingControllers.size()) { Set<InetAddress> removed = new HashSet<InetAddress>(existingControllers); if (removed.removeAll(newControllers)) { logger.debug("notifyNodeDisconnectFromMaster({})", node); notifyNodeDisconnectedEvent(node); } } } else { logger.debug("Ignoring the Update for : {} NewControllers : {}", node, newControllers.toString()); } existingConnections.put(node, newControllers); } @Override public void entryDeleted(Node key, String cacheName, boolean originLocal) { if (originLocal) return; logger.debug("Deleted entry {} from cache : {}", key, cacheName); notifyNodeDisconnectedEvent(key); } private void enqueueConnectionEvent(ConnectionMgmtEvent event) { try { if (!connectionEvents.contains(event)) { this.connectionEvents.put(event); } } catch (InterruptedException e) { logger.debug( "enqueueConnectionEvent caught Interrupt Exception for event {}", event); } } private void notifyClusterViewChanged() { ConnectionMgmtEvent event = new ConnectionMgmtEvent( ConnectionMgmtEventType.CLUSTER_VIEW_CHANGED, null); enqueueConnectionEvent(event); } private void notifyNodeDisconnectedEvent(Node node) { ConnectionMgmtEvent event = new ConnectionMgmtEvent( ConnectionMgmtEventType.NODE_DISCONNECTED_FROM_MASTER, node); enqueueConnectionEvent(event); } /* * this thread monitors the connectionEvent queue for new incoming events * from */ private class EventHandler implements Runnable { @Override public void run() { while (true) { try { ConnectionMgmtEvent ev = connectionEvents.take(); ConnectionMgmtEventType eType = ev.getEvent(); switch (eType) { case NODE_DISCONNECTED_FROM_MASTER: Node node = (Node) ev.getData(); connectionService.notifyNodeDisconnectFromMaster(node); break; case CLUSTER_VIEW_CHANGED: AbstractScheme scheme = schemes.get(activeScheme); if (scheme == null) return; scheme.handleClusterViewChanged(); connectionService.notifyClusterViewChanged(); break; default: logger.error("Unknown Connection event {}", eType.ordinal()); } } catch (InterruptedException e) { connectionEvents.clear(); return; } } } } private void registerWithOSGIConsole() { BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) .getBundleContext(); bundleContext.registerService(CommandProvider.class.getName(), this, null); } public void _scheme(CommandInterpreter ci) { String schemeStr = ci.nextArgument(); if (schemeStr == null) { ci.println("Please enter valid Scheme name"); ci.println("Current Scheme : " + activeScheme.name()); return; } ConnectionMgmtScheme scheme = ConnectionMgmtScheme.valueOf(schemeStr); if (scheme == null) { ci.println("Please enter a valid Scheme name"); return; } activeScheme = scheme; } public void _printNodes(CommandInterpreter ci) { String controller = ci.nextArgument(); if (controller == null) { ci.println("Nodes connected to this controller : "); if (this.getLocalNodes() == null) { ci.println("None"); } else { ci.println(this.getLocalNodes().toString()); } return; } try { InetAddress address = InetAddress.getByName(controller); ci.println("Nodes connected to controller " + controller); if (this.getNodes(address) == null) { ci.println("None"); } else { ci.println(this.getNodes(address).toString()); } } catch (UnknownHostException e) { logger.error("An error occured", e); } } @Override public String getHelp() { StringBuffer help = new StringBuffer(); help.append("---Connection Manager---\n"); help.append("\t scheme [<name>] - Print / Set scheme\n"); help.append("\t printNodes [<controller>] - Print connected nodes\n"); return help.toString(); } @Override public Set<InetAddress> getControllers(Node node) { AbstractScheme scheme = schemes.get(activeScheme); if (scheme == null) return Collections.emptySet(); return scheme.getControllers(node); } }
37.318584
120
0.63244
f57e3ede0e9f769d7e2ad6fc82c9f0182cb3b717
301
package com.rmaslov.blog.auth.routes; import com.rmaslov.blog.base.routers.BaseApiRoutes; public class AuthRoutes { public static final String ROOT = BaseApiRoutes.V1; public static final String AUTH = ROOT + "/auth"; public static final String REGISTRATION = ROOT + "/registration"; }
27.363636
69
0.744186
1b2beef432e34c66a29829bc9cd826871f55f5b3
6,176
package vl; import org.junit.Before; import org.junit.Test; import vl.algorithms.*; import vl.function.Function; import vl.function.functions.NextFunction; import vl.table.Result; import vl.table.SimpleTable; import vl.table.ValueTable; import java.util.List; import java.util.Map; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; import static org.assertj.core.api.Assertions.assertThat; public class SimpleExpressionTest { private TokenAlgorithm<Integer, String> algorithm; private ValueTable<Integer, String> table; @Before public void before() { algorithm = new ShuntingYard<>(); table = new SimpleTable(); table.addValue(2020, "A", 3.0); // 2020 2021 table.addValue(2020, "B", 4.0); // A 3.0 1.0 table.addValue(2021, "A", 1.0); // B 4.0 2.0 table.addValue(2021, "B", 2.0); } @Test public void return_single_result_for_numbers() { // setup String expressionName = "expression with numbers"; SimpleExpression expression = new SimpleExpression(expressionName, "2 * 3 / ( 2 - 1 ) + 5 * ( 4 - 1 )", algorithm); // action Result<Integer, String> result = expression.calculate(); // verify assertThat(result).isEqualTo(Result.<Integer, String>builder() .name(expressionName) .value(21.0) .build() ); } @Test public void return_single_result_for_expression_with_custom_variables() { // setup String expressionName = "expression with constants"; Map<String, Double> customVariable = newHashMap(); customVariable.put("A", 0.19); SimpleExpression expression = new SimpleExpression(expressionName, "(Pi - 3.14) * A", algorithm); // action Result<Integer, String> result = expression.calculate(customVariable); System.out.println(result); // verify assertThat(result).isEqualTo(Result.<Integer, String>builder() .name(expressionName) .value(3.0260350000001603E-4) .build() ); } @Test public void return_single_result_for_simple_table() { // setup String expressionName = "simple expression"; SimpleExpression expression = new SimpleExpression(expressionName, "2 / (A + B)", algorithm); // action Result<Integer, String> result = expression.calculate(table, 2020); // verify assertThat(result).isEqualTo(Result.<Integer, String>builder() .x(2020) .name(expressionName) .value(0.2857142857142857) .build() ); } @Test public void return_all_x_results_for_simple_table() { // setup String expressionName = "simple expression"; SimpleExpression expression = new SimpleExpression(expressionName, "2 / (A + B)", algorithm); List<Result<Integer, String>> results = newArrayList(); // action table.traverse((x) -> { Result<Integer, String> result = expression.calculate(table, x); results.add(result); }); // verify assertThat(results).containsExactly( Result.<Integer, String>builder() .x(2020) .name(expressionName) .value(0.2857142857142857) .build(), Result.<Integer, String>builder() .x(2021) .name(expressionName) .value(0.6666666666666666) .build() ); } @Test public void return_single_result_for_simple_table_with_custom_variables() { // setup String expressionName = "expression with custom variables"; SimpleExpression expression = new SimpleExpression(expressionName, "(X - A)/B * 0.4", algorithm); Map<String, Double> customVariable = newHashMap(); customVariable.put("X", 12.1); // action Result<Integer, String> result = expression.calculate(table, 2020, customVariable); // verify assertThat(result).isEqualTo(Result.<Integer, String>builder() .x(2020) .name(expressionName) .value(0.91) .build() ); } @Test public void return_all_x_results_for_simple_table_with_functions() { // setup String expressionName = "expression with next function"; Function<Integer, String>[] functions = new Function[]{new NextFunction()}; SimpleExpression expression = new SimpleExpression(expressionName, "A - next(B)", algorithm, functions); List<Result<Integer, String>> results = newArrayList(); // action table.traverse((x) -> { Result<Integer, String> result = expression.calculate(table, x); System.out.println(result); results.add(result); }); // verify assertThat(results).containsExactly( Result.<Integer, String>builder() .x(2020) .name(expressionName) .value(1.0) .build(), Result.<Integer, String>builder() .x(2021) .name(expressionName) .value(null) .build() ); } @Test public void return_single_result_for_constant_variables() { // setup String expressionName = "expression with constants"; SimpleExpression expression = new SimpleExpression(expressionName, "MONTHS_COUNT/Pi", algorithm); // action Result<Integer, String> result = expression.calculate(); System.out.println(result); // verify assertThat(result).isEqualTo(Result.<Integer, String>builder() .name(expressionName) .value(3.819718638570153) .build() ); } }
36.116959
123
0.576263
d405236c9291d398f4a42ea4ad0a4e42488dc83c
2,584
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.annotations; import java.lang.annotation.*; import io.reactivex.schedulers.Schedulers; /** * Indicates what kind of scheduler the class or method uses. * <p> * Constants are provided for instances from {@link Schedulers} as well as values for * {@linkplain #NONE not using a scheduler} and {@linkplain #CUSTOM a manually-specified scheduler}. * Libraries providing their own values should namespace them with their base package name followed * by a colon ({@code :}) and then a human-readable name (e.g., {@code com.example:ui-thread}). */ @Retention(RetentionPolicy.RUNTIME) @Documented @Target({ElementType.METHOD, ElementType.TYPE}) public @interface SchedulerSupport { /** * A special value indicating the operator/class doesn't use schedulers. */ String NONE = "none"; /** * A special value indicating the operator/class requires a scheduler to be manually specified. */ String CUSTOM = "custom"; // Built-in schedulers: /** * The operator/class runs on RxJava's {@linkplain Schedulers#computation() computation * scheduler} or takes timing information from it. */ String COMPUTATION = "io.reactivex:computation"; /** * The operator/class runs on RxJava's {@linkplain Schedulers#io() I/O scheduler} or takes * timing information from it. */ String IO = "io.reactivex:io"; /** * The operator/class runs on RxJava's {@linkplain Schedulers#newThread() new thread scheduler} * or takes timing information from it. */ String NEW_THREAD = "io.reactivex:new-thread"; /** * The operator/class runs on RxJava's {@linkplain Schedulers#trampoline() trampoline scheduler} * or takes timing information from it. */ String TRAMPOLINE = "io.reactivex:trampoline"; /** * The kind of scheduler the class or method uses. * @return the name of the scheduler the class or method uses */ String value(); }
37.449275
112
0.703173
60b777fc2b5716aeb273300737c0e62185a56c32
2,870
package com.mgl.demo.popularpurchases.server.service; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.cache.annotation.CacheDefaults; import javax.cache.annotation.CacheKey; import javax.cache.annotation.CacheResult; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.interceptor.Interceptors; import com.mgl.demo.popularpurchases.dawps.client.DawPurchasesClient; import com.mgl.demo.popularpurchases.dawps.client.ProductNotFoundException; import com.mgl.demo.popularpurchases.dawps.client.UserNotFoundException; import com.mgl.demo.popularpurchases.dawps.client.model.Product; import com.mgl.demo.popularpurchases.dawps.client.model.Purchase; import com.mgl.demo.popularpurchases.dawps.client.model.User; import org.infinispan.jcache.annotation.CacheResultInterceptor; import org.wildfly.swarm.cdi.ConfigValue; @ApplicationScoped @CacheDefaults @Interceptors({CacheResultInterceptor.class}) public class CacheAwareDawPurchasesClient { // A smarter, finer grained caching strategy could be implemented for methods // taking a limit parameter, but because the consumed API does not have "offset" taking // operations, I am sticking to this. // Also please note this is a too straightforward cache because no invalidation // is taking place. This is because this project use case is very simple and there are // no modifying operations happening, nor we have a means to detect that the data // from the consumed API has changed. @Inject @ConfigValue("daw.https") private boolean useHttps; @Inject @ConfigValue("daw.host") private String host; @Inject @ConfigValue("daw.port") private int port; private DawPurchasesClient delegate; @PostConstruct public void init() { delegate = new DawPurchasesClient(useHttps, host, port); } @PreDestroy public void destroy() { delegate.dispose(); } @CacheResult(cacheName = "users", cachedExceptions = {UserNotFoundException.class}) public User getUser(@CacheKey String username) throws UserNotFoundException { return delegate.getUser(username); } @CacheResult(cacheName = "products", cachedExceptions = {ProductNotFoundException.class}) public Product getProduct(@CacheKey long productId) throws ProductNotFoundException { return delegate.getProduct(productId); } @CacheResult(cacheName = "user-purchases") public List<Purchase> getPurchasesByUser(@CacheKey String username, @CacheKey int limit) { return delegate.getPurchasesByUser(username, limit); } @CacheResult(cacheName = "product-purchases") public List<Purchase> getPurchasesByProduct(@CacheKey long productId, @CacheKey int limit) { return delegate.getPurchasesByProduct(productId, limit); } }
38.783784
96
0.768641
cc2d454cbe8d3c6b4db2fdba2ce19b01e1107a45
8,821
package org.sunbird.user.actors; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.sunbird.actor.core.BaseActor; import org.sunbird.actor.router.ActorConfig; import org.sunbird.cassandra.CassandraOperation; import org.sunbird.common.exception.ProjectCommonException; import org.sunbird.common.models.response.Response; import org.sunbird.common.models.util.ActorOperations; import org.sunbird.common.models.util.JsonKey; import org.sunbird.common.models.util.LoggerEnum; import org.sunbird.common.models.util.ProjectLogger; import org.sunbird.common.request.Request; import org.sunbird.common.responsecode.ResponseCode; import org.sunbird.helper.ServiceFactory; import org.sunbird.learner.util.UserUtility; import org.sunbird.learner.util.Util; import org.sunbird.user.service.UserEncryptionService; import org.sunbird.user.service.impl.UserEncryptionServiceImpl; /** Background encrytion and decryption of user sensitive data. */ @ActorConfig( tasks = {}, asyncTasks = {"backgroundEncryption", "backgroundDecryption"} ) public class BackgroundUserDataEncryptionActor extends BaseActor { private CassandraOperation cassandraOperation = ServiceFactory.getInstance(); private UserEncryptionService userEncryptionService = UserEncryptionServiceImpl.getInstance(); private Util.DbInfo usrDbInfo = Util.dbInfoMap.get(JsonKey.USER_DB); private Util.DbInfo addrDbInfo = Util.dbInfoMap.get(JsonKey.ADDRESS_DB); @Override public void onReceive(Request request) throws Throwable { String operation = request.getOperation(); switch (operation) { case "backgroundEncryption": backgroundEncrypt(request); break; case "backgroundDecryption": backgroundDecrypt(request); break; default: onReceiveUnsupportedOperation("BackgroundUserDataEncryptionActor"); break; } } private void backgroundEncrypt(Request request) { List<Map<String, Object>> userDetails = getUserDetails(request); encryptData(userDetails); } private void backgroundDecrypt(Request request) { List<Map<String, Object>> userDetails = getUserDetails(request); decryptData(userDetails); } private void encryptData(List<Map<String, Object>> userDetails) { List<String> userIdsListToSync = new ArrayList<>(); if (CollectionUtils.isEmpty(userDetails)) { ProjectLogger.log( "BackgroundUserDataEncryptionActor:encryptData: Empty user details.", LoggerEnum.INFO); return; } for (Map<String, Object> userMap : userDetails) { List<String> fieldsToEncrypt = userEncryptionService.getDecryptedFields(userMap); if (CollectionUtils.isNotEmpty(fieldsToEncrypt)) { encryptUserDataAndUpdateDB(userMap, fieldsToEncrypt); userIdsListToSync.add((String) userMap.get(JsonKey.ID)); } else { ProjectLogger.log( "BackgroundUserDataEncryptionActor:encryptData: Cannot encrypt data for userId = " + (String) userMap.get(JsonKey.ID), LoggerEnum.INFO); } } ProjectLogger.log( "BackgroundUserDataEncryptionActor:encryptData: Total number of user details to encrypt = " + userIdsListToSync.size(), LoggerEnum.INFO); if (CollectionUtils.isNotEmpty(userIdsListToSync)) { syncToES(userIdsListToSync); } } private void decryptData(List<Map<String, Object>> userDetails) { List<String> userIdsListToSync = new ArrayList<>(); if (CollectionUtils.isEmpty(userDetails)) { ProjectLogger.log( "BackgroundUserDataEncryptionActor:decryptData: Empty user details.", LoggerEnum.INFO); return; } for (Map<String, Object> userMap : userDetails) { List<String> fieldsToDecrypt = userEncryptionService.getEncryptedFields(userMap); if (CollectionUtils.isNotEmpty(fieldsToDecrypt)) { decryptUserDataAndUpdateDB(userMap, fieldsToDecrypt); userIdsListToSync.add((String) userMap.get(JsonKey.ID)); } else { ProjectLogger.log( "BackgroundUserDataEncryptionActor:decryptData: Cannot decrypt data for userId = " + (String) userMap.get(JsonKey.ID), LoggerEnum.INFO); } } ProjectLogger.log( "BackgroundUserDataEncryptionActor:decryptData: Total number of user details to decrypt = " + userIdsListToSync.size(), LoggerEnum.INFO); if (CollectionUtils.isNotEmpty(userIdsListToSync)) { syncToES(userIdsListToSync); } } @SuppressWarnings("unchecked") private List<Map<String, Object>> getUserDetails(Request request) { List<String> userIds = (List<String>) request.getRequest().get(JsonKey.USER_IDs); Response response = cassandraOperation.getRecordsByIdsWithSpecifiedColumns( JsonKey.SUNBIRD, JsonKey.USER, null, userIds); List<Map<String, Object>> userList = (List<Map<String, Object>>) response.get(JsonKey.RESPONSE); if (CollectionUtils.isEmpty(userList)) { ProjectCommonException.throwClientErrorException(ResponseCode.invalidUserId); } return userList; } private void encryptUserDataAndUpdateDB( Map<String, Object> userMap, List<String> fieldsToEncrypt) { try { UserUtility.encryptSpecificUserData(userMap, fieldsToEncrypt); cassandraOperation.updateRecord(usrDbInfo.getKeySpace(), usrDbInfo.getTableName(), userMap); ProjectLogger.log( "BackgroundUserDataEncryptionActor:encryptUserDataAndUpdateDB: Updating user data for userId = " + ((String) userMap.get(JsonKey.ID)) + " is completed", LoggerEnum.INFO); List<Map<String, Object>> addressList = getAddressList((String) userMap.get(JsonKey.ID)); if (CollectionUtils.isNotEmpty(addressList)) { UserUtility.encryptUserAddressData(addressList); updateAddressList(addressList); ProjectLogger.log( "BackgroundUserDataEncryptionActor:encryptUserDataAndUpdateDB: Updating user address data for userId = " + ((String) userMap.get(JsonKey.ID)) + " is completed", LoggerEnum.INFO); } } catch (Exception e) { ProjectLogger.log( "BackgroundUserDataEncryptionActor:encryptUserDataAndUpdateDB: Exception occurred with error message = " + e.getMessage(), e); } } private void decryptUserDataAndUpdateDB( Map<String, Object> userMap, List<String> fieldsToDecrypt) { try { UserUtility.decryptSpecificUserData(userMap, fieldsToDecrypt); cassandraOperation.updateRecord(usrDbInfo.getKeySpace(), usrDbInfo.getTableName(), userMap); ProjectLogger.log( "BackgroundUserDataEncryptionActor:decryptUserDataAndUpdateDB: Updating user data for userId = " + ((String) userMap.get(JsonKey.ID)) + " is completed", LoggerEnum.INFO); List<Map<String, Object>> addressList = getAddressList((String) userMap.get(JsonKey.ID)); if (CollectionUtils.isNotEmpty(addressList)) { UserUtility.decryptUserAddressData(addressList); updateAddressList(addressList); ProjectLogger.log( "BackgroundUserDataEncryptionActor:decryptUserDataAndUpdateDB: Updating user address data for userId = " + ((String) userMap.get(JsonKey.ID)) + " is completed", LoggerEnum.INFO); } } catch (Exception e) { ProjectLogger.log( "BackgroundUserDataEncryptionActor:decryptUserDataAndUpdateDB: Exception occurred with error message = " + e.getMessage(), e); } } @SuppressWarnings("unchecked") private List<Map<String, Object>> getAddressList(String userId) { Response response = cassandraOperation.getRecordsByProperty( addrDbInfo.getKeySpace(), addrDbInfo.getTableName(), JsonKey.USER_ID, userId); return (List<Map<String, Object>>) response.get(JsonKey.RESPONSE); } private void updateAddressList(List<Map<String, Object>> addressList) { for (Map<String, Object> address : addressList) { cassandraOperation.updateRecord(addrDbInfo.getKeySpace(), addrDbInfo.getTableName(), address); } } private void syncToES(List<String> userIds) { Request backgroundSyncRequest = new Request(); backgroundSyncRequest.setOperation(ActorOperations.BACKGROUND_SYNC.getValue()); Map<String, Object> requestMap = new HashMap<>(); requestMap.put(JsonKey.OBJECT_TYPE, JsonKey.USER); requestMap.put(JsonKey.OBJECT_IDS, userIds); backgroundSyncRequest.getRequest().put(JsonKey.DATA, requestMap); tellToAnother(backgroundSyncRequest); } }
40.095455
116
0.709443
bea54de10d2e1439baf46b7b5ae61eccc98cf8fb
1,058
package fi.haagahelia.course.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Data @NoArgsConstructor @EqualsAndHashCode(exclude = {"role","managerProjects","devProjects"}) @ToString(exclude = {"managerProjects","devProjects","role","password"}) public class User { @Id @GeneratedValue @Column(name = "id_user") private Long id; @Column(name = "Firstname") private String firstName; @Column(name = "Lastname") private String lastName; @Column(name = "Email") private String email; @Column(name = "Password") private String password; @ManyToOne @JoinColumn(name = "id_role") private Role role; @JsonIgnore @OneToMany(mappedBy = "manager",fetch = FetchType.LAZY) private Set<Project> managerProjects = new HashSet<Project>(); @JsonIgnore @ManyToMany(fetch = FetchType.LAZY, mappedBy = "developers") private Set<Project> devProjects = new HashSet<Project>(); }
27.128205
72
0.700378
694733c7574c24f5cbe05fbb21b4987d75ff1b29
763
package aqua.recommend; import java.io.File; import java.io.IOException; import java.io.OutputStream; public class TmpFile implements AutoCloseable { public File targetFile, tmpFile; public OutputStream handle; public TmpFile(String targetFile, String tmpFile, OutputStream handle) { this.targetFile = new File(targetFile); this.tmpFile = new File(tmpFile); this.handle = handle; } @Override public void close() throws IOException { if (handle != null) discard(); } public void discard() throws IOException { handle.close(); tmpFile.delete(); } public void commit() throws IOException { handle.close(); tmpFile.renameTo(targetFile); } }
23.121212
76
0.646134
aeab20ca84f0d18cafefcc1e9b6625393fbbb46d
776
package xyz.kwin.yapi.parsers; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import xyz.kwin.yapi.entity.node.InterfaceNode; import java.util.List; /** * 接口解析 * * @author kwin * @since 2021/12/28 2:58 下午 */ public interface InterfaceParser { /** * 获取类下所有接口节点 * * @param pattern 解析规则 * @param psiClass 对应控制器类 * @param psiMethods 对应方法列表 * @return 控制器下所有接口节点 */ List<InterfaceNode> getInterfaces(String pattern, PsiClass psiClass, PsiMethod[] psiMethods); /** * 获取指定接口节点 * * @param pattern 解析规则 * @param psiClass 对应控制器类 * @param psiMethod 对应接口方法 * @return 对应接口节点 */ InterfaceNode getInterface(String pattern, PsiClass psiClass, PsiMethod psiMethod); }
20.972973
97
0.655928
7baf0a37639cf60aa3b9adb76c7e97506c65ae7e
3,321
package com.nander.virtual.store.repository; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.nander.virtual.store.dao.CategoryDAO; import com.nander.virtual.store.dao.ProductDAO; public class CategoryRepository { private Connection connection; public CategoryRepository(Connection connection) { this.connection = connection; } public void save(CategoryDAO category) throws SQLException { String query = "INSERT INTO CATEGORY (name) VALUES (?)"; System.out.println(query); try (PreparedStatement statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { statement.setString(1, category.getName()); statement.execute(); try (ResultSet generatedKeys = statement.getGeneratedKeys()) { while (generatedKeys.next()) { category.setId(generatedKeys.getInt(1)); } } System.out.println(category); } } public List<CategoryDAO> list() throws SQLException { List<CategoryDAO> listCategories = new ArrayList<>(); String query = "SELECT id, name FROM CATEGORY"; System.out.println(query); try(PreparedStatement statement = connection.prepareStatement(query)) { statement.execute(); ResultSet resultSet = statement.getResultSet(); while(resultSet.next()) { Integer id = resultSet.getInt("id"); String name = resultSet.getString("name"); CategoryDAO category = new CategoryDAO(id, name); listCategories.add(category); } listCategories.forEach(category -> { try { System.out.println(category + "\n"); List<ProductDAO> productList = new ProductRepository(this.connection).findByCategory(category); productList.forEach(System.out::println); System.out.println(); } catch (SQLException e) { e.printStackTrace(); } }); } return listCategories; } public List<CategoryDAO> listWithProducts() throws SQLException { List<CategoryDAO> listCategories = new ArrayList<>(); String query = "SELECT c.id, c.name, p.id, p.name, p.description FROM CATEGORY c INNER JOIN PRODUCT p ON p.CATEGORY_ID = c.id"; System.out.println(query); try(PreparedStatement statement = connection.prepareStatement(query)) { statement.execute(); ResultSet resultSet = statement.getResultSet(); while(resultSet.next()) { Integer categoryId = resultSet.getInt(1); String categoryName = resultSet.getString(2); Integer productId = resultSet.getInt(3); String productName = resultSet.getString(4); String productDescription = resultSet.getString(5); CategoryDAO category = new CategoryDAO(categoryId, categoryName); Optional<CategoryDAO> optional = listCategories .stream() .filter(c -> c.getId() == category.getId()) .findFirst(); if(optional.isPresent()) { optional.get().addProduct(new ProductDAO(productId, productName, productDescription));; } else { category.addProduct(new ProductDAO(productId, productName, productDescription)); listCategories.add(category); } } listCategories.forEach(System.out::println); } return listCategories; } }
24.783582
129
0.707919
909d23d0ace2aa646f6efd7f8f7090f1bfeb07f2
11,458
package OneLang.Parsers.Common.Reader; import OneLang.Parsers.Common.Utils.Utils; import OneLang.Parsers.Common.Reader.CursorPositionSearch; import java.util.List; import OneLang.Parsers.Common.Reader.ParseError; import OneLang.Parsers.Common.Reader.IReaderHooks; import OneLang.Parsers.Common.Reader.Cursor; import java.util.regex.Pattern; import java.util.ArrayList; import io.onelang.std.core.Objects; import java.util.stream.Collectors; import java.util.Arrays; import io.onelang.std.core.RegExp; public class Reader { public Integer wsOffset = 0; public Integer offset = 0; public CursorPositionSearch cursorSearch; public String lineComment = "//"; public Boolean supportsBlockComment = true; public String blockCommentStart = "/*"; public String blockCommentEnd = "*/"; public Boolean commentDisabled = false; public String identifierRegex = "[A-Za-z_][A-Za-z0-9_]*"; public String numberRegex = "[+-]?(\\d*\\.\\d+|\\d+\\.\\d+|0x[0-9a-fA-F_]+|0b[01_]+|[0-9_]+)"; public List<ParseError> errors; public IReaderHooks hooks; public Integer wsLineCounter = 0; public Boolean moveWsOffset = true; public Integer prevTokenOffset; public String input; public Boolean getEof() { return this.offset >= this.input.length(); } public Cursor getCursor() { return this.cursorSearch.getCursorForOffset(this.offset); } public String getPreview() { var preview = this.input.substring(this.offset, this.offset + 30).replaceAll("\\n", "\\\\n"); if (preview.length() == 30) preview += "..."; return preview; } public Reader(String input) { this.input = input; this.errors = new ArrayList<ParseError>(); this.hooks = null; this.prevTokenOffset = -1; this.cursorSearch = new CursorPositionSearch(input); } public String linePreview(Cursor cursor) { var line = this.input.substring(cursor.lineStart, cursor.lineEnd - 1); return line + "\n" + " ".repeat(cursor.column - 1) + "^^^"; } public void fail(String message, Integer offset) { var error = new ParseError(message, this.cursorSearch.getCursorForOffset(offset == -1 ? this.offset : offset), this); this.errors.add(error); if (this.hooks != null) this.hooks.errorCallback(error); else throw new Error(message + " at " + error.cursor.line + ":" + error.cursor.column + "\n" + this.linePreview(error.cursor)); } public void skipWhitespace(Boolean includeInTrivia) { for (; this.offset < this.input.length(); this.offset++) { var c = this.input.substring(this.offset, this.offset + 1); if (Objects.equals(c, "\n")) this.wsLineCounter++; if (!(Objects.equals(c, "\n") || Objects.equals(c, "\r") || Objects.equals(c, "\t") || Objects.equals(c, " "))) break; } if (!includeInTrivia) this.wsOffset = this.offset; } public Boolean skipUntil(String token) { var index = this.input.indexOf(token, this.offset); if (index == -1) return false; this.offset = index + token.length(); if (this.moveWsOffset) this.wsOffset = this.offset; return true; } public String readUntil(String token, Boolean orToEnd) { var index = this.input.indexOf(token, this.offset); if (index == -1) { if (!orToEnd) return null; var result = this.input.substring(this.offset); this.wsOffset = this.offset = this.input.length(); return result; } else { var result = this.input.substring(this.offset, index); this.wsOffset = this.offset = index; return result; } } public void skipLine() { if (!this.skipUntil("\n")) this.offset = this.input.length(); } public Boolean isAlphaNum(String c) { var n = (int)c.charAt(0); return (97 <= n && n <= 122) || (65 <= n && n <= 90) || (48 <= n && n <= 57) || n == 95; } public Boolean readExactly(String what) { if (this.input.startsWith(what, this.offset)) { this.wsOffset = this.offset = this.offset + what.length(); return true; } return false; } public Boolean peekExactly(String what) { return this.input.startsWith(what, this.offset); } public String readChar() { // TODO: should we move wsOffset? this.offset++; return this.input.substring(this.offset - 1, this.offset - 1 + 1); } public Boolean peekToken(String token) { this.skipWhitespaceAndComment(); if (this.input.startsWith(token, this.offset)) { // TODO: hackish way to make sure space comes after word tokens if (this.isAlphaNum(token.substring(token.length() - 1, token.length() - 1 + 1)) && this.isAlphaNum(this.input.substring(this.offset + token.length(), this.offset + token.length() + 1))) return false; return true; } else return false; } public Boolean readToken(String token) { if (this.peekToken(token)) { this.prevTokenOffset = this.offset; this.wsOffset = this.offset = this.offset + token.length(); return true; } return false; } public String readAnyOf(String[] tokens) { for (var token : tokens) { if (this.readToken(token)) return token; } return null; } public void expectToken(String token, String errorMsg) { if (!this.readToken(token)) { var result = errorMsg; this.fail((result != null ? (result) : ("expected token '" + token + "'")), -1); } } public String expectString(String errorMsg) { var result = this.readString(); if (result == null) { var result2 = errorMsg; this.fail((result2 != null ? (result2) : ("expected string")), -1); } return result; } public String expectOneOf(String[] tokens) { var result = this.readAnyOf(tokens); if (result == null) this.fail("expected one of the following tokens: " + Arrays.stream(tokens).collect(Collectors.joining(", ")), -1); return result; } public static String[] matchFromIndex(String pattern, String input, Integer offset) { var regex = new RegExp(pattern, "gy"); regex.lastIndex = offset; var matches = regex.exec(input); if (matches == null) return null; else { var result = new ArrayList<String>(); for (Integer i = 0; i < matches.length; i++) result.add(matches[i]); return result.toArray(String[]::new); } } public String[] peekRegex(String pattern) { var matches = Reader.matchFromIndex(pattern, this.input, this.offset); return matches; } public String[] readRegex(String pattern) { var matches = Reader.matchFromIndex(pattern, this.input, this.offset); if (matches != null) { this.prevTokenOffset = this.offset; this.wsOffset = this.offset = this.offset + matches[0].length(); } return matches; } public void skipWhitespaceAndComment() { if (this.commentDisabled) return; this.moveWsOffset = false; while (true) { this.skipWhitespace(true); if (this.input.startsWith(this.lineComment, this.offset)) this.skipLine(); else if (this.supportsBlockComment && this.input.startsWith(this.blockCommentStart, this.offset)) { if (!this.skipUntil(this.blockCommentEnd)) this.fail("block comment end (\"" + this.blockCommentEnd + "\") was not found", -1); } else break; } this.moveWsOffset = true; } public String readLeadingTrivia() { this.skipWhitespaceAndComment(); var thisLineStart = this.input.lastIndexOf("\n", this.offset); if (thisLineStart <= this.wsOffset) return ""; var result = this.input.substring(this.wsOffset, thisLineStart + 1); result = Utils.deindent(result); this.wsOffset = thisLineStart; return result; } public String readIdentifier() { this.skipWhitespace(false); var idMatch = this.readRegex(this.identifierRegex); if (idMatch == null) return null; return idMatch[0]; } public String readNumber() { this.skipWhitespace(false); var numMatch = this.readRegex(this.numberRegex); if (numMatch == null) return null; if (this.readRegex("[0-9a-zA-Z]") != null) this.fail("invalid character in number", -1); return numMatch[0]; } public String readString() { this.skipWhitespace(false); var sepChar = this.input.substring(this.offset, this.offset + 1); if (!Objects.equals(sepChar, "'") && !Objects.equals(sepChar, "\"")) return null; var str = ""; this.readExactly(sepChar); while (!this.readExactly(sepChar)) { var chr = this.readChar(); if (Objects.equals(chr, "\\")) { var esc = this.readChar(); if (Objects.equals(esc, "n")) str += "\n"; else if (Objects.equals(esc, "r")) str += "\r"; else if (Objects.equals(esc, "t")) str += "\t"; else if (Objects.equals(esc, "\\")) str += "\\"; else if (Objects.equals(esc, sepChar)) str += sepChar; else this.fail("invalid escape", this.offset - 1); } else { var chrCode = (int)chr.charAt(0); if (!(32 <= chrCode && chrCode <= 126) || Objects.equals(chr, "\\") || Objects.equals(chr, sepChar)) this.fail("not allowed character (code=" + chrCode + ")", this.offset - 1); str += chr; } } return str; } public String expectIdentifier(String errorMsg) { var id = this.readIdentifier(); if (id == null) { var result = errorMsg; this.fail((result != null ? (result) : ("expected identifier")), -1); } return id; } public String[] readModifiers(String[] modifiers) { var result = new ArrayList<String>(); while (true) { var success = false; for (var modifier : modifiers) { if (this.readToken(modifier)) { result.add(modifier); success = true; } } if (!success) break; } return result.toArray(String[]::new); } }
34
198
0.544598
387f3fcca6700d27f11574e2629bac7644e39a02
1,055
package com.chuck.framework.redis_distributed_lock; import org.springframework.data.redis.core.RedisTemplate; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * RedisDistributedLock * 责任人: chenlei * 修改人: chenlei * 创建/修改时间: 2020/6/28 17:32 * Copyright : 2014-2020 深圳令令科技有限公司-版权所有 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RedisDistributedLock { String[] keys() default "";//分布式锁的key,唯一性,格式类似mybatis的参数,例如: #params.id Class<?> redisTemplateBean() default RedisTemplate.class;//redisTemplate实例,最好自己通过@Configration和@Bean提供bean,如果直接用容器的,可能导致报错 String redisKeyPrefix() default "";//key的前缀 String redisKeySuffix() default "";//key的后缀 long lockTime() default 10000L;//锁的时间,到期自动释放,单位毫秒 long waitTime() default 2000L;//等待时间,单位毫秒 int retryCountThreshold() default 1;//重试阈值 String blockingHint() default "当前访问人数较多,请稍后再试!";//阻塞时的提示信息 }
35.166667
127
0.743128
ba45a3691940d72958a8fd7499861d853ed6a767
7,000
/* * Copyright 2019, Digi International Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package usb; /** * Helper class used to store data bytes as a circular buffer. */ public class CircularByteBuffer { // Variables. private byte[] buffer; private int readIndex; private int writeIndex; private boolean empty = true; /** * Instantiates a new {@code CircularByteBuffer} with the given capacity * in bytes. * * @param size Circular byte buffer size in bytes. * * @throws IllegalArgumentException if {@code size < 1}. */ public CircularByteBuffer(int size) { if (size < 1) throw new IllegalArgumentException("Buffer size must be greater than 0."); buffer = new byte[size]; readIndex = 0; writeIndex = 0; } /** * Writes the given amount of bytes to the circular byte buffer. * * @param data Bytes to write. * @param offset Offset inside data where bytes to write start. * @param numBytes Number of bytes to write. * @return The number of bytes actually written. * * @throws IllegalArgumentException if {@code offset < 0} or * if {@code numBytes < 1}. * @throws NullPointerException if {@code data == null}. * * @see #read(byte[], int, int) * @see #skip(int) */ public synchronized int write(byte[] data, int offset, int numBytes) { if (data == null) throw new NullPointerException("Data cannot be null."); if (offset < 0) throw new IllegalArgumentException("Offset cannot be negative."); if (numBytes < 1) throw new IllegalArgumentException("Number of bytes to write must be greater than 0."); // Check if there are enough bytes to write. int availableBytes = data.length - offset; if (numBytes > availableBytes) numBytes = availableBytes; // Check where we should start writing. if (numBytes < buffer.length - getWriteIndex()) { System.arraycopy(data, offset, buffer, getWriteIndex(), numBytes); writeIndex = getWriteIndex() + numBytes; } else { System.arraycopy(data, offset, buffer, getWriteIndex(), buffer.length - getWriteIndex()); System.arraycopy(data, offset + buffer.length-getWriteIndex(), buffer, 0, numBytes - (buffer.length - getWriteIndex())); writeIndex = numBytes - (buffer.length-getWriteIndex()); if (getReadIndex() < getWriteIndex()) readIndex = getWriteIndex(); } // Check if we were able to write all the bytes. if (numBytes > getCapacity()) numBytes = getCapacity(); empty = false; return numBytes; } /** * Reads the given amount of bytes to the given array from the circular byte * buffer. * * @param data Byte buffer to place read bytes in. * @param offset Offset inside data to start placing read bytes in. * @param numBytes Number of bytes to read. * @return The number of bytes actually read. * * @throws IllegalArgumentException if {@code offset < 0} or * if {@code numBytes < 1}. * @throws NullPointerException if {@code data == null}. * * @see #skip(int) * @see #write(byte[], int, int) */ public synchronized int read(byte[] data, int offset, int numBytes) { if (data == null) throw new NullPointerException("Data cannot be null."); if (offset < 0) throw new IllegalArgumentException("Offset cannot be negative."); if (numBytes < 1) throw new IllegalArgumentException("Number of bytes to read must be greater than 0."); // If we are empty, return 0. if (empty) return 0; // If we try to place bytes in an index bigger than buffer index, return 0 read bytes. if (offset >= data.length) return 0; if (data.length - offset < numBytes) return read(data, offset, data.length - offset); if (availableToRead() < numBytes) return read(data, offset, availableToRead()); if (numBytes < buffer.length - getReadIndex()){ System.arraycopy(buffer, getReadIndex(), data, offset, numBytes); readIndex = getReadIndex() + numBytes; } else { System.arraycopy(buffer, getReadIndex(), data, offset, buffer.length - getReadIndex()); System.arraycopy(buffer, 0, data, offset + buffer.length - getReadIndex(), numBytes - (buffer.length - getReadIndex())); readIndex = numBytes-(buffer.length - getReadIndex()); } // If we have read all bytes, set the buffer as empty. if (readIndex == writeIndex) empty = true; return numBytes; } /** * Skips the given number of bytes from the circular byte buffer. * * @param numBytes Number of bytes to skip. * @return The number of bytes actually skipped. * * @throws IllegalArgumentException if {@code numBytes < 1}. * * @see #read(byte[], int, int) * @see #write(byte[], int, int) */ public synchronized int skip(int numBytes) { if (numBytes < 1) throw new IllegalArgumentException("Number of bytes to skip must be greater than 0."); // If we are empty, return 0. if (empty) return 0; if (availableToRead() < numBytes) return skip(availableToRead()); if (numBytes < buffer.length - getReadIndex()) readIndex = getReadIndex() + numBytes; else readIndex = numBytes - (buffer.length - getReadIndex()); // If we have skipped all bytes, set the buffer as empty. if (readIndex == writeIndex) empty = true; return numBytes; } /** * Returns the available number of bytes to read from the byte buffer. * * @return The number of bytes in the buffer available for reading. * * @see #getCapacity() * @see #read(byte[], int, int) */ public int availableToRead() { if (empty) return 0; if (getReadIndex() < getWriteIndex()) return (getWriteIndex() - getReadIndex()); else return (buffer.length - getReadIndex() + getWriteIndex()); } /** * Returns the current read index. * * @return readIndex The current read index. */ private int getReadIndex() { return readIndex; } /** * Returns the current write index. * * @return writeIndex The current write index. */ private int getWriteIndex() { return writeIndex; } /** * Returns the circular byte buffer capacity. * * @return The circular byte buffer capacity. */ public int getCapacity() { return buffer.length; } /** * Clears the circular buffer. */ public void clearBuffer() { empty = true; readIndex = 0; writeIndex = 0; } }
30.042918
123
0.672857
b782f5d0ac35e256af98a4a6871729f95091e1ff
511
package no.unit.nva.publication.exception; import static org.apache.http.HttpStatus.SC_BAD_GATEWAY; import nva.commons.apigateway.exceptions.ApiGatewayException; public class DynamoDBException extends ApiGatewayException { public DynamoDBException(Exception exception) { super(exception); } public DynamoDBException(String message, Exception exception) { super(exception, message); } @Override protected Integer statusCode() { return SC_BAD_GATEWAY; } }
24.333333
67
0.739726
5d726f6f7511d0ff8d95e0a5ae4e82c2e9d1bf30
505
package us.cuatoi.s34j.spring.dto; import com.google.api.client.util.Key; import java.util.ArrayList; import java.util.List; public class BucketsXml extends AbstractXml { @Key("Bucket") private List<BucketXml> bucketList = new ArrayList<>(); public BucketsXml() { super.name = "Buckets"; } public List<BucketXml> getBucketList() { return bucketList; } public void setBucketList(List<BucketXml> bucketList) { this.bucketList = bucketList; } }
20.2
59
0.673267
296e58f807a30502dbd211323fc093fa1d6e9954
15,933
package com.foxety0f.proton.modules.employees.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.apache.commons.collections4.map.HashedMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.RowMapper; import com.foxety0f.proton.common.abstracts.AbstractDAO; import com.foxety0f.proton.common.exceptions.UserAlreadyExistException; import com.foxety0f.proton.common.exceptions.UserNotFound; import com.foxety0f.proton.common.user.UserDetailsProton; import com.foxety0f.proton.modules.ProtonEssences; import com.foxety0f.proton.modules.ProtonModules; import com.foxety0f.proton.modules.employees.domain.AlphaUserInformation; import com.foxety0f.proton.modules.employees.domain.EmployeeTitle; import com.foxety0f.proton.modules.employees.domain.EmployeesGroup; import com.foxety0f.proton.modules.employees.domain.EmployeesInformation; /** * This DAO using for access to core-database from application.properties * <br> Employees Module can : * <br> Create new employeer from exists user into database * <br> Modify employeer active state (Mark active or inactive) * <br> Edit employeer information for exist employees * <br> Create new groups (internal hierarchy of employees) * <br> Create new title (the internal chain of command the hierarchy of the employees) */ public class EmployeesDAO extends AbstractDAO implements IEmployeesDAO { private Logger LOGGER = LoggerFactory.getLogger(EmployeesDAO.class); /** * DAO constructor * @param DataSource dataSource - connect to core-database from application.properties */ public EmployeesDAO(DataSource dataSource) { super(dataSource); } private ProtonModules thisModule = ProtonModules.EMPLOYEES; /** * Create new Employeer from creating users * @param Integer idUser - unique user Id from app_user * @param String login - user login from app_user * @param Integer idGroup - internal hierarchical identificator of employees * @param Integer titleId - the internal chain of command the hierarchy of the employees * @param String pcNumber - employeer PC number * @param String placeNumber - employeer place number (like 3J39) * @param String ipAddress - employeer ID address * @param UserDetailsProton user - using for identify user modify help * @param Date startDate - employeer hired date */ public void setNewEmployee(Integer idUser, String login, Integer idGroup, Integer titleId, String pcNumber, String placeNumber, String ipAddress, UserDetailsProton user, Date startDate) throws UserAlreadyExistException { Map<String, Object> map = new HashedMap<String, Object>(); map.put("idUser", idUser); map.put("login", login); map.put("idGroup", idGroup); map.put("titleId", titleId); map.put("pcNumber", pcNumber); map.put("placeNumber", placeNumber); map.put("ipAddress", ipAddress); Integer cnt = querySource.queryForObject("select count(*) from proton_employees where login = :login", map, Integer.class); if (cnt > 0) { throw new UserAlreadyExistException(login); } querySource.update("insert into proton_employees(login, isActive, id_User, sys_add_tst)" + "values(:login, 1, :idUser, CURRENT_TIMESTAMP)", map); Integer employeeId = querySource.queryForObject("select id_employee from proton_employees where login = :login", map, Integer.class); map.put("employeeId", employeeId); map.put("startDate", startDate == null ? "CURRENT_DATE" : startDate); querySource.update( "insert into proton_employees_attr(id_employee, beg_date, end_date, id_group, id_title, pc_number, ip_address, place, lastRow)" + "values (:employeeId, :startDate, null, :idGroup, :titleId, :pcNumber, :ipAddress, :placeNumber, 1)", map); loggerWithUser(thisModule, map, ProtonEssences.INSERT, user); } /** * Using for change actual status for employeer. Employeer marked as inactive * @param Integer employeeId - internal employee identificator * @param UserDetailsProton user - using for identify user modify help */ public void markEmployeeAsInactive(Integer employeeId, UserDetailsProton user) { Map<String, Integer> map = new HashedMap<String, Integer>(); map.put("employeeId", employeeId); querySource.update("update proton_employees" + "set isActive = 0 " + " where employee_id = :employeeId", map); loggerWithUser(thisModule, map, ProtonEssences.MARK_INACTIVE, user); } /** * Using for change actual status for employeer. Employeer marked as active * @param Integer employeeId - internal employee identificator * @param UserDetailsProton user - using for identify user modify help */ public void markEmployeeAsActive(Integer employeeId, UserDetailsProton user) { Map<String, Object> map = new HashedMap<String, Object>(); map.put("employeeId", employeeId); querySource.update("update proton_employees" + "set isActive = 1" + "where employee_id = :employeeId", map); loggerWithUser(thisModule, map, ProtonEssences.MARK_ACTIVE, user); } /** * Get all employees information (actial and nonactual rows) * @return List<EmployeesInformation> */ public List<EmployeesInformation> getEmployeeInformation() { return querySource.query("select emp.id_employee" + " , emp.login" + " , emp.isActive" + " , emp.id_user" + " , attr.id_group" + " , attr.id_title" + " , attr.pc_number" + " , attr.ip_address" + " , attr.place" + " , attr.lastRow" + " , attr.id_row" + " , attr.beg_date" + " , attr.end_date" + " , tl.name_title" + " , gp.name_group" + ", au.first_name, au.surname from proton_employees emp " + " left join proton_employees_attr attr on emp.id_employee = attr.id_employee" + " left join proton_employee_titles tl on tl.id_title = attr.id_title" + " left join proton_employees_groups gp on gp.id_group = attr.id_group" + " left join app_user au on au.user_id = emp.id_user" + " order by emp.login, attr.beg_date desc", new EmployeesInformationRowMapper()); } private static class EmployeesInformationRowMapper implements RowMapper<EmployeesInformation> { @Override public EmployeesInformation mapRow(ResultSet rs, int rowNum) throws SQLException { EmployeesInformation item = new EmployeesInformation(); item.setIdEmployee(rs.getInt("id_employee")); item.setLogin(rs.getString("login")); item.setIsActive(rs.getInt("isActive") == 1 ? true : false); item.setIdGroup(rs.getInt("id_group")); item.setTitelId(rs.getInt("id_title")); item.setPcNumber(rs.getString("pc_number")); item.setIpAddress(rs.getString("ip_address")); item.setPlaceNumber(rs.getString("place")); item.setIsActualRow(rs.getInt("lastRow") == 1 ? true : false); item.setStartDate(rs.getDate("beg_date")); item.setEndDate(rs.getDate("end_date")); item.setTitelName(rs.getString("name_title")); item.setGroupName(rs.getString("name_group")); item.setIdRow(rs.getInt("id_row")); item.setFirstName(rs.getString("first_name")); item.setSurname(rs.getString("surname")); return item; } } /** * Get all employees internal hierarchy of employees * @return List<EmployeesGroup> */ public List<EmployeesGroup> getEmployeeGroup() { return querySource.query("select * from proton_employees_groups", new EmployeesGroupRowMapper()); } private static class EmployeesGroupRowMapper implements RowMapper<EmployeesGroup> { @Override public EmployeesGroup mapRow(ResultSet rs, int rowNum) throws SQLException { EmployeesGroup item = new EmployeesGroup(); item.setIdGroup(rs.getInt("id_group")); item.setNameGroup(rs.getString("name_group")); item.setDescription(rs.getString("description")); return item; } } /** * Get all employees internal chain of command the hierarchy of the employees * @return List<EmployeesGroup> */ public List<EmployeeTitle> getEmployeeTitles() { return querySource.query("select * from proton_employee_titles", new EmployeeTitleRowMapper()); } private static class EmployeeTitleRowMapper implements RowMapper<EmployeeTitle> { @Override public EmployeeTitle mapRow(ResultSet rs, int rowNum) throws SQLException { EmployeeTitle item = new EmployeeTitle(); item.setTitleId(rs.getInt(1)); item.setTitleName(rs.getString(2)); item.setDescription(rs.getString(3)); return item; } } /** * Get last rows by employeer (actual information) or all rows by employeer by login * @param String login - employee login * @param Boolean lastRow - last row flag (true - only last row, false - all rows) */ public List<EmployeesInformation> getEmployeeInformation(String login, Boolean lastRow) { Map<String, String> map = new HashedMap<String, String>(); map.put("login", login); String whereLR = " and attr.lastRow = 1"; if (!lastRow) { whereLR = ""; } return querySource.query("select emp.id_employee" + " , emp.login" + " , emp.isActive" + " , emp.id_user" + " , attr.id_group" + " , attr.id_title" + " , attr.pc_number" + " , attr.ip_address" + " , attr.place" + " , attr.lastRow" + " , attr.id_row" + " , attr.beg_date" + " , attr.end_date" + " , tl.name_title" + " , gp.name_group" + ", au.first_name, au.surname from proton_employees emp " + " left join proton_employees_attr attr on emp.id_employee = attr.id_employee" + " left join proton_employee_titles tl on tl.id_title = attr.id_title" + " left join proton_employees_groups gp on gp.id_group = attr.id_group" + " left join app_user au on au.user_id = emp.id_user" + " where login = :login " + whereLR + " order by emp.login, attr.beg_date desc", map, new EmployeesInformationRowMapper()); } /** * Get last rows by employeer (actual information) or all rows by employeer by id * @param String login - employee login * @param Boolean lastRow - last row flag (true - only last row, false - all rows) */ public List<EmployeesInformation> getEmployeeInformation(Integer employeeId, Boolean lastRow) { Map<String, Integer> map = new HashedMap<String, Integer>(); map.put("employeeId", employeeId); String whereLR = " and attr.lastRow = 1"; if (!lastRow) { whereLR = ""; } return querySource.query(" select emp.id_employee \r\n" + " , emp.login \r\n" + " , emp.isActive \r\n" + " , emp.id_user\r\n" + " , attr.id_group \r\n" + " , attr.id_title \r\n" + " , attr.pc_number \r\n" + " , attr.ip_address \r\n" + " , attr.place\r\n" + " , attr.lastRow \r\n" + " , attr.id_row \r\n" + " , attr.beg_date \r\n" + " , attr.end_date \r\n" + " , tl.name_title\r\n" + " , gp.name_group \r\n" + " , au.first_name\r\n" + " , au.surname \r\n" + " from proton_employees emp \r\n" + " left join proton_employees_attr attr on emp.id_employee = attr.id_employee\r\n" + " left join proton_employee_titles tl on tl.id_title = attr.id_title\r\n" + " left join proton_employees_groups gp on gp.id_group = attr.id_group\r\n" + " left join app_user au on au.user_id = emp.id_user \r\n" + " where emp.id_employee = :employeeId\r\n" + whereLR + " order by emp.login, attr.beg_date desc", map, new EmployeesInformationRowMapper()); } /** * Update employeer information * @param Integer employeeId - internal unique employee Id * @param String login - user login from app_user * @param Integer idGroup - internal hierarchical identificator of employees * @param Integer titleId - the internal chain of command the hierarchy of the employees * @param String pcNumber - employeer PC number * @param String placeNumber - employeer place number (like 3J39) * @param String ipAddress - employeer ID address * @param Date startDate - start actual information date * @param Date endDate - end actual information date * @param UserDetailsProton user - using for identify user */ public void updateInformation(Integer employeeId, String login, Integer idGroup, Integer titleId, String pcNumber, String placeNumber, String ipAddress, Date startDate, Date endDate, UserDetailsProton user) throws UserNotFound { Map<String, Object> map = new HashedMap<String, Object>(); map.put("id", employeeId); List<EmployeesInformation> emp = getEmployeeInformation(employeeId, true); if (emp.size() == 0) { logException(thisModule, ProtonEssences.EXCEPTION_UPDATE, "User Not Found", login); throw new UserNotFound(login); } map.put("idGroup", idGroup); map.put("idTitle", titleId); map.put("pcNumber", pcNumber); map.put("placeNumber", placeNumber); map.put("ipAddress", ipAddress); map.put("startDate", startDate == null ? new Date() : startDate); map.put("endDate", endDate == null ? startDate : endDate); map.put("id_row", emp.get(0).getIdRow()); querySource.update( "update proton_employees_attr " + " set end_Date = :endDate, lastRow = 0 " + " where id_row = :id_row", map); loggerWithUser(thisModule, map, ProtonEssences.USER_UPDATE, user); querySource.update( "insert into proton_employees_attr(id_employee, beg_date, end_date, id_group, id_title, pc_number, ip_address, place, lastRow)" + "values (:id, :startDate, null, :idGroup, :idTitle, :pcNumber, :ipAddress, :placeNumber, 1)", map); loggerWithUser(thisModule, map, ProtonEssences.INSERT_USER_ATTR, user); } /** * Get all users from database whos not employeer yet * @return List<AlphaUserInformation> */ public List<AlphaUserInformation> getAlphaUsers() { return querySource.query( "select * from app_user where user_id not in(select distinct id_user from proton_employees)", new AlphaUserInformationRowMapper()); } private static class AlphaUserInformationRowMapper implements RowMapper<AlphaUserInformation> { @Override public AlphaUserInformation mapRow(ResultSet rs, int rowNum) throws SQLException { AlphaUserInformation item = new AlphaUserInformation(); item.setLogin(rs.getString("user_name")); item.setFirstName(rs.getString("first_name")); item.setSurname(rs.getString("surname")); item.setUserId(rs.getLong("user_id")); return item; } } /** * Using for create new internal hierarchy of employees * @param String name - name of group * @param String description - description of group * @param UserDetailsProton user - using for identify user */ public void setNewGroup(String name, String description, UserDetailsProton user) { Map<String, String> map = new HashedMap<String, String>(); map.put("name", name); map.put("description", description); querySource.update( "insert into proton_employees_groups(name_group, description) " + " values(:name, :description)", map); loggerWithUser(thisModule, map, ProtonEssences.INSERT, user); } /** * Using for create new internal chain of command the hierarchy of the employees * @param String name - name of group * @param String description - description of group * @param UserDetailsProton user - using for identify user */ public void setNewTitle(String name, String description, UserDetailsProton user) { Map<String, String> map = new HashedMap<String, String>(); map.put("name", name); map.put("description", description); querySource.update( "insert into proton_employee_titles(name_title, description) " + " values(:name, :description)", map); loggerWithUser(thisModule, map, ProtonEssences.INSERT, user); } }
40.853846
132
0.701563
6fa40c25332d6bc4362d1af3cac8268c0b32f9c0
8,194
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2008, 2009, 2010, 2013, 2014, 2016 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.mailclient.imap; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.AbstractSet; import java.io.IOException; /** * IMAP message flags. */ public final class Flags extends AbstractSet<Atom> { private int flagMask; private Set<Atom> otherFlags; private static final int MASK_ANSWERED = 0x01; private static final int MASK_FLAGGED = 0x02; private static final int MASK_DELETED = 0x04; private static final int MASK_SEEN = 0x08; private static final int MASK_DRAFT = 0x10; private static final int MASK_RECENT = 0x20; private static final int MASK_STAR = 0x40; // LIST response flags private static final int MASK_NOSELECT = 0x80; private static final int MASK_MARKED = 0x100; private static final int MASK_UNMARKED = 0x200; private static final int MASK_NOINFERIORS = 0x400; private static final CAtom[] FLAG_ATOMS = { CAtom.F_ANSWERED, CAtom.F_FLAGGED, CAtom.F_DELETED, CAtom.F_SEEN, CAtom.F_DRAFT, CAtom.F_RECENT, CAtom.F_STAR, CAtom.F_NOSELECT, CAtom.F_MARKED, CAtom.F_UNMARKED, CAtom.F_NOINFERIORS }; public static Flags read(ImapInputStream is) throws IOException { Flags flags = new Flags(); is.skipSpaces(); is.skipChar('('); is.skipSpaces(); while (!is.match(')')) { flags.set(is.readFlag()); is.skipSpaces(); } return flags; } public static Flags fromSpec(String spec) throws IOException { Flags flags = new Flags(); for (int i = 0; i < spec.length(); i++) { flags.set(getMask(spec.charAt(i))); } return flags; } private static int getMask(char c) { switch (c) { case 'a': return MASK_ANSWERED; case 'f': return MASK_FLAGGED; case 'd': return MASK_DELETED; case 's': return MASK_SEEN; case 'r': return MASK_RECENT; case 't': return MASK_STAR; case 'x' : return MASK_DRAFT; default: throw new IllegalArgumentException( "Invalid flag spec char '" + c + "'"); } } public Flags() {} public void setAnswered() { set(MASK_ANSWERED); } public void setFlagged() { set(MASK_FLAGGED); } public void setDeleted() { set(MASK_DELETED); } public void setSeen() { set(MASK_SEEN); } public void setDraft() { set(MASK_DRAFT); } public void setRecent() { set(MASK_RECENT); } public void set(String flag) { set(new Atom(flag)); } public void set(Atom flag) { add(flag); } @Override public boolean add(Atom flag) { int mask = getMask(CAtom.get(flag)); if (mask != 0) { boolean b = isSet(mask); set(mask); return b; } if (otherFlags == null) { otherFlags = new HashSet<Atom>(); } return otherFlags.add(flag); } public void unsetAnswered() { unset(MASK_ANSWERED); } public void unsetFlagged() { unset(MASK_FLAGGED); } public void unsetDeleted() { unset(MASK_DELETED); } public void unsetSeen() { unset(MASK_SEEN); } public void unsetDraft() { unset(MASK_DRAFT); } public void unsetRecent() { unset(MASK_RECENT); } public void unset(String flag) { unset(new Atom(flag)); } public void unset(Atom flag) { remove(flag); } @Override public boolean remove(Object obj) { if (!(obj instanceof Atom)) return false; Atom flag = (Atom) obj; int mask = getMask(CAtom.get(flag)); if (mask != 0) { boolean b = !isSet(mask); unset(mask); return b; } return otherFlags.remove(flag); } public boolean isAnswered() { return isSet(MASK_ANSWERED); } public boolean isFlagged() { return isSet(MASK_FLAGGED); } public boolean isDeleted() { return isSet(MASK_DELETED); } public boolean isSeen() { return isSet(MASK_SEEN); } public boolean isDraft() { return isSet(MASK_DRAFT); } public boolean isRecent() { return isSet(MASK_RECENT); } public boolean isStar() { return isSet(MASK_STAR); } public boolean isNoselect() { return isSet(MASK_NOSELECT); } public boolean isMarked() { return isSet(MASK_MARKED); } public boolean isUnmarked() { return isSet(MASK_UNMARKED); } public boolean isNoinferiors() { return isSet(MASK_NOINFERIORS); } public boolean isSet(String flag) { return isSet(new Atom(flag)); } public boolean isSet(Atom flag) { return contains(flag); } @Override public boolean contains(Object obj) { if (!(obj instanceof Atom)) return false; Atom flag = (Atom) obj; int mask = getMask(CAtom.get(flag)); return mask != 0 ? isSet(mask) : otherFlags != null && otherFlags.contains(flag); } @Override public int size() { int size = otherFlags != null ? otherFlags.size() : 0; return size + bitcount(flagMask); } @Override public Iterator<Atom> iterator() { List<Atom> flags = new ArrayList<Atom>(size()); for (CAtom catom : FLAG_ATOMS) { if (isSet(getMask(catom))) { flags.add(catom.atom()); } } if (otherFlags != null) { flags.addAll(otherFlags); } assert flags.size() == size(); return flags.iterator(); } @Override public String toString() { StringBuilder sb = new StringBuilder("("); Iterator<Atom> it = iterator(); if (it.hasNext()) { sb.append(it.next()); while (it.hasNext()) { sb.append(' ').append(it.next()); } } return sb.append(')').toString(); } public void write(ImapOutputStream os) throws IOException { os.write('('); Iterator<Atom> it = iterator(); if (it.hasNext()) { it.next().write(os); while (it.hasNext()) { os.write(' '); it.next().write(os); } } os.write(')'); } private void set(int mask) { flagMask |= mask; } private void unset(int mask) { flagMask &= ~mask; } private boolean isSet(int mask) { return (flagMask & mask) != 0; } private int getMask(CAtom catom) { switch (catom) { case F_ANSWERED: return MASK_ANSWERED; case F_FLAGGED: return MASK_FLAGGED; case F_DELETED: return MASK_DELETED; case F_SEEN: return MASK_SEEN; case F_DRAFT: return MASK_DRAFT; case F_RECENT: return MASK_RECENT; case F_STAR: return MASK_STAR; case F_NOSELECT: return MASK_NOSELECT; default: return 0; } } // MIT HACKMEM Count private static int bitcount(int n) { long tmp = (long) n & 0xffffffffL; tmp = tmp - ((tmp >> 1) & 033333333333L) - ((tmp >> 2) & 011111111111L); return (int) (((tmp + (tmp >> 3)) & 030707070707L) % 63); } }
30.804511
93
0.581157
902c87bc2153b59f4a65d347d793384f209dc44a
158
package pack2; import java.util.List; import pack1.*; public class Usage { int method() { List list = null; MyList myList = null; } }
15.8
29
0.594937
8a7e0fad6d2d27afe7672c2e1e7d8466223d8bc6
872
package com.edu.fiap.catalogprocessing.repository; import com.edu.fiap.catalogprocessing.model.entity.CatalogGenreEntity; import com.edu.fiap.catalogprocessing.model.entity.CatalogKeywordsEntity; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Service; /** * Genre Repository * @author agnaldo.almeida */ @Service public interface CatalogKeywordRepository extends CrudRepository<CatalogKeywordsEntity, Integer> { /** * finds catalog by its genre name * @param keyword genre name to be found * @return catalogs genre entity found */ CatalogKeywordsEntity findByKeywordIgnoreCase(String keyword); /** * finds by catalogs by catalog id * @param catalogId catalog id * @return catalog genre by its id */ CatalogKeywordsEntity findByCatalogId(Integer catalogId); }
30.068966
98
0.760321
ebd7a27ef77d302e2d0267deeae105c25d70795b
1,927
/* * Copyright (c) 2018 Jämes Ménétrey <james@menetrey.me> * * This file is part of the Keystone Java bindings which is released under MIT. * See file LICENSE in the Java bindings folder for full license details. */ package keystone; import keystone.jna.JnaEnum; import java.util.HashMap; import java.util.Map; public enum KeystoneOptionType implements JnaEnum { /** * Choose syntax for input assembly. */ Syntax(1), /** * Set symbol resolver callback. */ SymbolResolver(2); /** * Mapping table to determine an enumeration value based on an integer with a complexity of θ(1). */ private static Map<Integer, KeystoneOptionType> intToEnumMapping = new HashMap<>(); static { // Initializes the mapping table. for (KeystoneOptionType type : KeystoneOptionType.values()) { intToEnumMapping.put(type.value(), type); } } /** * Holds the integer value of the enumeration, that corresponds to the value used in the enumeration in C. */ private final int value; /** * Constructor of the enumeration. * * @param value The integer value, that corresponds to the value used in the enumeration in C. */ KeystoneOptionType(int value) { this.value = value; } /** * Converts an integer value into its corresponding enumeration value. * <p> * The complexity of the conversion is θ(1). * * @param value The integer value. * @return The return value is a value of the enumeration. */ public static KeystoneOptionType fromValue(Integer value) { return intToEnumMapping.get(value); } /** * Retrieves the value of the enumeration, that corresponds to the value used in the enumeration in C. * * @return The return value is an integer value. */ public int value() { return value; } }
26.39726
110
0.644525
ee1821dc6bbe528ab117eb8ad96a61fe6923b520
5,439
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.android.settingslib.graph; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.SparseIntArray; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import com.android.settingslib.R; public class UsageView extends FrameLayout { private final UsageGraph mUsageGraph; private final TextView[] mLabels; private final TextView[] mBottomLabels; public UsageView(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.usage_view, this); mUsageGraph = (UsageGraph) findViewById(R.id.usage_graph); mLabels = new TextView[] { (TextView) findViewById(R.id.label_bottom), (TextView) findViewById(R.id.label_middle), (TextView) findViewById(R.id.label_top), }; mBottomLabels = new TextView[] { (TextView) findViewById(R.id.label_start), (TextView) findViewById(R.id.label_end), }; TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.UsageView, 0, 0); if (a.hasValue(R.styleable.UsageView_sideLabels)) { setSideLabels(a.getTextArray(R.styleable.UsageView_sideLabels)); } if (a.hasValue(R.styleable.UsageView_bottomLabels)) { setBottomLabels(a.getTextArray(R.styleable.UsageView_bottomLabels)); } if (a.hasValue(R.styleable.UsageView_textColor)) { int color = a.getColor(R.styleable.UsageView_textColor, 0); for (TextView v : mLabels) { v.setTextColor(color); } for (TextView v : mBottomLabels) { v.setTextColor(color); } } if (a.hasValue(R.styleable.UsageView_android_gravity)) { int gravity = a.getInt(R.styleable.UsageView_android_gravity, 0); if (gravity == Gravity.END) { LinearLayout layout = (LinearLayout) findViewById(R.id.graph_label_group); LinearLayout labels = (LinearLayout) findViewById(R.id.label_group); // Swap the children order. layout.removeView(labels); layout.addView(labels); // Set gravity. labels.setGravity(Gravity.END); // Swap the bottom label padding LinearLayout bottomLabels = (LinearLayout) findViewById(R.id.bottom_label_group); bottomLabels.setPadding(bottomLabels.getPaddingRight(), bottomLabels.getPaddingTop(), bottomLabels.getPaddingLeft(), bottomLabels.getPaddingBottom()); } else if (gravity != Gravity.START) { throw new IllegalArgumentException("Unsupported gravity " + gravity); } } mUsageGraph.setAccentColor(a.getColor(R.styleable.UsageView_android_colorAccent, 0)); } public void clearPaths() { mUsageGraph.clearPaths(); } public void addPath(SparseIntArray points) { mUsageGraph.addPath(points); } public void configureGraph(int maxX, int maxY, boolean showProjection, boolean projectUp) { mUsageGraph.setMax(maxX, maxY); mUsageGraph.setShowProjection(showProjection, projectUp); } public void setAccentColor(int color) { mUsageGraph.setAccentColor(color); } public void setDividerLoc(int dividerLoc) { mUsageGraph.setDividerLoc(dividerLoc); } public void setDividerColors(int middleColor, int topColor) { mUsageGraph.setDividerColors(middleColor, topColor); } public void setSideLabelWeights(float before, float after) { setWeight(R.id.space1, before); setWeight(R.id.space2, after); } private void setWeight(int id, float weight) { View v = findViewById(id); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) v.getLayoutParams(); params.weight = weight; v.setLayoutParams(params); } public void setSideLabels(CharSequence[] labels) { if (labels.length != mLabels.length) { throw new IllegalArgumentException("Invalid number of labels"); } for (int i = 0; i < mLabels.length; i++) { mLabels[i].setText(labels[i]); } } public void setBottomLabels(CharSequence[] labels) { if (labels.length != mBottomLabels.length) { throw new IllegalArgumentException("Invalid number of labels"); } for (int i = 0; i < mBottomLabels.length; i++) { mBottomLabels[i].setText(labels[i]); } } }
38.574468
101
0.651958
76f28dba6fa1fbf902cbde6759ddc138149cf2f4
1,390
package io.reflectoring.coderadar.graph.analyzer; import io.reflectoring.coderadar.analyzer.domain.Finding; import io.reflectoring.coderadar.graph.Mapper; /** * Findings are mapped to strings in the following format: "1-2-3-4" where 1 is lineStart, 2 is * lineEnd, 3 is charStart and 4 is charEnd. */ public class FindingsMapper implements Mapper<Finding, String> { @Override public Finding mapGraphObject(String findingsString) { Finding domainObject = new Finding(); String[] values = findingsString.split("-"); domainObject.setLineStart(Integer.parseInt(values[0])); domainObject.setLineEnd(Integer.parseInt(values[1])); domainObject.setCharStart(Integer.parseInt(values[2])); domainObject.setCharEnd(Integer.parseInt(values[3])); StringBuilder message = new StringBuilder(); message.append(values[4]).append("-"); for (int i = 5; i < values.length; i++) { message.append(values[i]).append("-"); } message.deleteCharAt(message.length() - 1); domainObject.setMessage(message.toString()); return domainObject; } @Override public String mapDomainObject(Finding domainObject) { return String.format( "%d-%d-%d-%d-%s", domainObject.getLineStart(), domainObject.getLineEnd(), domainObject.getCharStart(), domainObject.getCharEnd(), domainObject.getMessage()); } }
33.902439
95
0.7
1efe866bbf359cd9af09c1ccc0e0be8840f8cfb4
252
package comp3350.go2fit.BuisnessLayer.DatabaseManagers; import comp3350.go2fit.Models.SetGoalModel; /**Set goal interface**/ public interface SetGoalManagerInterface { boolean setGoal(SetGoalModel model); SetGoalModel getGoal(int id); }
22.909091
55
0.781746
4edad33164b33e5b05bf3a69e7b104ed9e4b1a7e
2,534
package oauth; import java.security.Principal; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.nostalgia.UserRepository; import com.nostalgia.persistence.model.User; import io.dropwizard.auth.Auth; @Path("/test/auth/") @Produces(MediaType.TEXT_PLAIN) public class AuthResource { private final UserRepository userRepo; public AuthResource(UserRepository userRepo){ this.userRepo = userRepo; } @RolesAllowed({"ADMIN"}) @GET @Path("admin") public String show(@Auth AccessToken principal) { User matching = userRepo.findOneByOAuthToken(principal.getAccess_token_id().toString()); return "Hello. User '" + matching.getUsername() + "' has admin privileges"; } @PermitAll @POST @Path("profile") public String showForEveryUserPost(@Auth AccessToken principal, String body) { User matching = userRepo.findOneByOAuthToken(principal.getAccess_token_id().toString()); return "Hello. User '" + matching.getUsername() + "' posted wit user privileges. Post body sent: " + body; } @PermitAll @GET @Path("params/profile") public String showForEveryUserGet(@Auth AccessToken principal, @QueryParam("testval") String testVal) { User matching = userRepo.findOneByOAuthToken(principal.getAccess_token_id().toString()); return "Hello. User '" + matching.getUsername() + "' has did a get with privileges, sent query testVal: " + testVal; } @PermitAll @GET @Path("profile") public String showForEveryUserGetEmpty(@Auth AccessToken principal) { User matching = userRepo.findOneByOAuthToken(principal.getAccess_token_id().toString()); return "Hello. User '" + matching.getUsername() + "' has did a get with privileges, empty get."; } @GET @Path("implicit-permitall") public String implicitPermitAllAuthorization(@Auth AccessToken principal) { User matching = userRepo.findOneByOAuthToken(principal.getAccess_token_id().toString()); return "Hello. User '" + matching.getUsername() + "' has user privileges"; } @GET @Path("noauth") public String hello() { return "hello"; } @DenyAll @GET @Path("denied") public String denied() { return "denied"; } }
30.902439
125
0.697711
d2910f3b5b294f5e1407031a582c776a155f3260
1,535
package com.avob.openadr.server.common.vtn.models.ven; import java.util.List; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import com.avob.openadr.server.common.vtn.models.venmarketcontext.VenMarketContext; /** * Ven crud repository * * @author bertrand * */ public interface VenDao extends CrudRepository<Ven, Long>, JpaSpecificationExecutor<Ven> { public Ven findOneByUsername(String username); public Ven findOneByRegistrationId(String registrationId); public List<Ven> findByUsernameInAndVenMarketContextsContains(List<String> username, VenMarketContext marketContext); @Query("select ven from Ven ven join ven.venGroups gr where gr.name = :groupName") public List<Ven> findByVenGroupsName(@Param("groupName") String groupName); @Query("select ven from Ven ven join ven.venGroups gr where gr.name in :groupName") public List<Ven> findByVenGroupsName(@Param("groupName") List<String> groupName); @Query("select ven from Ven ven join ven.venMarketContexts mc where mc.name = :marketContextName") public List<Ven> findByVenMarketContextsName(@Param("marketContextName") String marketContextName); @Query("select ven from Ven ven join ven.venMarketContexts mc where mc.name in :marketContextName") public List<Ven> findByVenMarketContextsName(@Param("marketContextName") List<String> marketContextName); }
38.375
106
0.803909
f4eb1c25554225165e5d7a5826f85860f4e46a5d
750
package com.jvra.ocache.es; import com.jvra.ocache.debug.BuildConfig; /** * Created by Jansel Valentin on 08/21/15. **/ public final class CacheProviders { private static CacheIdiomProvider mDefault; public static void registerDefault( CacheIdiomProvider cacheIdiom ){ boolean manyProvider = false; try{ assert (manyProvider = BuildConfig.ALLOW_MANY_PROVIDERS); }catch( AssertionError e ){ //expected e.printStackTrace(); } if( null != mDefault && !manyProvider ) throw new IllegalStateException("Provider has been set"); mDefault = cacheIdiom; } public static CacheIdiomProvider getDefault(){ return mDefault; } }
22.727273
72
0.641333
dc502bed5a441f8eea55baf0f3301cfba2d41679
5,630
package com.megotechnologies.ecommerce_retronight.loading; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Looper; import com.megotechnologies.ecommerce_retronight.MainActivity; import com.megotechnologies.ecommerce_retronight.db.DbConnection; import com.megotechnologies.ecommerce_retronight.utilities.MLog; public class ThreadCleanCart extends Thread{ String myEmail = null; String myToken = null; String myCountryId = null; String myStateId = null; String myCityId = null; DbConnection dbC; public ThreadCleanCart(String email, String token, String idCountry, String idState, String idCity, DbConnection conn) { // TODO Auto-generated constructor stub myEmail = email; myToken = token; myCountryId = idCountry; myStateId = idState; myCityId = idCity; dbC = conn; } @Override public void run() { // TODO Auto-generated method stub super.run(); MLog.log("Starting Cart thread.. "); Looper.prepare(); Thread t = Thread.currentThread(); String tName = t.getName(); // Get open cart HashMap<String, String> map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CART); map.put(MainActivity.DB_COL_CART_CART_ISOPEN, MainActivity.DB_RECORD_VALUE_CART_OPEN); String _idOpenCart = null; if(dbC.isOpen()) { dbC.isAvailale(); _idOpenCart = dbC.retrieveId(map); } // If open cart exists proceed else show message no item present if(_idOpenCart != null && _idOpenCart.length() > 0) { map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CART_ITEM); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idOpenCart); ArrayList<HashMap<String, String>> recordsItems = null; if(dbC.isOpen()) { dbC.isAvailale(); recordsItems = dbC.retrieveRecords(map); } MLog.log("Checking cart items " + recordsItems.size()); if(recordsItems.size() > 0) { // Compose the json string for requesting the cart information from the API String jsonStr = "[{\"idProject\": \"" + MainActivity.PID + "\", \"email\": \"" + myEmail + "\", \"token\": \"" + myToken + "\", \"idCountry\": \"" + myCountryId + "\", \"idState\": \"" + myStateId + "\", \"idCity\": \"" + myCityId + "\", \"numItems\": \"" + recordsItems.size() + "\", \"items\": ["; for(int i = 0; i < recordsItems.size(); i++) { map = recordsItems.get(i); String idStream = map.get(MainActivity.DB_COL_CART_ITEM_STREAM_SRV_ID); String idItem = map.get(MainActivity.DB_COL_CART_ITEM_SRV_ID); if(i == (recordsItems.size() - 1)) { jsonStr += "{\"stream\": \"" + idStream + "\", \"item\": \"" + idItem + "\"}"; } else { jsonStr += "{\"stream\": \"" + idStream + "\", \"item\": \"" + idItem + "\"},"; } } jsonStr += "]}]"; MLog.log(jsonStr); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(MainActivity.API_CART); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("params", jsonStr)); MLog.log(jsonStr); String responseString = null; try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); responseString = out.toString(); MLog.log(responseString); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(responseString != null) { jsonStr = responseString; if(jsonStr != null && jsonStr.length() > 0) { MLog.log(jsonStr); JSONObject jsonObj; try { jsonObj = new JSONObject(jsonStr); if(jsonObj.getString("result").equals("success")) { // Loop through the items array which has been downloaded via the API String valueStr = jsonObj.getString("value"); JSONArray jsonArr = new JSONArray(valueStr); // First check if both the sizes match, if they dont match some server item may have been removed, cart inconsistent if(jsonArr.length() == recordsItems.size()) { return; } } // Delete the Cart Items map = new HashMap<String, String>(); map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CART_ITEM); map.put(MainActivity.DB_COL_FOREIGN_KEY, _idOpenCart); if(dbC.isOpen()) { dbC.isAvailale(); dbC.deleteRecord(map); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } }
30.106952
304
0.669627
2a129a7ede4fa5cafc6d0d09b8e1a80b790ddb40
5,281
package io.boomerang.service.refactor; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @JsonIgnoreProperties(ignoreUnknown = true) public class ControllerRequestProperties { private boolean includeGlobalProperties = true; @JsonIgnore private Map<String, String> systemProperties = new HashMap<>(); @JsonIgnore private Map<String, String> globalProperties = new HashMap<>(); @JsonIgnore private Map<String, String> teamProperties = new HashMap<>(); @JsonIgnore private Map<String, String> workflowProperties = new HashMap<>(); @JsonIgnore private Map<String, String> taskInputProperties = new HashMap<>(); @JsonIgnore private Map<String, String> reservedProperties = new HashMap<>(); public Map<String, String> getReservedProperties() { return reservedProperties; } public void setReservedProperties(Map<String, String> reservedProperties) { this.reservedProperties = reservedProperties; } public Map<String, String> getTaskInputProperties() { return taskInputProperties; } public void setTaskInputProperties(Map<String, String> taskInputProperties) { this.taskInputProperties = taskInputProperties; } public Map<String, String> getGlobalProperties() { return globalProperties; } public void setGlobalProperties(Map<String, String> globalProperties) { this.globalProperties = globalProperties; } public Map<String, String> getSystemProperties() { return systemProperties; } public void setSystemProperties(Map<String, String> systemProperties) { this.systemProperties = systemProperties; } public Map<String, String> getTeamProperties() { return teamProperties; } public void setTeamProperties(Map<String, String> teamProperties) { this.teamProperties = teamProperties; } public Map<String, String> getWorkflowProperties() { return workflowProperties; } public void setWorkflowProperties(Map<String, String> workflowProperties) { this.workflowProperties = workflowProperties; } @JsonAnyGetter public Map<String, String> getMap(boolean includeScope) { Map<String, String> finalProperties = new TreeMap<>(); if (this.includeGlobalProperties) { copyProperties(globalProperties, finalProperties, "global", includeScope); } copyProperties(teamProperties, finalProperties, "team", includeScope); copyProperties(workflowProperties, finalProperties, "workflow", includeScope); copyStringMap(taskInputProperties, finalProperties, "workflow", includeScope); copyProperties(systemProperties, finalProperties, "system", includeScope); copyProperties( this.getReservedProperties(), finalProperties, null, false); return finalProperties; } public String getLayeredProperty(String key) { Object val = this.getMap(false).get(key); if (val instanceof Boolean) { return String.valueOf(val); } else { return this.getMap(false).get(key); } } private void copyProperties(Map<String, String> source, Map<String, String> target, String prefix, boolean inludeScope) { for (Entry<String, String> entry : source.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value != null) { if (inludeScope) { target.put(prefix + "/" + key, value.toString()); } target.put(key, value.toString()); } } } private void copyStringMap(Map<String, String> source, Map<String, String> target, String prefix, boolean includeScope) { for (Entry<String, String> entry : source.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value != null) { if (includeScope) { target.put(prefix + "/" + key, value.toString()); } target.put(key, value.toString()); } } } @Override public String toString() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); String jsonResult; try { jsonResult = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this); } catch (JsonProcessingException e) { return ""; } return jsonResult; } public boolean isIncludeGlobalProperties() { return includeGlobalProperties; } public void setIncludeGlobalProperties(boolean includeGlobalProperties) { this.includeGlobalProperties = includeGlobalProperties; } public Map<String, String> getMapForKey(String key) { if ("workflow".equals(key)) { return this.getWorkflowProperties(); } else if ("system".equals(key)) { return this.getSystemProperties(); } else if ("team".equals(key)) { return this.getTeamProperties(); } else if ("global".equals(key)) { return this.getGlobalProperties(); } else { return new HashMap<>(); } } }
29.176796
100
0.711797
63df886f0c0dd50caa692d20529d676cbf075046
1,137
package com.epam.brest.service.impl; import com.epam.brest.model.dto.CarDto; import com.epam.brest.service.config.ServiceTestConfig; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(SpringExtension.class) @Import({ServiceTestConfig.class}) @PropertySource({"classpath:sql-car.properties"}) @Transactional class CarDtoServiceImplIT { @Autowired CarDtoServiceImpl carDtoService; @Test public void shouldFindByPrice() { List<CarDto> cars = carDtoService.findByPrice(); assertNotNull(cars); assertTrue(cars.size() > 0); assertTrue(cars.get(0).getPrice().intValue() > 0); } }
32.485714
70
0.784521
cb217bbe4b1f6bd32a1d347309bd4e235907ad6d
3,849
package io.cloudthing.sdk.device.connectivity.mqtt; import io.cloudthing.sdk.device.data.ICloudThingMessage; import org.eclipse.paho.client.mqttv3.*; /** * Created by Krzysztof Drozynski on 17.03.17. */ public class MqttCloudthingClient implements IMqttCloudthingClient { private MqttConnectOptions connectOptions; private IMqttClient client; private MqttTopic topic; private MqttCallback callback; private String defaultTopic; private int qos; private boolean retain = false; MqttCloudthingClient(IMqttClient client, MqttConnectOptions connectOptions) { this.client = client; this.connectOptions = connectOptions; } @Override public void connect() throws MqttException { this.client.connect(this.connectOptions); } @Override public void disconnect() throws MqttException { this.client.disconnect(); } @Override public boolean isConnected() { return this.client.isConnected(); } @Override public void subscribe(String topic) throws MqttException { this.client.subscribe(topic); } @Override public void unsubscribe(String topic) throws MqttException { this.client.unsubscribe(topic); } @Override public void subscribe() throws MqttException { if (defaultTopic == null) { throw new IllegalStateException("Default topic was not set!"); } this.client.subscribe(defaultTopic); } @Override public void unsubscribe() throws MqttException { if (defaultTopic == null) { throw new IllegalStateException("Default topic was not set!"); } this.client.unsubscribe(defaultTopic); } @Override public MqttDeliveryToken publish(String topic, ICloudThingMessage message) throws MqttException { try { return this.client.getTopic(topic).publish(message.toBytes(), qos, retain); } catch (Exception e) { throw new MqttException(e); } } @Override public MqttDeliveryToken publish(String topic, ICloudThingMessage message, int qos) throws MqttException { try { return this.client.getTopic(topic).publish(message.toBytes(), qos, retain); } catch (Exception e) { throw new MqttException(e); } } @Override public MqttDeliveryToken publish(ICloudThingMessage message) throws MqttException { if (topic == null) { throw new IllegalStateException("Default topic was not set!"); } try { return this.topic.publish(message.toBytes(), qos, retain); } catch (Exception e) { throw new MqttException(e); } } @Override public MqttDeliveryToken publish(ICloudThingMessage message, int qos) throws MqttException { if (topic == null) { throw new IllegalStateException("Default topic was not set!"); } try { return this.topic.publish(message.toBytes(), qos, retain); } catch (Exception e) { throw new MqttException(e); } } @Override public MqttCallback getCallback() { return callback; } @Override public void setCallback(MqttCallback callback) { this.callback = callback; this.client.setCallback(callback); } public void setDefaultTopic(String topic) { this.defaultTopic = topic; this.topic = client.getTopic(topic); } public String getDefaultTopic() { return defaultTopic; } public void setQos(int qos) { this.qos = qos; } public int getQos() { return qos; } public boolean isRetain() { return retain; } public void setRetain(boolean retain) { this.retain = retain; } }
26.916084
110
0.63549
24a1d7e9dcab174eb4042d8b7fa150524c8fc061
1,209
package net.sourceforge.barbecue.linear.ean; import net.sourceforge.barbecue.BarcodeException; public class BooklandBarcode extends EAN13Barcode { public BooklandBarcode(String isbn) throws BarcodeException { super(processIsbn(isbn)); } private static String processIsbn(String isbn) throws BarcodeException { // remove any '-' characters, used in ISBN formatting if (isbn.indexOf('-') > -1) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < isbn.length(); i++) { if (isbn.charAt(i) != '-') { sb.append(isbn.charAt(i)); } } isbn = sb.toString(); } // check the length of the value of the ISBN if (isbn.length() != EAN13Barcode.ISBN_SIZE) { throw new BarcodeException("ISBN is an invalid length"); } // trim off the check digit // check digit will be created automaticaly as the size is only 11 return EAN13Barcode.ISBN_NUMBER_SYSTEM + isbn.substring(0, isbn.length() - 1); // check digit will be created automaticaly as the size is only 11 } }
35.558824
161
0.583954
4341a0b2a0fe06976bf222b1ef7f8ff1f65f4120
1,278
package ure.ui.particles; import ure.math.UColor; /** * A hit on an actor. Spray out blood particles too. */ public class ParticleHit extends UParticle { float intensity; UColor bloodColor; public ParticleHit(int _x, int _y, UColor bloodColor, float intensity) { super(_x, _y, 8, UColor.YELLOW, intensity, false,0,0, 0, 0,0); this.intensity = intensity; this.bloodColor = bloodColor; glyphFrames = "X*X*X*+*+... "; } @Override public void animationTick() { super.animationTick(); if (frame() == 1) { int angle = 0; for (int i=0;i<9;i++) { angle += random.i(360/5); float speed = 5f+random.f(4f); float px = speed*(float)Math.cos(Math.toRadians(angle)); float py = speed*(float)Math.sin(Math.toRadians(angle)); area.addParticle(new ParticleBlood(x,y,bloodColor,intensity*2f,px,py)); } } else if (frame() < 6) { area.addParticle(new ParticleStain(x+random.i(3)-1,y+random.i(3)-1,bloodColor,9617, 120,40,0.6f)); } } @Override public int glyphX() { return glyphY(); } public int glyphY() { return random.i(5)-3; } }
27.782609
110
0.555556
3173deb857d532574ae13251b7f3b3ca757a304e
2,395
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.undertow.security.api; /** * Enumeration to indicate the authentication mode in use. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public enum AuthenticationMode { /** * Where the authentication mode is set to pro-active each request on arrival will be passed to the defined authentication * mechanisms to eagerly perform authentication if there is sufficient information available in order to do so. * * A pro-active authentication could be possible for a number of reasons such as already having a SSL connection * established, an identity being cached against the current session or even a browser sending in authentication headers. * * Running in pro-active mode the sending of the challenge to the client is still driven by the constraints defined so this * is not the same as mandating security for all paths. For some mechanisms such as Digest this is a recommended mode as * without it there is a risk that clients are sending in headers with unique nonce counts that go unverified risking that a * malicious client could make use of them. This is also useful for applications that wish to make use of the current * authenticated user if one exists without mandating that authentication occurs. */ PRO_ACTIVE, /** * When running in constraint driven mode the authentication mechanisms are only executed where the constraint that mandates * authentication is triggered, for all other requests no authentication occurs unless requested by the internal APIs which * may be exposed using the Servlet APIs. */ CONSTRAINT_DRIVEN; }
47.9
128
0.745303
9fe2ed75bd52d89feb286f47e8bff72f1f60cee8
292
package sa.gov.moe.etraining.model.json; import com.google.gson.annotations.SerializedName; public class CreateGroupResponse { @SerializedName("id") private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } }
17.176471
50
0.643836
ebddd947b56b63208a6fe2d5caffd3f119703e19
7,965
package com.github.cmput301f21t44.hellohabits.view; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.github.cmput301f21t44.hellohabits.R; import com.github.cmput301f21t44.hellohabits.databinding.ActivityMainBinding; import com.github.cmput301f21t44.hellohabits.firebase.Authentication; import com.github.cmput301f21t44.hellohabits.view.habitevent.CreateEditHabitEventFragment; import com.github.cmput301f21t44.hellohabits.viewmodel.PhotoViewModel; import com.github.cmput301f21t44.hellohabits.viewmodel.PreviousListViewModel; import com.github.cmput301f21t44.hellohabits.viewmodel.ViewModelFactory; public class MainActivity extends AppCompatActivity { private AppBarConfiguration mAppBarConfiguration; private NavController mNavController; private PreviousListViewModel mPreviousListViewModel; private PhotoViewModel mPhotoViewModel; private boolean mFromViewHabit; private ActivityMainBinding mBinding; private Authentication mAuth; private Uri mImageUri; public Uri getImageUri() { return mImageUri; } public void setImageUri(Uri uri) { this.mImageUri = uri; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mImageUri != null) { outState.putString("cameraImageUri", mImageUri.toString()); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.containsKey("cameraImageUri")) { mImageUri = Uri.parse(savedInstanceState.getString("cameraImageUri")); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(mBinding.getRoot()); setSupportActionBar(mBinding.appBarMain.toolbar); mAuth = new Authentication(); ViewModelProvider provider = ViewModelFactory.getProvider(this); mPreviousListViewModel = provider.get(PreviousListViewModel.class); mPhotoViewModel = provider.get(PhotoViewModel.class); mAppBarConfiguration = new AppBarConfiguration.Builder( R.id.TodaysHabitsFragment, R.id.AllHabitsFragment, R.id.FollowersFragment, R.id.FollowingFragment, R.id.AllUsersFragment ) .setOpenableLayout(mBinding.drawerLayout) .build(); mNavController = Navigation .findNavController(this, R.id.nav_host_fragment_content_main); NavigationUI .setupActionBarWithNavController(this, mNavController, mAppBarConfiguration); NavigationUI.setupWithNavController(mBinding.navView, mNavController); mPreviousListViewModel.getFromViewHabit() .observe(this, val -> this.mFromViewHabit = val); requireUser(); } /** * Navigates to login if there is no user */ private void requireUser() { if (mAuth.getCurrentUser() == null) { mNavController.navigate(R.id.LoginFragment); } } /** * Sets the header message in the sidebar * * @param message The message to add in the header */ public void setHeaderMessage(String message) { // no way to do this with data binding :( final TextView helloMessage = mBinding.navView.getHeaderView(0) .findViewById(R.id.hello_message); if (helloMessage == null) return; helloMessage.setText(message.isEmpty() ? "Hello Habits" : message); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CreateEditHabitEventFragment.REQUEST_CODE_CAMERA) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mPhotoViewModel.setTakePhoto(true); } else { Toast.makeText(this, "We have no permission to camera! (T▽T) ...", Toast.LENGTH_SHORT).show(); } } else if (requestCode == CreateEditHabitEventFragment.REQUEST_CODE_GALLERY) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mPhotoViewModel.setChoosePhoto(true); } else { Toast.makeText(this, "We have no permission to gallery! (T▽T) ...", Toast.LENGTH_SHORT).show(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); } public String getImagePath(Uri uri, String selection) { String path = null; Cursor cursor = getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); } cursor.close(); } return path; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_sign_out) { showSignOutDialog(); return true; } return super.onOptionsItemSelected(item); } /** * Navigates up when the user selects option * * @return true or false */ @Override public boolean onSupportNavigateUp() { if (mFromViewHabit) { getOnBackPressedDispatcher().onBackPressed(); mPreviousListViewModel.setFromViewHabit(false); return true; } return NavigationUI.navigateUp(mNavController, mAppBarConfiguration) || super.onSupportNavigateUp(); } /** * Show an AlertDialog when trying to sign out */ private void showSignOutDialog() { new AlertDialog.Builder(this) .setTitle("Sign out") .setMessage("Are you sure you want to sign out?") .setIcon(R.drawable.ic_baseline_warning_24) .setPositiveButton("YES", (dialog, b) -> signOut()) .setNegativeButton("NO", null).show(); } /** * Signs out and restarts MainActivity to clear all LiveData listeners */ private void signOut() { mAuth.signOut(); Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); } }
35.717489
121
0.672191
61ee932861e887e85eadf07d1bb3d92b5b2703b1
8,250
package com.alipay.api.domain; import java.util.Date; import java.util.List; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; /** * 发票详细信息 * * @author auto create * @since 1.0, 2021-09-23 14:18:46 */ public class CompleteVoucherInfo extends AlipayObject { private static final long serialVersionUID = 8436738492191186751L; /** * 防伪码 */ @ApiField("anti_fake_code") private String antiFakeCode; /** * 校验码 */ @ApiField("check_sum") private String checkSum; /** * 开票机器码 */ @ApiField("device_no") private String deviceNo; /** * 板式文件下载地址 */ @ApiField("file_download_url") private String fileDownloadUrl; /** * 板式文件的类型 */ @ApiField("file_type") private String fileType; /** * 发票金额 */ @ApiField("invoice_amount") private Long invoiceAmount; /** * 发票代码 */ @ApiField("invoice_code") private String invoiceCode; /** * 汇总发票详细信息(目前该字段为空) */ @ApiListField("invoice_content_list") @ApiField("invoice_content_info") private List<InvoiceContentInfo> invoiceContentList; /** * 发票日期 */ @ApiField("invoice_date") private Date invoiceDate; /** * 发票类型 0:增值税普通电子发票 1:增值税普通发票 2:增值税专用发票 3:增值税专用电子发票 4:财政电子发票 */ @ApiField("invoice_kind") private Long invoiceKind; /** * 备注 */ @ApiField("invoice_memo") private String invoiceMemo; /** * 发票号码 */ @ApiField("invoice_no") private String invoiceNo; /** * 发票抬头 */ @ApiField("invoice_title") private String invoiceTitle; /** * 发票类型(红、蓝) */ @ApiField("invoice_type") private String invoiceType; /** * 销售方地址 */ @ApiField("payee_address") private String payeeAddress; /** * 销售方银行账号 */ @ApiField("payee_bank_account") private String payeeBankAccount; /** * 销售方银行名称 */ @ApiField("payee_bank_name") private String payeeBankName; /** * 复核人 */ @ApiField("payee_checker") private String payeeChecker; /** * 销售方电话 */ @ApiField("payee_mobile") private String payeeMobile; /** * 销售方名称 */ @ApiField("payee_name") private String payeeName; /** * 开票人 */ @ApiField("payee_operator") private String payeeOperator; /** * 收款人 */ @ApiField("payee_receiver") private String payeeReceiver; /** * 销售方税号 */ @ApiField("payee_register_no") private String payeeRegisterNo; /** * 购买方地址 */ @ApiField("payer_address") private String payerAddress; /** * 购买方银行账号 */ @ApiField("payer_bank_account") private String payerBankAccount; /** * 购买方银行名称 */ @ApiField("payer_bank_name") private String payerBankName; /** * 购买方电话 */ @ApiField("payer_mobile") private String payerMobile; /** * 购买方名称 */ @ApiField("payer_name") private String payerName; /** * 购买方税号 */ @ApiField("payer_register_no") private String payerRegisterNo; /** * 不含税金额 */ @ApiField("sum_price") private Long sumPrice; /** * 合计税额 */ @ApiField("sum_tax") private Long sumTax; public String getAntiFakeCode() { return this.antiFakeCode; } public void setAntiFakeCode(String antiFakeCode) { this.antiFakeCode = antiFakeCode; } public String getCheckSum() { return this.checkSum; } public void setCheckSum(String checkSum) { this.checkSum = checkSum; } public String getDeviceNo() { return this.deviceNo; } public void setDeviceNo(String deviceNo) { this.deviceNo = deviceNo; } public String getFileDownloadUrl() { return this.fileDownloadUrl; } public void setFileDownloadUrl(String fileDownloadUrl) { this.fileDownloadUrl = fileDownloadUrl; } public String getFileType() { return this.fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public Long getInvoiceAmount() { return this.invoiceAmount; } public void setInvoiceAmount(Long invoiceAmount) { this.invoiceAmount = invoiceAmount; } public String getInvoiceCode() { return this.invoiceCode; } public void setInvoiceCode(String invoiceCode) { this.invoiceCode = invoiceCode; } public List<InvoiceContentInfo> getInvoiceContentList() { return this.invoiceContentList; } public void setInvoiceContentList(List<InvoiceContentInfo> invoiceContentList) { this.invoiceContentList = invoiceContentList; } public Date getInvoiceDate() { return this.invoiceDate; } public void setInvoiceDate(Date invoiceDate) { this.invoiceDate = invoiceDate; } public Long getInvoiceKind() { return this.invoiceKind; } public void setInvoiceKind(Long invoiceKind) { this.invoiceKind = invoiceKind; } public String getInvoiceMemo() { return this.invoiceMemo; } public void setInvoiceMemo(String invoiceMemo) { this.invoiceMemo = invoiceMemo; } public String getInvoiceNo() { return this.invoiceNo; } public void setInvoiceNo(String invoiceNo) { this.invoiceNo = invoiceNo; } public String getInvoiceTitle() { return this.invoiceTitle; } public void setInvoiceTitle(String invoiceTitle) { this.invoiceTitle = invoiceTitle; } public String getInvoiceType() { return this.invoiceType; } public void setInvoiceType(String invoiceType) { this.invoiceType = invoiceType; } public String getPayeeAddress() { return this.payeeAddress; } public void setPayeeAddress(String payeeAddress) { this.payeeAddress = payeeAddress; } public String getPayeeBankAccount() { return this.payeeBankAccount; } public void setPayeeBankAccount(String payeeBankAccount) { this.payeeBankAccount = payeeBankAccount; } public String getPayeeBankName() { return this.payeeBankName; } public void setPayeeBankName(String payeeBankName) { this.payeeBankName = payeeBankName; } public String getPayeeChecker() { return this.payeeChecker; } public void setPayeeChecker(String payeeChecker) { this.payeeChecker = payeeChecker; } public String getPayeeMobile() { return this.payeeMobile; } public void setPayeeMobile(String payeeMobile) { this.payeeMobile = payeeMobile; } public String getPayeeName() { return this.payeeName; } public void setPayeeName(String payeeName) { this.payeeName = payeeName; } public String getPayeeOperator() { return this.payeeOperator; } public void setPayeeOperator(String payeeOperator) { this.payeeOperator = payeeOperator; } public String getPayeeReceiver() { return this.payeeReceiver; } public void setPayeeReceiver(String payeeReceiver) { this.payeeReceiver = payeeReceiver; } public String getPayeeRegisterNo() { return this.payeeRegisterNo; } public void setPayeeRegisterNo(String payeeRegisterNo) { this.payeeRegisterNo = payeeRegisterNo; } public String getPayerAddress() { return this.payerAddress; } public void setPayerAddress(String payerAddress) { this.payerAddress = payerAddress; } public String getPayerBankAccount() { return this.payerBankAccount; } public void setPayerBankAccount(String payerBankAccount) { this.payerBankAccount = payerBankAccount; } public String getPayerBankName() { return this.payerBankName; } public void setPayerBankName(String payerBankName) { this.payerBankName = payerBankName; } public String getPayerMobile() { return this.payerMobile; } public void setPayerMobile(String payerMobile) { this.payerMobile = payerMobile; } public String getPayerName() { return this.payerName; } public void setPayerName(String payerName) { this.payerName = payerName; } public String getPayerRegisterNo() { return this.payerRegisterNo; } public void setPayerRegisterNo(String payerRegisterNo) { this.payerRegisterNo = payerRegisterNo; } public Long getSumPrice() { return this.sumPrice; } public void setSumPrice(Long sumPrice) { this.sumPrice = sumPrice; } public Long getSumTax() { return this.sumTax; } public void setSumTax(Long sumTax) { this.sumTax = sumTax; } }
19.411765
82
0.685333
31dea14007d8820e3644042ee6241cb5c8190abe
1,005
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static int birthdayCakeCandles(int n, int[] ar) { if (n == 0) { return 0; } if (n == 1) { return 1; } int height = ar[0]; int candles = 1; for (int i = 1; i < n; i++) { if (height < ar[i]) { height = ar[i]; candles = 1; } else if (height == ar[i]) { candles++; } } return candles; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] ar = new int[n]; for(int ar_i = 0; ar_i < n; ar_i++){ ar[ar_i] = in.nextInt(); } int result = birthdayCakeCandles(n, ar); System.out.println(result); } }
20.9375
53
0.41592
1d76e0882defa1d78f5f7a547accffd1dd1558df
3,835
package com.epi; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; import java.util.List; public class AddOperatorsInString { // @include public static boolean expressionSynthesis(List<Integer> digits, int target) { List<Character> operators = new ArrayList<>(); List<Integer> operands = new ArrayList<>(); return directedExpressionSynthesis(digits, target, 0, 0, operands, operators); } private static boolean directedExpressionSynthesis( List<Integer> digits, int target, int currentTerm, int offset, List<Integer> operands, List<Character> operators) { currentTerm = currentTerm * 10 + digits.get(offset); if (offset == digits.size() - 1) { operands.add(currentTerm); if (evaluate(operands, operators) == target) { // Found a match. // @exclude int operandIdx = 0; System.out.print(operands.get(operandIdx)); for (Character oper : operators) { ++operandIdx; System.out.print(" " + oper + " " + operands.get(operandIdx)); } System.out.println(" = " + target); // @include return true; } operands.remove(operands.size() - 1); return false; } // No operator. if (directedExpressionSynthesis(digits, target, currentTerm, offset + 1, operands, operators)) { return true; } // Tries multiplication operator '*'. operands.add(currentTerm); operators.add('*'); if (directedExpressionSynthesis(digits, target, 0, offset + 1, operands, operators)) { return true; } operators.remove(operators.size() - 1); operands.remove(operands.size() - 1); // Tries addition operator '+'. operands.add(currentTerm); if (target - evaluate(operands, operators) <= remainingInt(digits, offset + 1)) { operators.add('+'); if (directedExpressionSynthesis(digits, target, 0, offset + 1, operands, operators)) { return true; } operators.remove(operators.size() - 1); } operands.remove(operands.size() - 1); return false; } // Calculates the int represented by digits.subList(idx, digits.size()). private static int remainingInt(List<Integer> digits, int idx) { int val = 0; for (int i = idx; i < digits.size(); ++i) { val = val * 10 + digits.get(i); } return val; } private static int evaluate(List<Integer> operands, List<Character> operators) { Deque<Integer> intermediateOperands = new LinkedList<>(); int operandIdx = 0; intermediateOperands.addFirst(operands.get(operandIdx++)); // Evaluates '*' first. for (char oper : operators) { if (oper == '*') { intermediateOperands.addFirst(intermediateOperands.removeFirst() * operands.get(operandIdx++)); } else { intermediateOperands.addFirst(operands.get(operandIdx++)); } } // Evaluates '+' second. int sum = 0; while (!intermediateOperands.isEmpty()) { sum += intermediateOperands.removeFirst(); } return sum; } // @exclude public static void main(String[] args) { List<Integer> A = Arrays.asList(2, 3, 4); int k = 4; assert !expressionSynthesis(A, k); A = Arrays.asList(1, 2, 3, 4); k = 11; assert expressionSynthesis(A, k); A = Arrays.asList(1, 2, 3, 2, 5, 3, 7, 8, 5, 9); k = 995; assert expressionSynthesis(A, k); A = Arrays.asList(5, 2, 3, 4, 1); k = 20; assert expressionSynthesis(A, k); A = Arrays.asList(1, 1, 2, 3); k = 124; assert expressionSynthesis(A, k); } }
31.958333
79
0.589048
cd48fafe3de1b802c1d1451a7690d0908789702a
671
package com.zcprog.springcloud.alibaba.service; import com.zcprog.springcloud.alibaba.domain.CommonResult; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.math.BigDecimal; /** * @Description * @Author zhaochao * @Date 2021/1/18 18:40 * @Email zcprog@foxmail.com * @Version V1.0 */ @FeignClient(value = "seata-account-service") public interface AccountService{ @PostMapping(value = "/account/decrease") public CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money); }
29.173913
111
0.777943
9f8ed643eefb034e2aa4eb30ccc8362c37bb55a7
1,922
/* * $Id: PluginViewPropertyCheckBoxMenuItem.java,v 1.0 18 Apr 2007 12:17:40 Administrator Exp $ * * Copyright (C) 2005, Cladonia Ltd. All rights reserved. * * This software is the proprietary information of Cladonia Ltd. * Use is subject to license terms. */ package com.cladonia.xngreditor.plugins; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Vector; import javax.swing.JCheckBoxMenuItem; import com.cladonia.xngreditor.ExchangerView; /** * * * @version $Revision: 1.0 $, $Date: 18 Apr 2007 12:17:40 $ * @author Thomas Curley <tcurley@cladonia.com> */ public class PluginViewPropertyCheckBoxMenuItem extends JCheckBoxMenuItem implements ItemListener { private PluginView pluginView = null; private String propertyName = null; private String propertyLabel = null; public PluginViewPropertyCheckBoxMenuItem(PluginView view, String propertyName, String propertyLabel) { super(propertyLabel); this.pluginView = view; this.propertyName = propertyName; this.addItemListener(this); if(pluginView.getProperties() != null) { this.setSelected(pluginView.getProperties().getBoolean((propertyName))); } } /* (non-Javadoc) * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent) */ public void itemStateChanged(ItemEvent e) { // properties.getGridProperties().hideContainerTables( gridHideContainerTables.isSelected()); //Vector views = getViews(); //for (int i = 0; i < views.size(); i++) { // ((ExchangerView) views.elementAt(i)).getGrid().updatePreferences(); //} pluginView.getProperties().set(propertyName, this.isSelected()); Vector views = pluginView.getExchangerEditor().getViews(); for (int i = 0; i < views.size(); i++) { ((ExchangerView) views.elementAt(i)).updatePreferences(); } } }
27.855072
105
0.697711
dda34073373999c6e11c524fddcabb6d95fee5d8
8,328
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.security.authc.support.mapper.expressiondsl; import com.carrotsearch.randomizedtesting.WriterOutputStream; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xcontent.ToXContent; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentFactory; import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xpack.core.XPackClientPlugin; import org.elasticsearch.xpack.core.security.authc.support.mapper.expressiondsl.FieldExpression.FieldValue; import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource; import java.io.IOException; import java.io.StringWriter; import java.util.Arrays; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.iterableWithSize; import static org.hamcrest.Matchers.notNullValue; public class ExpressionParserTests extends ESTestCase { public void testParseSimpleFieldExpression() throws Exception { String json = "{ \"field\": { \"username\" : \"*@shield.gov\" } }"; FieldExpression field = checkExpressionType(parse(json), FieldExpression.class); assertThat(field.getField(), equalTo("username")); assertThat(field.getValues(), iterableWithSize(1)); final FieldValue value = field.getValues().get(0); assertThat(value.getValue(), equalTo("*@shield.gov")); assertThat(value.getAutomaton(), notNullValue()); assertThat(value.getAutomaton().run("bob@shield.gov"), equalTo(true)); assertThat(value.getAutomaton().run("bob@example.net"), equalTo(false)); assertThat(json(field), equalTo(json.replaceAll("\\s", ""))); } public void testParseComplexExpression() throws Exception { String json = "{ \"any\": [" + " { \"field\": { \"username\" : \"*@shield.gov\" } }, " + " { \"all\": [" + " { \"field\": { \"username\" : \"/.*\\\\@avengers\\\\.(net|org)/\" } }, " + " { \"field\": { \"groups\" : [ \"admin\", \"operators\" ] } }, " + " { \"except\":" + " { \"field\": { \"groups\" : \"disavowed\" } }" + " }" + " ] }" + "] }"; final RoleMapperExpression expr = parse(json); assertThat(expr, instanceOf(AnyExpression.class)); AnyExpression any = (AnyExpression) expr; assertThat(any.getElements(), iterableWithSize(2)); final FieldExpression fieldShield = checkExpressionType(any.getElements().get(0), FieldExpression.class); assertThat(fieldShield.getField(), equalTo("username")); assertThat(fieldShield.getValues(), iterableWithSize(1)); final FieldValue valueShield = fieldShield.getValues().get(0); assertThat(valueShield.getValue(), equalTo("*@shield.gov")); assertThat(valueShield.getAutomaton(), notNullValue()); assertThat(valueShield.getAutomaton().run("fury@shield.gov"), equalTo(true)); assertThat(valueShield.getAutomaton().run("fury@shield.net"), equalTo(false)); final AllExpression all = checkExpressionType(any.getElements().get(1), AllExpression.class); assertThat(all.getElements(), iterableWithSize(3)); final FieldExpression fieldAvengers = checkExpressionType(all.getElements().get(0), FieldExpression.class); assertThat(fieldAvengers.getField(), equalTo("username")); assertThat(fieldAvengers.getValues(), iterableWithSize(1)); final FieldValue valueAvengers = fieldAvengers.getValues().get(0); assertThat(valueAvengers.getAutomaton().run("stark@avengers.net"), equalTo(true)); assertThat(valueAvengers.getAutomaton().run("romanov@avengers.org"), equalTo(true)); assertThat(valueAvengers.getAutomaton().run("fury@shield.gov"), equalTo(false)); final FieldExpression fieldGroupsAdmin = checkExpressionType(all.getElements().get(1), FieldExpression.class); assertThat(fieldGroupsAdmin.getField(), equalTo("groups")); assertThat(fieldGroupsAdmin.getValues(), iterableWithSize(2)); assertThat(fieldGroupsAdmin.getValues().get(0).getValue(), equalTo("admin")); assertThat(fieldGroupsAdmin.getValues().get(1).getValue(), equalTo("operators")); final ExceptExpression except = checkExpressionType(all.getElements().get(2), ExceptExpression.class); final FieldExpression fieldDisavowed = checkExpressionType(except.getInnerExpression(), FieldExpression.class); assertThat(fieldDisavowed.getField(), equalTo("groups")); assertThat(fieldDisavowed.getValues(), iterableWithSize(1)); assertThat(fieldDisavowed.getValues().get(0).getValue(), equalTo("disavowed")); ExpressionModel hawkeye = new ExpressionModel(); hawkeye.defineField("username", "hawkeye@avengers.org"); hawkeye.defineField("groups", Arrays.asList("operators")); assertThat(expr.match(hawkeye), equalTo(true)); ExpressionModel captain = new ExpressionModel(); captain.defineField("username", "america@avengers.net"); assertThat(expr.match(captain), equalTo(false)); ExpressionModel warmachine = new ExpressionModel(); warmachine.defineField("username", "warmachine@avengers.net"); warmachine.defineField("groups", Arrays.asList("admin", "disavowed")); assertThat(expr.match(warmachine), equalTo(false)); ExpressionModel fury = new ExpressionModel(); fury.defineField("username", "fury@shield.gov"); fury.defineField("groups", Arrays.asList("classified", "directors")); assertThat(expr.asPredicate().test(fury), equalTo(true)); assertThat(json(expr), equalTo(json.replaceAll("\\s", ""))); } public void testWriteAndReadFromStream() throws Exception { String json = "{ \"any\": [" + " { \"field\": { \"username\" : \"*@shield.gov\" } }, " + " { \"all\": [" + " { \"field\": { \"username\" : \"/.*\\\\@avengers\\\\.(net|org)/\" } }, " + " { \"field\": { \"groups\" : [ \"admin\", \"operators\" ] } }, " + " { \"except\":" + " { \"field\": { \"groups\" : \"disavowed\" } }" + " }" + " ] }" + "] }"; final RoleMapperExpression exprSource = parse(json); final BytesStreamOutput out = new BytesStreamOutput(); ExpressionParser.writeExpression(exprSource, out); final Settings settings = Settings.builder().put("path.home", createTempDir()).build(); final NamedWriteableRegistry registry = new NamedWriteableRegistry(new XPackClientPlugin().getNamedWriteables()); final NamedWriteableAwareStreamInput input = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry); final RoleMapperExpression exprResult = ExpressionParser.readExpression(input); assertThat(json(exprResult), equalTo(json.replaceAll("\\s", ""))); } private <T> T checkExpressionType(RoleMapperExpression expr, Class<T> type) { assertThat(expr, instanceOf(type)); return type.cast(expr); } private RoleMapperExpression parse(String json) throws IOException { return new ExpressionParser().parse("rules", new XContentSource(new BytesArray(json), XContentType.JSON)); } private String json(RoleMapperExpression node) throws IOException { final StringWriter writer = new StringWriter(); try (XContentBuilder builder = XContentFactory.jsonBuilder(new WriterOutputStream(writer))) { node.toXContent(builder, ToXContent.EMPTY_PARAMS); } return writer.toString(); } }
52.05
125
0.67219
2633d4e78e8ccf30169ef91bf22694a9270d825b
3,037
package io.seldon.wrapper.api; import com.google.protobuf.InvalidProtocolBufferException; import io.seldon.protos.PredictionProtos.SeldonMessage; import io.seldon.wrapper.exception.APIException; import io.seldon.wrapper.exception.APIException.ApiExceptionType; import io.seldon.wrapper.pb.ProtoBufUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; 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; @RestController @ConditionalOnExpression("${seldon.api.transformer.enabled:false}") public class TransformerRestController { private static Logger logger = LoggerFactory.getLogger(TransformerRestController.class.getName()); @Autowired SeldonPredictionService predictionService; @RequestMapping( value = "/transform-input", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=utf-8") public ResponseEntity<String> transformInput(@RequestParam("json") String json) { SeldonMessage request; try { SeldonMessage.Builder builder = SeldonMessage.newBuilder(); ProtoBufUtils.updateMessageBuilderFromJson(builder, json); request = builder.build(); } catch (InvalidProtocolBufferException e) { logger.error("Bad request", e); throw new APIException(ApiExceptionType.WRAPPER_INVALID_MESSAGE, json); } try { SeldonMessage response = predictionService.transformInput(request); String res = ProtoBufUtils.toJson(response); return new ResponseEntity<String>(res, HttpStatus.OK); } catch (InvalidProtocolBufferException e) { throw new APIException(ApiExceptionType.WRAPPER_INVALID_MESSAGE, ""); } } @RequestMapping( value = "/transform-output", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=utf-8") public ResponseEntity<String> transformOutput(@RequestParam("json") String json) { SeldonMessage request; try { SeldonMessage.Builder builder = SeldonMessage.newBuilder(); ProtoBufUtils.updateMessageBuilderFromJson(builder, json); request = builder.build(); } catch (InvalidProtocolBufferException e) { logger.error("Bad request", e); throw new APIException(ApiExceptionType.WRAPPER_INVALID_MESSAGE, json); } try { SeldonMessage response = predictionService.transformOutput(request); String res = ProtoBufUtils.toJson(response); return new ResponseEntity<String>(res, HttpStatus.OK); } catch (InvalidProtocolBufferException e) { throw new APIException(ApiExceptionType.WRAPPER_INVALID_MESSAGE, ""); } } }
40.493333
100
0.765229
86d088adb1c33ffead7541241e864417d3fb956f
9,677
package com.easymicro.rest.modular.business.wechat; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.easymicro.core.https.HttpsUtil; import com.easymicro.rest.modular.business.wechat.po.WeChatTemplteMsgModel; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.RequestParam; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.*; public class WeChatUtil { public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } private String appid; private String secret; static final String AuditKey = ""; static final String AppointKey = "CHebUlLqLFw0gqYpdH8TR9vgKaSkeG5XzQ7Ni4FfA9o"; static final String code_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"; static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?"; static final String send_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?"; static final String template_send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?"; static final String authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize?"; static final String userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"; Logger logger = Logger.getLogger(WeChatUtil.class); public WeChatUtil(String appid, String secret) { this.appid = appid; this.secret = secret; } public String authorize(String redirect_uri,String state) { String url = authorize_url + "appid=" + appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state="+state+"#wechat_redirect"; return url; } /** * 根据code获得 accessToken * * @param code * @return */ public Map accessTokenByCode(@RequestParam String code) { String url = code_access_token_url + "appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code"; Map<String, String> params = new HashMap<>(); params.put("appid", appid); params.put("secret", secret); params.put("code", code); params.put("grant_type", "authorization_code"); params = HttpsUtil.executePost(url,params,Map.class); System.out.print("accesstoken:" + params); return params; } /** * 获得 accessToken * * @return */ public Map accessToken() { String url = access_token_url + "grant_type=client_credential&appid=" + appid + "&secret=" + secret; Map<String, String> params = new HashMap<>(); params.put("grant_type","client_credential"); params.put("appid", appid); params.put("secret", secret); String resut = HttpsUtil.executePost(url,params,null); logger.info("url = " + url + " resut = " + resut); Map resultMap = JSON.parseObject(resut, Map.class); System.out.print("accesstoken:" + JSONObject.toJSONString(resultMap)); return resultMap; } /** * 拉取用户信息 * @param acesstoken * @param openid * @return */ public Map getuserinfo(String acesstoken, String openid) { String url = String.format(userinfo_url, acesstoken, openid); String resut = HttpsUtil.executePost(url,""); logger.info("url = " + url + " resut = " + resut); Map resultMap = JSON.parseObject(resut, Map.class); System.out.print("accesstoken:" + JSONObject.toJSONString(resultMap)); return resultMap; } public Map gettickt(String token) { Map<String, String> params = new HashMap<>(); params.put("access_token", token); params.put("type", "jsapi"); params = HttpsUtil.executePost("https://api.weixin.qq.com/cgi-bin/ticket/getticket", params, Map.class); logger.info("获取ticket" + params); return params; } /** * 发送消息 * * @param strJson * @return */ public Map sendMsg(String strJson) { Map tempMap = accessToken(); String accessToken = (String) tempMap.get("access_token"); String url = send_url + "access_token=" + accessToken; String resut = HttpsUtil.executePost(url, strJson); logger.info("url = " + url + " resut = " + resut); Map resultMap = JSON.parseObject(resut, Map.class); return resultMap; } /** * 发送模板消息 * * @param openId * @param urlStr * @param empplateId * @param obj * @return */ public Map sendTemplateMsg(String openId, String urlStr, String empplateId, JSONObject obj) { Map tempMap = accessToken(); JSONObject json = new JSONObject(); String touser = openId;//接收者openid     json.put("touser", touser); json.put("template_id", empplateId); json.put("url", urlStr); json.put("data", obj);//模板数据 String accessToken = (String) tempMap.get("access_token"); String url = template_send_url + "access_token=" + accessToken; String resut =HttpsUtil.executePost(url, JSON.toJSONString(json)); logger.info("url = " + url + " resut = " + resut); Map resultMap = JSON.parseObject(resut, Map.class); return resultMap; } /** * 发送模板消息 * * @param openId * @param urlStr * @return */ public Map sendTemplateMsg(String accessToken, String openId, String urlStr, WeChatTemplteMsgModel msgModel , String AppointKey) { logger.info("==================向openid= "+openId+" 发送了消息====================="); JSONObject obj = new JSONObject(); obj.put("first", toJson(msgModel.getFirst())); obj.put("keyword1", toJson(msgModel.getKeyword1())); obj.put("keyword2", toJson(msgModel.getKeyword2())); obj.put("keyword3", toJson(msgModel.getKeyword3())); obj.put("keyword4", toJson(msgModel.getKeyword4())); obj.put("remark", toJson(msgModel.getRmk())); Map tempMap = accessToken(); JSONObject json = new JSONObject(); String touser = openId;//接收者openid     json.put("touser", touser); json.put("template_id", AppointKey); json.put("url", urlStr); json.put("data", obj);//模板数据 String url = template_send_url + "access_token=" + accessToken; String resut = HttpsUtil.executePost(url, JSON.toJSONString(json)); logger.info("推送微信 url = " + url + " resut = " + resut); Map resultMap = JSON.parseObject(resut, Map.class); return resultMap; } public void templateMsg(String openid, String url,WeChatTemplteMsgModel msgModel) { //向用户发送微信消息 // String first = "您好!您有待审核的任务";//标题 // String rmk = "请在2个工作日完成审核";//备注 // String keyword1 = "预约拜访"; // String keyword2 = DateUtil.dateToStringWithTime2(); // String keyword3 = ""; JSONObject json = new JSONObject(); json.put("first", toJson(msgModel.getFirst())); json.put("keyword1", toJson(msgModel.getKeyword1())); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); json.put("keyword2", toJson(sdf.format(new Date()))); json.put("remark", toJson(msgModel.getRmk())); sendTemplateMsg(openid, url, AppointKey, json); } public JSONObject toJson(String value) { JSONObject json = new JSONObject(); json.put("value", value); json.put("color", "#173177");//消息字体颜色 return json; } public Map<String, String> sign(String url) { String token = accessToken().get("access_token").toString(); String jsapi_ticket = gettickt(token).get("ticket").toString(); Map<String, String> ret = new HashMap<String, String>(); String nonce_str = create_nonce_str(); String timestamp = create_timestamp(); String string1; String signature = ""; //注意这里参数名必须全部小写,且必须有序 string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url; // System.out.println(string1); try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(string1.getBytes("UTF-8")); signature = byteToHex(crypt.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ret.put("url", url); ret.put("jsapi_ticket", jsapi_ticket); ret.put("nonceStr", nonce_str); ret.put("timestamp", timestamp); ret.put("signature", signature); ret.put("appid", appid); return ret; } private String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; } private String create_nonce_str() { return UUID.randomUUID().toString().replace("-", ""); } private String create_timestamp() { return Long.toString(System.currentTimeMillis() / 1000); } }
34.073944
166
0.613207
aaf3fd42880bc73289040dbf1acb35cae9fc3825
245
package net.emandates.merchant.library; /** * Indicates type of eMandate: one-off direct debit or recurring. */ public enum SequenceType { /** * Recurring mandate */ RCUR, /** * One-off mandate */ OOFF }
13.611111
65
0.587755
e14a775e6830b78650df6b39f437475d87b8946e
1,656
package quickcarpet.mixin.updateSuppressionCrashFix; import net.minecraft.server.MinecraftServer; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.crash.CrashException; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import quickcarpet.settings.Settings; import quickcarpet.utils.Messenger; import quickcarpet.utils.PistonHelper; import quickcarpet.utils.ThrowableUpdateSuppression; import java.util.function.BooleanSupplier; @Mixin(MinecraftServer.class) public class MinecraftServerMixin { @Redirect(method = "tickWorlds", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/world/ServerWorld;tick(Ljava/util/function/BooleanSupplier;)V")) private void quickcarpet$updateSuppressionCrashFix$tick(ServerWorld serverWorld, BooleanSupplier shouldKeepTicking) { if (!Settings.updateSuppressionCrashFix) { serverWorld.tick(shouldKeepTicking); return; } try { serverWorld.tick(shouldKeepTicking); } catch (CrashException e) { if (!(e.getReport().getCause() instanceof ThrowableUpdateSuppression)) throw e; logUpdateSuppression("world tick"); } catch (ThrowableUpdateSuppression ignored) { logUpdateSuppression("world tick"); } } @Unique private void logUpdateSuppression(String phase) { PistonHelper.finishPush(); Messenger.broadcast((MinecraftServer) (Object) this, "You just caused a server crash in " + phase + "."); } }
40.390244
160
0.736111
c266719a0266f60649bf54a7f499b095646e8e7f
1,248
/* * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.codecentric.boot.admin.client.registration; /** * Interface for client application registration at spring-boot-admin-server */ public interface ApplicationRegistrator { /** * Registers the client application at spring-boot-admin-server. * @return true if successful registration on at least one admin server */ boolean register(); /** * Tries to deregister currently registered application */ void deregister(); /** * @return the id of this client as given by the admin server. Returns null if the * client has not registered against the admin server yet. */ String getRegisteredId(); }
29.714286
83
0.737981
be44dea1e5676bf7e5ba10e7b25a44586611a7c7
2,350
package tools; import controllers.CountryController; import controllers.RegionController; import java.util.List; import models.Country; /** * * @author ASUS-PC BigBoss */ public class Testing { public static void main(String[] args) { // System.out.println(new Koneksi().getConnection()); RegionController regionController = new RegionController(); CountryController countryController = new CountryController(); // insert new region // System.out.println(regionController.save("12", "South Africa")); // update a region // System.out.println(regionController.edit("1", "Korea")); // delete a region // System.out.println(regionController.delete("12")); // get Regions // for (Region region : regionController.search()){ // System.out.println("ID: "+region.getId() // +", Name: "+region.getName()); // } // search a region // List<Region> daftarRegions = regionController.search("1"); // for (Region region : daftarRegions) { // System.out.println("ID: "+region.getId()+", Name: "+region.getName()); // } // Region region = regionController.getById("2"); // System.out.println("ID: "+region.getId()+", Name: "+region.getName()); // search a country // List<Country> countriesList = countryController.search("a"); // for (Country country : countriesList) { // System.out.println("ID: "+country.getId()+", Name: "+country.getName()+", Region: "+country.getRegion()); // } // Country country = countryController.getById("UK"); // System.out.println("ID: "+country.getId()+", Name: "+country.getName()+", Region: "+country.getRegion()); // insert a country // System.out.println(countryController.save("JP", "Japan", "2")); // update a country // System.out.println(countryController.editName("KR", "South Korea", "2")); // delete a country // System.out.println(countryController.delete("JP")); // get Countries // for (Country country : countryController.binding()){ // System.out.println("ID: "+country.getId() // +", Name: "+country.getName()+", Region: "+country.getRegion()); // } } }
34.057971
119
0.588936
2868bc719f3baf4e29153d96159bacdf344c8f86
3,527
package com.acker.cafemanagement.controller; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; 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.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.acker.cafemanagement.entity.Customer; import com.acker.cafemanagement.entity.DineTable; import com.acker.cafemanagement.entity.Server; import com.acker.cafemanagement.entity.ServerReport; import com.acker.cafemanagement.service.UserService; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/api/v1/users") //@CrossOrigin(origins = "http://localhost:4200/**", allowedHeaders = "*") // for angular to interact with the controller public class UserController { final Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired UserService userService; //Get availabilities of tables, //TODO: to you, from the backend: block people from choosing occupied tables in the frontend @ApiOperation(value ="Get all tables",notes="Useful to check tables' status") @GetMapping(value="/tables") public List<DineTable> getDineTables() { return userService.getDineTables(); } //Get all customers @ApiOperation(value ="Lists all customers",notes="") @GetMapping(value="/customers") public @ResponseBody List<Customer> getCustomers() { return userService.getCustomers(); } //Register new customer @ApiOperation(value ="Creates a new customer",notes="") @PutMapping(value="/customers",consumes="application/json") public @ResponseBody Customer putCustomer(@RequestBody Customer jsonString) { return userService.putCustomer(jsonString); } @Deprecated @ApiOperation(value ="Deletes a customer",notes="NOT YET IMPLEMENTED") @DeleteMapping(value="/customers/{id}") public String deleteCustomer(@PathVariable String id) { //TODO:Implement delete customer function return "Feature hasn't been Implemented yet."; } //list of working servers @ApiOperation(value ="List all servers",notes="") @GetMapping(value="/servers") public @ResponseBody List<Server> getServers(){ return userService.getServers(); } @ApiOperation(value ="Return individual servers' report",notes="Useful to check how many orders servers has delivered.") @GetMapping(value="/servers/{serverId}") public @ResponseBody List<ServerReport> getServerReport(@PathVariable String serverId) { return userService.getServerReport(serverId); } //For new server hires @ApiOperation(value ="Creates a new server",notes="Hire a server") @PutMapping(value="/servers") public @ResponseBody Server putServer(@RequestBody Server jsonString){ userService.putServer(jsonString); return jsonString; } @Deprecated @ApiOperation(value ="Deletes a server",notes="Fire a server, NOT YET IMPLEMENTED") @DeleteMapping(value="/servers/{serverId}") public String deleteServer(@PathVariable String serverId) { //TODO:delete server with given id return null; } //end of the class }
38.758242
121
0.787638
261d92dabded07bc01eea6472768560ef12773fd
1,373
package org.appenders.log4j2.elasticsearch.failover; /*- * #%L * log4j2-elasticsearch * %% * Copyright (C) 2019 - 2020 Rafal Foltynski * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.util.Iterator; import java.util.concurrent.atomic.AtomicLong; class KeySequenceIterator implements Iterator<CharSequence> { private final KeySequence keySequence; private final AtomicLong remaining; public KeySequenceIterator(KeySequence keySequence, long maxKeys) { this.keySequence = keySequence; this.remaining = new AtomicLong(maxKeys); } @Override public boolean hasNext() { return remaining.get() > 0 && keySequence.readerKeysAvailable() > 0; } @Override public CharSequence next() { remaining.decrementAndGet(); return keySequence.nextReaderKey(); } }
28.604167
76
0.710124
83573d82d8089750a2a64c6976f01cac485e20d0
437
package com.heavenhr.interview.dto; import java.util.Date; public class CreateJobOffer { private String jobTitle; private Date startDate; public CreateJobOffer() { } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } }
15.607143
43
0.732265
f94cea90732c3359875320ddeac0e6057f824f64
9,473
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.database.snapshot; import static com.google.firebase.database.snapshot.NodeUtilities.NodeFromJSON; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableMap; import com.google.firebase.database.MapBuilder; import com.google.firebase.database.collection.ImmutableSortedMap; import com.google.firebase.database.core.Path; import com.google.firebase.database.snapshot.LeafNode.LeafType; import com.google.firebase.database.snapshot.Node.HashVersion; import java.util.Map; import org.junit.Test; public class NodeTest { @Test public void getHashWorksCorrectly() { Map<String, Object> data = new MapBuilder() .put("intNode", 4) .put("doubleNode", 4.5623) .put("stringNode", "hey guys") .put("boolNode", true) .build(); Node node = NodeFromJSON(data); Node child = node.getImmediateChild(ChildKey.fromString("intNode")); String hash = child.getHash(); assertEquals("eVih19a6ZDz3NL32uVBtg9KSgQY=", hash); child = node.getImmediateChild(ChildKey.fromString("doubleNode")); hash = child.getHash(); assertEquals("vf1CL0tIRwXXunHcG/irRECk3lY=", hash); child = node.getImmediateChild(ChildKey.fromString("stringNode")); hash = child.getHash(); assertEquals("CUNLXWpCVoJE6z7z1vE57lGaKAU=", hash); child = node.getImmediateChild(ChildKey.fromString("boolNode")); hash = child.getHash(); assertEquals("E5z61QM0lN/U2WsOnusszCTkR8M=", hash); hash = node.getHash(); assertEquals("6Mc4jFmNdrLVIlJJjz2/MakTK9I=", hash); } @Test public void matchServerHash() { Map<String, Object> wireData = new MapBuilder() .put("c", new MapBuilder().put(".value", 99).put(".priority", "abc").build()) .put(".priority", "def") .build(); Node node = NodeFromJSON(wireData); node = EmptyNode.Empty().updateChild(new Path("root"), node); String hash = node.getHash(); assertEquals("Fm6tzN4CVEu5WxFDZUdTtqbTVaA=", hash); } @Test public void leadingZeroesWorkCorrectly() { Map<String, Object> data = new MapBuilder().put("1", 1).put("01", 2).put("001", 3).put("0001", 4).build(); Node node = NodeFromJSON(data); Node child = node.getImmediateChild(ChildKey.fromString("1")); assertEquals(1L, child.getValue()); child = node.getImmediateChild(ChildKey.fromString("01")); assertEquals(2L, child.getValue()); child = node.getImmediateChild(ChildKey.fromString("001")); assertEquals(3L, child.getValue()); child = node.getImmediateChild(ChildKey.fromString("0001")); assertEquals(4L, child.getValue()); } @Test public void leadingZerosDoNotOverwriteOtherKeys() { Map<String, Object> data = new MapBuilder() .put("1", "value1") .put("01", "value2") .put("001", "value3") .put("0001", "value4") .build(); Node node = NodeFromJSON(data); assertEquals(node.getImmediateChild(ChildKey.fromString("1")).getValue(), "value1"); assertEquals(node.getImmediateChild(ChildKey.fromString("01")).getValue(), "value2"); assertEquals(node.getImmediateChild(ChildKey.fromString("001")).getValue(), "value3"); assertEquals(node.getImmediateChild(ChildKey.fromString("0001")).getValue(), "value4"); } @Test public void leadingZerosDoNotOverwriteKeysInValue() { Map<String, Object> data = new MapBuilder().put("1", "value1").put("01", "value2").build(); Node node = NodeFromJSON(data); assertEquals(node.getValue(), data); } @Test public void emptyNodeEqualsEmptyChildrenNode() { assertEquals(EmptyNode.Empty(), new ChildrenNode()); assertEquals(new ChildrenNode(), EmptyNode.Empty()); } @Test public void updatingEmptyChildrenDoesntOverwriteLeafNode() { LeafNode<StringNode> node = new StringNode("value", PriorityUtilities.NullPriority()); assertEquals(node, node.updateChild(new Path(".priority"), EmptyNode.Empty())); assertEquals(node, node.updateChild(new Path("child"), EmptyNode.Empty())); assertEquals(node, node.updateChild(new Path("child/.priority"), EmptyNode.Empty())); assertEquals(node, node.updateImmediateChild(ChildKey.fromString("child"), EmptyNode.Empty())); assertEquals(node, node.updateImmediateChild(ChildKey.getPriorityKey(), EmptyNode.Empty())); } @Test public void updatingPrioritiesOnEmptyNodesIsANoop() { Node priority = PriorityUtilities.parsePriority("prio"); assertTrue(EmptyNode.Empty().updatePriority(priority).getPriority().isEmpty()); assertTrue( EmptyNode.Empty().updateChild(new Path(".priority"), priority).getPriority().isEmpty()); assertTrue( EmptyNode.Empty() .updateImmediateChild(ChildKey.getPriorityKey(), priority) .getPriority() .isEmpty()); Node reemptiedChildren = EmptyNode.Empty() .updateChild(new Path("child"), NodeFromJSON("value")) .updateChild(new Path("child"), EmptyNode.Empty()); assertTrue(reemptiedChildren.updatePriority(priority).getPriority().isEmpty()); assertTrue( reemptiedChildren.updateChild(new Path(".priority"), priority).getPriority().isEmpty()); assertTrue( reemptiedChildren .updateImmediateChild(ChildKey.getPriorityKey(), priority) .getPriority() .isEmpty()); } @Test public void deletingLastChildFromChildrenNodeRemovesPriority() { Node priority = PriorityUtilities.parsePriority("prio"); Node withPriority = EmptyNode.Empty() .updateChild(new Path("child"), NodeFromJSON("value")) .updatePriority(priority); assertEquals(priority, withPriority.getPriority()); Node deletedChild = withPriority.updateChild(new Path("child"), EmptyNode.Empty()); assertTrue(deletedChild.getPriority().isEmpty()); } @Test public void nodeFromJsonReturnsEmptyNodesWithoutPriority() { Node empty1 = NodeFromJSON(new MapBuilder().put(".priority", "prio").build()); assertTrue(empty1.getPriority().isEmpty()); Node empty2 = NodeFromJSON(new MapBuilder().put("dummy-node", null).put(".priority", "prio").build()); assertTrue(empty2.getPriority().isEmpty()); } @Test public void testEmptyChildrenNode() { ChildrenNode node = new ChildrenNode(); assertTrue(node.isEmpty()); assertNull(node.getValue()); assertEquals("{ }", node.toString()); assertEquals(0, node.hashCode()); assertEquals(0, node.compareTo(new ChildrenNode())); } @Test public void testEmptyChildrenNodeWithPriority() { ImmutableSortedMap<ChildKey, Node> map = ImmutableSortedMap.Builder.fromMap( ImmutableMap.<ChildKey, Node>of(), null); try { new ChildrenNode(map, PriorityUtilities.parsePriority(1)); fail("No error thrown for empty children node"); } catch (IllegalArgumentException expected) { // expected } } @Test public void testChildrenNode() { ImmutableMap<ChildKey, Node> source = ImmutableMap.of( ChildKey.fromString("foo"), NodeUtilities.NodeFromJSON("value1"), ChildKey.fromString("bar"), NodeUtilities.NodeFromJSON("value2") ); ImmutableSortedMap<ChildKey, Node> map = ImmutableSortedMap.Builder.fromMap(source, null); ChildrenNode node = new ChildrenNode(map, PriorityUtilities.parsePriority(1)); assertFalse(node.isEmpty()); assertEquals(ImmutableMap.of("foo", "value1", "bar", "value2"), node.getValue()); assertEquals( "{\n" + " bar=value2\n" + " foo=value1\n" + " .priority=1.0\n" + "}", node.toString()); ChildrenNode other = new ChildrenNode(map, PriorityUtilities.parsePriority(1)); assertEquals(node, other); assertEquals(node.hashCode(), other.hashCode()); } @Test public void testDeferredValueNode() { Map<Object, Object> map = ImmutableMap.<Object, Object>of("foo", "bar", "int", 5); DeferredValueNode node = new DeferredValueNode(map, PriorityUtilities.parsePriority(1)); assertEquals(map, node.getValue()); assertEquals(LeafType.DeferredValue, node.getLeafType()); assertNotNull(node.getHashRepresentation(HashVersion.V1)); DeferredValueNode otherNode = new DeferredValueNode( ImmutableMap.<Object, Object>of("other", "value"), PriorityUtilities.parsePriority(2)); assertEquals(0, node.compareLeafValues(otherNode)); assertNotEquals(node, otherNode); assertNotEquals(node.hashCode(), otherNode.hashCode()); } }
37.295276
99
0.690172
83f759606e3ee288d72e21e7c85463b851a940e0
1,130
package com.be.library.worker.rxbindings; import com.be.android.library.worker.base.JobEvent; import com.be.android.library.worker.interfaces.JobEventListener; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * @author Eugene Byzov gdzhey@gmail.com * Created on 09-Sep-16. */ class CompositeEventListener implements JobEventListener { private final Set<Integer> mPendingJobs; private JobEventListener mDelegate; CompositeEventListener(Collection<Integer> pendingJobs) { mPendingJobs = new HashSet<>(pendingJobs); } @Override public void onJobEvent(JobEvent event) { if (!mPendingJobs.contains(event.getJobId())) { return; } if (event.isJobFinished()) { mPendingJobs.remove(event.getJobId()); } mDelegate.onJobEvent(event); } public boolean isCompleted() { return mPendingJobs.isEmpty(); } public JobEventListener getDelegate() { return mDelegate; } public void setDelegate(JobEventListener delegate) { mDelegate = delegate; } }
23.541667
65
0.674336
050cf5eedfcf53c7b13bc5cced887e068e642a2b
615
package com.ittianyu.relight.todo.common.constants; public interface Images { String ic_logo = "ic_logo.png"; String ic_empty = "ic_empty.png"; String ic_error = "ic_error.png"; String ic_add = "ic_add.png"; String ic_status_wait = "ic_status_wait.png"; String ic_status_doing = "ic_status_doing.png"; String ic_status_completed = "ic_status_completed.png"; String ic_back = "ic_back.png"; String ic_date_start = "ic_date_start.png"; String ic_date_end = "ic_date_end.png"; String ic_arrow_left = "ic_arrow_left.png"; String ic_arrow_right = "ic_arrow_right.png"; }
36.176471
59
0.720325
7f7880678d45b3157072406bf0e746c36fad7603
6,452
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.generation; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.source.PsiExtensibleClass; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.SimpleTextAttributes; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.util.*; /** * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com> */ public class PsiMethodWithOverridingPercentMember extends PsiMethodMember { private final int myOverridingPercent; public PsiMethodWithOverridingPercentMember(final CandidateInfo info, final int overridingPercent) { super(info); myOverridingPercent = overridingPercent; } @Override public void renderTreeNode(final SimpleColoredComponent component, final JTree tree) { component.append(myOverridingPercent + "% ", SimpleTextAttributes.GRAY_ATTRIBUTES); super.renderTreeNode(component, tree); } @TestOnly public int getOverridingPercent() { return myOverridingPercent; } public static final Comparator<PsiMethodMember> COMPARATOR = (e1, e2) -> { if (!(e1 instanceof PsiMethodWithOverridingPercentMember)) { if (!(e2 instanceof PsiMethodWithOverridingPercentMember)) { return e1.equals(e2) ? 0 : -1; } else { return -1; } } if (!(e2 instanceof PsiMethodWithOverridingPercentMember)) { return 1; } int sub = ((PsiMethodWithOverridingPercentMember)e2).myOverridingPercent - ((PsiMethodWithOverridingPercentMember)e1).myOverridingPercent; if (sub != 0) return sub; return String.CASE_INSENSITIVE_ORDER.compare(e1.getText(), e2.getText()); }; @NotNull public static PsiMethodWithOverridingPercentMember[] calculateOverridingPercents(@NotNull final Collection<? extends CandidateInfo> candidateInfos) { final List<PsiMethodWithOverridingPercentMember> result = new ArrayList<>(candidateInfos.size()); final Map<String, Collection<PsiClass>> classShortNames2Inheritors = new HashMap<>(); for (final CandidateInfo candidateInfo : candidateInfos) { final PsiMethod method = (PsiMethod)candidateInfo.getElement(); if (!method.hasModifierProperty(PsiModifier.FINAL) && !method.isConstructor() && !method.isDeprecated() && !EXCLUDED_JAVA_LANG_OBJECT_METHOD_NAMES.contains(method.getName())) { final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) { continue; } final String classShortName = containingClass.getName(); Collection<PsiClass> allInheritors = classShortNames2Inheritors.get(classShortName); if (allInheritors == null) { allInheritors = ClassInheritorsSearch.search(containingClass).findAll(); classShortNames2Inheritors.put(classShortName, allInheritors); } final int allInheritorsCount = allInheritors.size() - 1; if (allInheritorsCount > 0) { final int percent = searchForOverridingCount(method, allInheritors) * 100 / allInheritorsCount; if (percent > 1) { result.add(new PsiMethodWithOverridingPercentMember(candidateInfo, percent)); } } } } return result.toArray(new PsiMethodWithOverridingPercentMember[0]); } private static int searchForOverridingCount(final PsiMethod method, final Collection<? extends PsiClass> containingClassInheritors) { int counter = 0; for (final PsiClass inheritor : containingClassInheritors) { if (inheritor instanceof PsiExtensibleClass) { final List<PsiMethod> ownMethods = ((PsiExtensibleClass)inheritor).getOwnMethods(); for (PsiMethod ownMethod : ownMethods) { if (maybeSuper(method, ownMethod)) { counter++; break; } } } } return counter; } private static boolean maybeSuper(@NotNull final PsiMethod superMethod, @NotNull final PsiMethod method) { if (!superMethod.getName().equals(method.getName())) { return false; } final PsiParameterList superMethodParameterList = superMethod.getParameterList(); final PsiParameterList methodParameterList = method.getParameterList(); if (superMethodParameterList.getParametersCount() != methodParameterList.getParametersCount()) { return false; } final PsiParameter[] superMethodParameters = superMethodParameterList.getParameters(); final PsiParameter[] methodParameters = methodParameterList.getParameters(); for (int i = 0; i < methodParameters.length; i++) { if (!StringUtil.equals(getTypeShortName(superMethodParameters[i].getType()), getTypeShortName(methodParameters[i].getType()))) { return false; } } return true; } @Nullable private static String getTypeShortName(@NotNull final PsiType type) { if (type instanceof PsiPrimitiveType) { return ((PsiPrimitiveType)type).getBoxedTypeName(); } if (type instanceof PsiClassType) { return ((PsiClassType)type).getClassName(); } if (type instanceof PsiArrayType) { return getTypeShortName(((PsiArrayType)type).getComponentType()) + "[]"; } return null; } private static final Set<String> EXCLUDED_JAVA_LANG_OBJECT_METHOD_NAMES = ContainerUtil.newHashSet("hashCode", "finalize", "clone", "equals", "toString"); @Override public String toString() { return "PsiMethodWithOverridingPercentMember{" + "myOverridingPercent=" + myOverridingPercent + ", myElement=" + getElement() + '}'; } }
37.952941
151
0.718227
72763697d752462ae384f954def8e2b73ef15cfe
1,952
package com.ceiba.usuario.entidad; import com.ceiba.BasePrueba; import com.ceiba.dominio.excepcion.ExcepcionLongitudValor; import com.ceiba.dominio.excepcion.ExcepcionValorObligatorio; import com.ceiba.pedido.modelo.entidad.Pedido; import com.ceiba.usuario.modelo.entidad.Usuario; import com.ceiba.usuario.servicio.testdatabuilder.PedidoTestDataBuilder; import com.ceiba.usuario.servicio.testdatabuilder.UsuarioTestDataBuilder; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.Date; import static org.junit.jupiter.api.Assertions.assertEquals; public class PedidoTest { @Test @DisplayName("Deberia crear correctamente un Pedido") void deberiaCrearCorrectamenteUnPedido() { // arrange Date fechaCreacion = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); //act Pedido pedido = new PedidoTestDataBuilder(1L, sdf.format(fechaCreacion)).build(); //assert assertEquals(1, pedido.getId()); assertEquals(sdf.format(fechaCreacion), sdf.format(pedido.getFecha())); } @Test void deberiaFallarSinFecha() { //Arrange PedidoTestDataBuilder pedidoTestDataBuilder = new PedidoTestDataBuilder(null, null); //act-assert BasePrueba.assertThrows(() -> { pedidoTestDataBuilder.build(); }, ExcepcionValorObligatorio.class, "Se debe ingresar la fecha"); } @Test void deberiaFallarSinProductos() { //Arrange PedidoTestDataBuilder pedidoTestDataBuilder = new PedidoTestDataBuilder(); //act-assert BasePrueba.assertThrows(() -> { pedidoTestDataBuilder.build(); }, ExcepcionValorObligatorio.class, "Se debe ingresar productos"); } }
32.533333
92
0.695184
42e19140e7e8dc1f9d48825a6d06cbc75fb0f8d7
2,486
/* * #%L * de.metas.swat.base * %% * Copyright (C) 2021 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.inout.callout; import de.metas.document.location.IDocumentLocationBL; import de.metas.inout.location.adapter.InOutDocumentLocationAdapterFactory; import de.metas.util.Services; import lombok.NonNull; import org.adempiere.ad.callout.annotations.Callout; import org.adempiere.ad.callout.annotations.CalloutMethod; import org.adempiere.ad.callout.spi.IProgramaticCalloutProvider; import org.compiere.model.I_M_InOut; import org.springframework.stereotype.Component; @Callout(I_M_InOut.class) @Component public class M_InOut { private final IDocumentLocationBL documentLocationBL; public M_InOut(@NonNull final IDocumentLocationBL documentLocationBL) { this.documentLocationBL = documentLocationBL; final IProgramaticCalloutProvider programaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class); programaticCalloutProvider.registerAnnotatedCallout(this); } @CalloutMethod(columnNames = { I_M_InOut.COLUMNNAME_C_BPartner_ID, I_M_InOut.COLUMNNAME_C_BPartner_Location_ID, I_M_InOut.COLUMNNAME_AD_User_ID }, skipIfCopying = true) public void updateBPartnerAddress(final I_M_InOut inout) { documentLocationBL.updateRenderedAddressAndCapturedLocation(InOutDocumentLocationAdapterFactory.locationAdapter(inout)); } @CalloutMethod(columnNames = { I_M_InOut.COLUMNNAME_IsDropShip, I_M_InOut.COLUMNNAME_DropShip_BPartner_ID, I_M_InOut.COLUMNNAME_DropShip_Location_ID, I_M_InOut.COLUMNNAME_DropShip_User_ID, I_M_InOut.COLUMNNAME_M_Warehouse_ID }, skipIfCopying = true) public void updateDeliveryToAddress(final I_M_InOut inout) { documentLocationBL.updateRenderedAddressAndCapturedLocation(InOutDocumentLocationAdapterFactory.deliveryLocationAdapter(inout)); } }
35.014085
130
0.806516
5e0b7e101660d3dfe9c12890db66768c25b67d74
1,001
package com.example.administrator.myjournal.util; import android.content.Context; import android.graphics.Bitmap; import android.text.Editable; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ImageSpan; import android.util.AttributeSet; import android.widget.EditText; /** * Created by Administrator on 2016/6/8. */ //public class InsertPicEditText extends EditText { // // public InsertPicEditText(Context context) { // super(context); // } // public InsertPicEditText(Context context, AttributeSet attrs) { // super(context, attrs); // } // @SuppressWarnings("deprecation") // public SpannableString displayBitmap(Bitmap bitmap, String imagePath) { // SpannableString mSpan1 = new SpannableString("|" + "img" + imagePath + "|"); // if(bitmap == null) return null; // mSpan1.setSpan(new ImageSpan(bitmap) , 0, mSpan1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // return mSpan1; // } //}
32.290323
103
0.705295
1771a133bb03bfdd8f10b1da98d2535594390ec1
5,684
package de.upb.crypto.math.factory; /** * Requirements for a bilinear group. * <p> * This class is indented to use for the configuration of the {@link BilinearGroupFactory}. A user sets up an object * with the settings they need the bilinear group to fulfill and register the config using * {@link BilinearGroupFactory#setRequirements(BilinearGroupRequirement)}. The configuration are the basis for the * selecting a suitable bilinear group to create. * * @author Denis Diemert */ public class BilinearGroupRequirement { /** * The desired type of the {@link BilinearGroup}. For the possible values, consider {@link BilinearGroup.Type}. */ private BilinearGroup.Type type; /** * If set to true, the resulting factory will be able to supply a hash function byte[] -> G1. (If set to false, it * may or may not support this) */ private boolean hashIntoG1Needed = false; /** * If set to true, the resulting factory will be able to supply a hash function byte[] -> G2. (If set to false, it * may or may not support this) */ private boolean hashIntoG2Needed = false; /** * If set to true, the resulting factory will be able to supply a hash function byte[] -> GT. (If set to false, it * may or may not support this) */ private boolean hashIntoGTNeeded = false; /** * If set to 1, the resulting {@link BilinearGroup} will consist of (G1, G2, GT) of prime order. Else, if set to a * value > 1, the group order is a composite number with {@code cardinalityNumPrimeFactors} prime factors. */ private int cardinalityNumPrimeFactors; /** * Standard constructor to set all requirements by hand. * * @param type the desired type of the resulting bilinear group * @param hashIntoG1Needed true enforces that the resulting bilinear group provides a mapping byte[] -> * G1. When set to false, it * may still be supported. * @param hashIntoG2Needed true enforces that the resulting bilinear group provides a mapping byte[] -> * G2. When set to false, it * may still be supported. * @param hashIntoGTNeeded true enforces that the resulting bilinear group provides a mapping byte[] -> * GT. When set to false, it * may still be supported. * @param cardinalityNumPrimeFactors number of prime factors of the resulting groups */ public BilinearGroupRequirement(BilinearGroup.Type type, boolean hashIntoG1Needed, boolean hashIntoG2Needed, boolean hashIntoGTNeeded, int cardinalityNumPrimeFactors) { this.type = type; this.hashIntoG1Needed = hashIntoG1Needed; this.hashIntoG2Needed = hashIntoG2Needed; this.hashIntoGTNeeded = hashIntoGTNeeded; this.cardinalityNumPrimeFactors = cardinalityNumPrimeFactors; } /** * Constructor for prime order groups, and {@link #cardinalityNumPrimeFactors} is set to 1. * * @param type the desired type of the resulting bilinear group * @param hashIntoG1Needed true enforces that the resulting bilinear group provides a mapping byte[] -> G1. When * set to false, it * may still be supported. * @param hashIntoG2Needed true enforces that the resulting bilinear group provides a mapping byte[] -> G2. When * set to false, it * may still be supported. * @param hashIntoGTNeeded true enforces that the resulting bilinear group provides a mapping byte[] -> GT. When * set to false, it * may still be supported. */ public BilinearGroupRequirement(BilinearGroup.Type type, boolean hashIntoG1Needed, boolean hashIntoG2Needed, boolean hashIntoGTNeeded) { this(type, hashIntoG1Needed, hashIntoG2Needed, hashIntoGTNeeded, 1); } /** * Constructor for prime order groups without any requirements for hashing, i. e. * {@link #cardinalityNumPrimeFactors} is set to 1 and {@link #hashIntoG1Needed}, {@link #hashIntoG2Needed}, * {@link #hashIntoGTNeeded} is set to false. * * @param type the desired type of the resulting bilinear group */ public BilinearGroupRequirement(BilinearGroup.Type type) { this(type, false, false, false); } /** * Constructor for composite order groups without any requirements for hashing, i. e. {@link #hashIntoG1Needed}, * {@link #hashIntoG2Needed}, {@link #hashIntoGTNeeded} is set to false by default. * * @param type the desired type of the resulting bilinear group * @param cardinalityNumPrimeFactors * number of prime factors of the resulting groups */ public BilinearGroupRequirement(BilinearGroup.Type type, int cardinalityNumPrimeFactors) { this(type, false, false, false, cardinalityNumPrimeFactors); } public BilinearGroup.Type getType() { return type; } public boolean isHashIntoG1Needed() { return hashIntoG1Needed; } public boolean isHashIntoG2Needed() { return hashIntoG2Needed; } public boolean isHashIntoGTNeeded() { return hashIntoGTNeeded; } public int getCardinalityNumPrimeFactors() { return cardinalityNumPrimeFactors; } }
45.83871
118
0.63494
5c606068cccd869ea9620a70fcff6e5a97972ff3
2,580
package com.cm.media.ui.activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import androidx.appcompat.app.AppCompatActivity; import com.cm.media.R; import com.cm.media.ui.fragment.PlayerFragment; import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; public class VodPlayerActivity extends BaseThemeActivity { @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.clearFlags(FLAG_TRANSLUCENT_STATUS); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); } else { this.getWindow().addFlags(FLAG_TRANSLUCENT_STATUS); } super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_vod_player); int vid = getIntent().getIntExtra("vid", 0); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.container, PlayerFragment.newInstance(vid)) .commitNow(); } } public static void startVodPlay(Context context, int vid) { Intent intent = new Intent(context, VodPlayerActivity.class); intent.putExtra("vid", vid); context.startActivity(intent); } @Override public void onBackPressed() { PlayerFragment fragment = (PlayerFragment) getSupportFragmentManager().findFragmentById(R.id.container); if (fragment != null) { if (fragment.onBackPressed()) { return; } } super.onBackPressed(); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { PlayerFragment fragment = (PlayerFragment) getSupportFragmentManager().findFragmentById(R.id.container); if (fragment != null) { fragment.dismissNaviBar(); } } } }
36.857143
116
0.674806
4f5053122ec5edfa5daed476e2a98b939a983459
6,700
package seedu.address.storage; import static org.junit.jupiter.api.Assertions.assertEquals; import static seedu.address.storage.JsonAdaptedPatient.MISSING_FIELD_MESSAGE_FORMAT; import static seedu.address.testutil.Assert.assertThrows; import static seedu.address.testutil.TypicalPatients.BENSON; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.patient.Address; import seedu.address.model.patient.Email; import seedu.address.model.patient.Name; import seedu.address.model.patient.Phone; public class JsonAdaptedPatientTest { private static final String INVALID_NAME = "R@chel"; private static final String INVALID_BIRTHDATE = "020220"; private static final String INVALID_BLOODTYPE = "A"; private static final String INVALID_PHONE = "+651234"; private static final String INVALID_ADDRESS = " "; private static final String INVALID_EMAIL = "example.com"; private static final String INVALID_TAG = "#friend"; private static final String VALID_NAME = BENSON.getName().toString(); private static final String VALID_GENDER = BENSON.getGender().toString(); private static final String VALID_BIRTHDATE = BENSON.getBirthdate().toString(); private static final String VALID_BLOODTYPE = "A+"; private static final String VALID_PHONE = BENSON.getPhone().toString(); private static final String VALID_EMAIL = BENSON.getEmail().toString(); private static final String VALID_ADDRESS = BENSON.getAddress().toString(); private static final String VALID_REMARK = BENSON.getRemark().toString(); private static final List<JsonAdaptedTag> VALID_TAGS = BENSON.getTags().stream() .map(JsonAdaptedTag::new) .collect(Collectors.toList()); @Test public void toModelType_validPersonDetails_returnsPerson() throws Exception { JsonAdaptedPatient person = new JsonAdaptedPatient(BENSON); assertEquals(BENSON, person.toModelType()); } @Test public void toModelType_invalidName_throwsIllegalValueException() { JsonAdaptedPatient person = new JsonAdaptedPatient(INVALID_NAME, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, VALID_PHONE, VALID_EMAIL, VALID_ADDRESS, VALID_REMARK, VALID_TAGS); String expectedMessage = Name.MESSAGE_CONSTRAINTS; assertThrows(IllegalValueException.class, expectedMessage, person::toModelType); } @Test public void toModelType_nullName_throwsIllegalValueException() { JsonAdaptedPatient person = new JsonAdaptedPatient(null, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, VALID_PHONE, VALID_EMAIL, VALID_ADDRESS, VALID_REMARK, VALID_TAGS); String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, Name.class.getSimpleName()); assertThrows(IllegalValueException.class, expectedMessage, person::toModelType); } @Test public void toModelType_invalidPhone_throwsIllegalValueException() { JsonAdaptedPatient person = new JsonAdaptedPatient(VALID_NAME, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, INVALID_PHONE, VALID_EMAIL, VALID_ADDRESS, VALID_REMARK, VALID_TAGS); String expectedMessage = Phone.MESSAGE_CONSTRAINTS; assertThrows(IllegalValueException.class, expectedMessage, person::toModelType); } @Test public void toModelType_nullPhone_throwsIllegalValueException() { JsonAdaptedPatient person = new JsonAdaptedPatient(VALID_NAME, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, null, VALID_EMAIL, VALID_ADDRESS, VALID_REMARK, VALID_TAGS); String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, Phone.class.getSimpleName()); assertThrows(IllegalValueException.class, expectedMessage, person::toModelType); } @Test public void toModelType_invalidEmail_throwsIllegalValueException() { JsonAdaptedPatient person = new JsonAdaptedPatient(VALID_NAME, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, VALID_PHONE, INVALID_EMAIL, VALID_ADDRESS, VALID_REMARK, VALID_TAGS); String expectedMessage = Email.MESSAGE_CONSTRAINTS; assertThrows(IllegalValueException.class, expectedMessage, person::toModelType); } @Test public void toModelType_nullEmail_throwsIllegalValueException() { JsonAdaptedPatient person = new JsonAdaptedPatient(VALID_NAME, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, VALID_PHONE, null, VALID_ADDRESS, VALID_REMARK, VALID_TAGS); String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, Email.class.getSimpleName()); assertThrows(IllegalValueException.class, expectedMessage, person::toModelType); } @Test public void toModelType_invalidAddress_throwsIllegalValueException() { JsonAdaptedPatient person = new JsonAdaptedPatient(VALID_NAME, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, VALID_PHONE, VALID_EMAIL, INVALID_ADDRESS, VALID_REMARK, VALID_TAGS); String expectedMessage = Address.MESSAGE_CONSTRAINTS; assertThrows(IllegalValueException.class, expectedMessage, person::toModelType); } @Test public void toModelType_nullAddress_throwsIllegalValueException() { JsonAdaptedPatient person = new JsonAdaptedPatient(VALID_NAME, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, VALID_PHONE, VALID_EMAIL, null, VALID_REMARK, VALID_TAGS); String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, Address.class.getSimpleName()); assertThrows(IllegalValueException.class, expectedMessage, person::toModelType); } @Test public void toModelType_invalidTags_throwsIllegalValueException() { List<JsonAdaptedTag> invalidTags = new ArrayList<>(VALID_TAGS); invalidTags.add(new JsonAdaptedTag(INVALID_TAG)); JsonAdaptedPatient person = new JsonAdaptedPatient(VALID_NAME, VALID_GENDER, VALID_BIRTHDATE, VALID_BLOODTYPE, VALID_PHONE, VALID_EMAIL, VALID_ADDRESS, VALID_REMARK, invalidTags); assertThrows(IllegalValueException.class, person::toModelType); } }
48.201439
108
0.713731
62a7e14514851c63e6226fe54b0cf8ab81fbddf6
5,662
/* * Copyright 2014-2020 Christian Seifert * * 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 de.perdian.apps.tagtiger.model; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.function.Supplier; import org.apache.commons.lang3.StringUtils; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.tag.FieldDataInvalidException; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.images.Artwork; import javafx.beans.property.ObjectProperty; interface SongAttributeConverter<T> { Supplier<T> createClearSupplier(ObjectProperty<T> persistedValue); T readValue(AudioFile audioFile) throws IOException; void writeValue(AudioFile audioFile, T value) throws IOException; static class FileNameAttributeConverter implements SongAttributeConverter<String> { @Override public Supplier<String> createClearSupplier(ObjectProperty<String> persistedValue) { return persistedValue::getValue; } @Override public String readValue(AudioFile audioFile) throws IOException { String fileName = audioFile.getFile().getName(); int fileTypeSeparatorIndex = fileName.lastIndexOf("."); return fileTypeSeparatorIndex < 0 ? fileName.strip() : fileName.substring(0, fileTypeSeparatorIndex).strip(); } @Override public void writeValue(AudioFile audioFile, String newFileName) throws IOException { File existingFile = audioFile.getFile(); int existingFileTypeSeparatorIndex = existingFile.getName().lastIndexOf("."); String existingFileExtension = existingFileTypeSeparatorIndex < 0 ? ".mp3" : existingFile.getName().substring(existingFileTypeSeparatorIndex).strip(); String newFileNameWithExtension = cleanupFileName(newFileName.strip()) + existingFileExtension; File newFile = new File(existingFile.getParentFile(), newFileNameWithExtension); Files.move(existingFile.toPath(), newFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); audioFile.setFile(newFile); } private String cleanupFileName(String newFileName) { StringBuilder cleanFileName = new StringBuilder(); for (char c : newFileName.toCharArray()) { if (c == '/') { cleanFileName.append("_"); } else { cleanFileName.append(c); } } return cleanFileName.toString(); } } static class FieldKeyAttributeConverter implements SongAttributeConverter<String> { private FieldKey fieldKey = null; public FieldKeyAttributeConverter(FieldKey fieldKey) { this.setFieldKey(fieldKey); } @Override public Supplier<String> createClearSupplier(ObjectProperty<String> persistedValue) { return () -> ""; } @Override public String readValue(AudioFile audioFile) throws IOException { return audioFile.getTag() == null ? "" : audioFile.getTag().getFirst(this.getFieldKey()); } @Override public void writeValue(AudioFile audioFile, String newValue) throws IOException { try { if (StringUtils.isEmpty(newValue)) { if (audioFile.getTag() != null) { audioFile.getTag().deleteField(this.getFieldKey()); } } else { audioFile.getTagOrCreateAndSetDefault().setField(this.getFieldKey(), newValue); } } catch (FieldDataInvalidException e) { throw new IOException("Cannot write MP3 tag '" + this.getFieldKey().name() + "': " + e.getMessage(), e); } } private FieldKey getFieldKey() { return this.fieldKey; } private void setFieldKey(FieldKey fieldKey) { this.fieldKey = fieldKey; } } static class ArtworkAttributeConverter implements SongAttributeConverter<SongImages> { @Override public Supplier<SongImages> createClearSupplier(ObjectProperty<SongImages> persistedValue) { return () -> new SongImages(Collections.emptyList()); } @Override public SongImages readValue(AudioFile audioFile) throws IOException { return new SongImages(audioFile); } @Override public void writeValue(AudioFile audioFile, SongImages value) throws IOException { Tag audioFileTag = audioFile.getTagOrCreateDefault(); audioFileTag.deleteArtworkField(); for (Artwork artwork : value.toArtworkList()) { try { audioFileTag.addField(artwork); } catch (FieldDataInvalidException e) { throw new IOException("Cannot store image into MP3 tag", e); } } } } }
37.496689
162
0.65083
8353c7969ebb2aaa7f88539e6fc4f5ea77390475
627
package com.baitforbyte.networkhw1.shared.file.master; import java.io.IOException; public interface IFileServer { /** * Listens to new socket connections, accepts them and start them * * @return The newly opened socket connection * @throws IOException if there were an error opening the connection */ FileServerThread listenAndAccept() throws IOException; /** * Get the file server thread with the given identifier * * @param identifier Identifier for the file server thread * @return File server thread */ FileServerThread getFSThread(String identifier); }
28.5
72
0.706539
e8cb3ae7604cb04114b6ca454bcd61a47d6e6107
2,839
/** * Copyright (c) 2019, Salesforce.com, 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: * * 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 Salesforce.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.salesforce.bazel.sdk.command; import java.io.IOException; import java.util.List; import java.util.function.Function; /** * A built command that can be run via the run() method. */ public interface Command { /** * Executes the command represented by this instance, and return the exit code of the command. This method should * not be called twice on the same object. * * @throws CoreException */ int run() throws IOException, InterruptedException; /** * Returns the list of lines selected from the standard error stream. Lines printed to the standard error stream by * the executed command can be filtered to be added to that list. * * @see {@link CommandBuilder#setStderrLineSelector(Function)} */ List<String> getSelectedErrorLines(); /** * Returns the list of lines selected from the standard output stream. Lines printed to the standard output stream * by the executed command can be filtered to be added to that list. * * @see {@link CommandBuilder#setStdoutLineSelector(Function)} */ List<String> getSelectedOutputLines(); /** * Returns a BazelProcessBuilder configured to run this Command instance. */ BazelProcessBuilder getProcessBuilder(); }
44.359375
119
0.743924
42071854670eeb712b8a063ceb3ec221b498faab
1,615
package com.webcheckers.ui; import com.google.gson.Gson; import com.webcheckers.application.MoveController; import com.webcheckers.model.BoardView; import com.webcheckers.util.Message; import spark.Request; import spark.Response; import spark.Route; import spark.Session; import static com.webcheckers.ui.GetReplayGameRoute.MOVE_CONTROLLER_ATTR; import static com.webcheckers.ui.GetReplayGameRoute.NEW_BOARD; import static com.webcheckers.util.Message.info; /** * The UI controller used to tell the {@link MoveController} to * update the model when the user wants to display the next turn. * * @author Andrew Frank, ajf8248@rit.edu */ public class PostReplayNextTurnRoute implements Route { private Gson gson; public PostReplayNextTurnRoute(Gson gson) { this.gson = gson; } /** * When a user clicks the 'Next' button on the client, the MoveController * will update the model to the next move available that was made during * the game. * * @param request * the HTTP request * @param response * the HTTP response * @return A JSON converted {@link Message} with information about the * status of the move. */ @Override public Object handle(Request request, Response response) { final Session session = request.session(); MoveController moveController = session.attribute(MOVE_CONTROLLER_ATTR); BoardView newBoard = moveController.getNext(); session.attribute(NEW_BOARD, newBoard); Message nextMoveMessage = info("true"); return gson.toJson(nextMoveMessage); } }
31.057692
80
0.717028
161936d4c340d1052a34304cdcd8dd03409a0bc5
5,595
/* * @(#)IntersectEllipseEllipse.java * Copyright © 2021 The authors and contributors of JHotDraw. MIT License. */ package org.jhotdraw8.geom.intersect; import org.jhotdraw8.annotation.NonNull; import org.jhotdraw8.geom.Geom; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; /** * The code of this class has been derived from intersection.js [1]. * <p> * References: * <dl> * <dt>[1] intersection.js</dt> * <dd>intersection.js, Copyright (c) 2002 Kevin Lindsey, BSD 3-clause license. * <a href="http://www.kevlindev.com/gui/math/intersection/Intersection.js">kevlindev.com</a></dd> * </dl> */ public class IntersectEllipseEllipse { private IntersectEllipseEllipse() { } /** * Computes the intersection between two ellipses. * * @param c1 the center of ellipse 1 * @param rx1 the x-radius of ellipse 1 * @param ry1 the y-radius of ellipse 1 * @param c2 the center of ellipse 2 * @param rx2 the x-radius of ellipse 2 * @param ry2 the y-radius of ellipse 2 * @return computed intersection */ public static @NonNull IntersectionResult intersectEllipseEllipse(@NonNull Point2D c1, double rx1, double ry1, @NonNull Point2D c2, double rx2, double ry2) { return intersectEllipseEllipse(c1.getX(), c1.getY(), rx1, ry1, c2.getX(), c2.getY(), rx2, ry2); } /** * Computes the intersection between two ellipses. * * @param cx1 the center of ellipse 1 * @param cy1 the center of ellipse 1 * @param rx1 the x-radius of ellipse 1 * @param ry1 the y-radius of ellipse 1 * @param cx2 the center of ellipse 2 * @param cy2 the center of ellipse 2 * @param rx2 the x-radius of ellipse 2 * @param ry2 the y-radius of ellipse 2 * @return computed intersection */ public static @NonNull IntersectionResult intersectEllipseEllipse(double cx1, double cy1, double rx1, double ry1, double cx2, double cy2, double rx2, double ry2) { return intersectEllipseEllipse(cx1, cy1, rx1, ry1, cx2, cy2, rx2, ry2, Geom.REAL_THRESHOLD); } /** * @param cx1 * @param cy1 * @param rx1 * @param ry1 * @param cx2 * @param cy2 * @param rx2 * @param ry2 * @param epsilon * @return */ public static @NonNull IntersectionResult intersectEllipseEllipse(double cx1, double cy1, double rx1, double ry1, double cx2, double cy2, double rx2, double ry2, double epsilon) { double[] a = { ry1 * ry1, 0, rx1 * rx1, -2 * ry1 * ry1 * cx1, -2 * rx1 * rx1 * cy1, ry1 * ry1 * cx1 * cx1 + rx1 * rx1 * cy1 * cy1 - rx1 * rx1 * ry1 * ry1 }; double[] b = { ry2 * ry2, 0, rx2 * rx2, -2 * ry2 * ry2 * cx2, -2 * rx2 * rx2 * cy2, ry2 * ry2 * cx2 * cx2 + rx2 * rx2 * cy2 * cy2 - rx2 * rx2 * ry2 * ry2 }; Polynomial yPoly = Intersections.bezout(a, b); double[] yRoots = yPoly.getRoots(); double norm0 = (a[0] * a[0] + 2 * a[1] * a[1] + a[2] * a[2]) * Intersections.EPSILON; double norm1 = (b[0] * b[0] + 2 * b[1] * b[1] + b[2] * b[2]) * Intersections.EPSILON; List<IntersectionPoint> result = new ArrayList<>(); for (int y = 0; y < yRoots.length; y++) { Polynomial xPoly = new Polynomial( a[0], a[3] + yRoots[y] * a[1], a[5] + yRoots[y] * (a[4] + yRoots[y] * a[2]) ); double[] xRoots = xPoly.getRoots(); for (int x = 0; x < xRoots.length; x++) { double test = (a[0] * xRoots[x] + a[1] * yRoots[y] + a[3]) * xRoots[x] + (a[2] * yRoots[y] + a[4]) * yRoots[y] + a[5]; if (Math.abs(test) < norm0) { test = (b[0] * xRoots[x] + b[1] * yRoots[y] + b[3]) * xRoots[x] + (b[2] * yRoots[y] + b[4]) * yRoots[y] + b[5]; if (Math.abs(test) < norm1) { // FIXME compute angle in radians result.add(new IntersectionPoint(new Point2D.Double(xRoots[x], yRoots[y]), Double.NaN)); } } } } return new IntersectionResult(result.isEmpty() ? IntersectionStatus.NO_INTERSECTION : IntersectionStatus.INTERSECTION, result); } public static IntersectionResultEx intersectEllipseEllipseEx(double cx1, double cy1, double rx1, double ry1, double cx2, double cy2, double rx2, double ry2) { return intersectEllipseEllipseEx(cx1, cy1, rx1, ry1, cx2, cy2, rx2, ry2, Geom.REAL_THRESHOLD); } public static IntersectionResultEx intersectEllipseEllipseEx(double cx1, double cy1, double rx1, double ry1, double cx2, double cy2, double rx2, double ry2, double epsilon) { IntersectionResult result = intersectEllipseEllipse(cx1, cy1, rx1, ry1, cx2, cy2, rx2, ry2, epsilon); @NonNull List<IntersectionPointEx> list = new ArrayList<>(); for (IntersectionPoint ip : result) { double px = ip.getX(); double py = ip.getY(); list.add(new IntersectionPointEx(px, py, ip.getArgumentA(), py - cy1, cx1 - px, Double.NaN, py - cy2, cx2 - px// FIXME compute angle in radians )); } return new IntersectionResultEx(result.getStatus(), list); } }
39.680851
183
0.563896
c270cac10330f6aac7c69b9c8b20674b5bb97128
4,416
package chat.rocket.android.adapter; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import chat.rocket.android.R; import chat.rocket.android.helper.DateTime; import chat.rocket.android.widget.emotionkeyboard.utils.EmotionUtils; import chat.rocket.android.widget.emotionkeyboard.utils.SpanStringUtils; import chat.rocket.core.models.Mention; import chat.rocket.core.models.Message; /** * Created by helloworld on 2018/2/27 */ public class SearchChatAdapter extends RecyclerView.Adapter{ private Context mContext; private List<Message> allMessageByRoomId; private String mark; public void setDatas(List<Message> tempDataList, String mark) { if (tempDataList == null) { tempDataList = new ArrayList<>(); } this.mark = mark; allMessageByRoomId = tempDataList; notifyDataSetChanged(); } //自定义监听事件 public interface OnRecyclerViewItemClickListener { void onItemClick(View view, Message message); } private OnRecyclerViewItemClickListener mOnItemClickListener = null; public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) { mOnItemClickListener = listener; } public SearchChatAdapter(Context activity, List<Message> allMessageByRoomId) { this.mContext = activity; if(allMessageByRoomId == null){ allMessageByRoomId = new ArrayList<>(); } this.allMessageByRoomId = allMessageByRoomId; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_search_info, parent, false); return new ContentVH(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ContentVH vh = (ContentVH) holder; Message message = allMessageByRoomId.get(position); //给布局设置点击和长点击监听 holder.itemView.setOnClickListener(v -> { if(mOnItemClickListener!=null){ mOnItemClickListener.onItemClick(v, message); } }); String messageStr = message.getMessage(); if(messageStr.contains(mark)){ if (!TextUtils.isEmpty(messageStr)) { List<Mention> mentions=message.getMentions(); if(mentions!=null&&mentions.size()>0){ for (Mention mention:mentions){ int lastIndexOf=mention.getUsername().lastIndexOf("&"); if (lastIndexOf!=-1){ String name = mention.getUsername().substring(0, lastIndexOf); messageStr=messageStr.replace(mention.getUsername(),name); } } } } SpannableString sp= SpanStringUtils.getEmotionContent(EmotionUtils.EMOTION_CLASSIC_TYPE,mContext, vh.tvName,messageStr); SpannableString spannableString = new SpannableString(sp); int start = messageStr.indexOf(mark); spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#ff0000")), start, start+mark.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); vh.tvName.setText(spannableString); }else { vh.tvName.setText(messageStr); } vh.tv_time.setText(DateTime.fromEpocMs(message.getTimestamp(), DateTime.Format.DATE_TIME2)); String realName = message.getUser().getRealName(); vh.tv_from.setText(realName); } @Override public int getItemCount() { return allMessageByRoomId.size(); } private class ContentVH extends RecyclerView.ViewHolder { TextView tvName,tv_time,tv_from; public ContentVH(View itemView) { super(itemView); tvName = itemView.findViewById(R.id.tv_name); tv_time = itemView.findViewById(R.id.tv_time); tv_from = itemView.findViewById(R.id.tv_from); } } }
35.902439
152
0.664402
61a1042112d19deecd33fceac97f5e2f2a37a154
3,637
package xyz.devlxl.chaos.support.domainevents.notification; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import lombok.experimental.Accessors; import xyz.devlxl.chaos.base.JsonSerializationException; import xyz.devlxl.chaos.support.domain.DomainEvent; import xyz.devlxl.chaos.support.domain.StoredDomainEvent; /** * A notification of domain event * * @author Liu Xiaolei * @date 2018/09/06 */ @Data @Accessors(chain = true) public class Notification { private final static String F_N_OCCURRED_ON = "occurredOn"; /** * The domain event of this notification * <p> * Note:<br> * a command in notification is also a domain event. * <p> * <strong>Warning: <br> * This field's instance, should be an instance of {@link DomainEvent}, or can be converted into it.</strong> * * @see DomainEvent */ private Object event; /** * The time when the event occurred or when the command created */ private Date occurredOn; /** * The notification's ID, sometimes it equal to the stored event's ID */ private Long notificationId; /** * The event or command's type name, sometimes it equal to the class name of the event */ private String typeName; public static Notification fromStoredEvent(ObjectMapper objcetMapper, StoredDomainEvent storedEvent) { try { return new Notification() .setEvent(objcetMapper.readValue(storedEvent.eventBody(), Class.forName(storedEvent.className()))) .setOccurredOn(storedEvent.occurredOn()) .setNotificationId(storedEvent.eventId()) .setTypeName(storedEvent.className()); } catch (ClassNotFoundException | IOException e) { throw new JsonSerializationException(e); } } public static List<Notification> listFromStoredEvent(ObjectMapper objcetMapper, List<? extends StoredDomainEvent> storedEvents) { List<Notification> notifications = new ArrayList<>(storedEvents.size()); for (StoredDomainEvent storedEvent : storedEvents) { notifications.add(fromStoredEvent(objcetMapper, storedEvent)); } return notifications; } /** * Create a command notification from the original information of the command * * @param type the command type * @param parameters the command parameters. Optional, will defaults to empty map if not be provided. * @param occurredOn the time when the command created. Optional, will defaults to current time if not be provided. * @param notificationId the notification's id . Optional, will defaults to -1 if not be provided. * @return */ public static Notification fromCommandOriginalInfo(String type, Map<String, Object> parameters, Date occurredOn, Long notificationId) { checkNotNull(type); if (parameters == null) { parameters = new HashMap<>(); } if (occurredOn == null) { occurredOn = new Date(); } if (notificationId == null) { notificationId = -1L; } parameters.put(F_N_OCCURRED_ON, occurredOn); return new Notification() .setEvent(parameters) .setOccurredOn(occurredOn) .setNotificationId(notificationId) .setTypeName(type); } }
34.638095
119
0.668683
f51187ff821db9726f6eebe53ebf7c6d736ad3a6
4,719
package edu.fiuba.algo3.vista; import edu.fiuba.algo3.controlador.BotonEmpezarControlador; import edu.fiuba.algo3.controlador.BotonSalirControlador; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.media.AudioClip; import javafx.scene.media.Media; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.io.File; import java.net.URI; public class PantallaInicio { double xOffset; double yOffset; Stage primaryStage = new Stage(); private static AudioClip mediaPlayer; private void arrastrarVentana(Scene root, Stage primaryStage){ //para arrastar la ventana. root.setOnMousePressed(new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event){ xOffset = event.getSceneX(); yOffset = event.getSceneY(); } }); root.setOnMouseDragged(new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event){ primaryStage.setX(event.getScreenX() - xOffset); primaryStage.setY(event.getScreenY() - yOffset); } }); } public Stage initialize() { AudioClip musica; int alturaImagen = 640; int anchuraImagen = 640; int tamañoIcono = 30; //Imagenes e iconos Image icono = new Image((getClass().getResourceAsStream("/imagenes/iconos/globo.png"))); Image iconoPlay = new Image((getClass().getResourceAsStream("/imagenes/iconos/start_48px.png"))); Image iconoSalida = new Image((getClass().getResourceAsStream("/imagenes/iconos/exit_50px.png"))); Image fondo = new Image((getClass().getResourceAsStream("/imagenes/inicio/globo_teg_3.png"))); ImageView portada = new ImageView(fondo); ImageView imagenPlay = new ImageView(iconoPlay); ImageView imagenSalida = new ImageView(iconoSalida); imagenPlay.setFitHeight(tamañoIcono); imagenPlay.setFitWidth(tamañoIcono); imagenSalida.setFitHeight(tamañoIcono); imagenSalida.setFitWidth(tamañoIcono); Button botonEmpezar = new Button("Empezar Partida", imagenPlay); Button botonSalir = new Button("Salir", imagenSalida); Group panel = new Group(portada, botonEmpezar, botonSalir); Scene scene = new Scene(panel, alturaImagen, anchuraImagen); portada.setFitHeight(alturaImagen); portada.setFitWidth(anchuraImagen); primaryStage.getIcons().add(icono); //cambia el icono de ejecución //construcción de los botones botonEmpezar.setLayoutX(200); botonEmpezar.setLayoutY(310); botonEmpezar.setId("botonEmpezar"); botonEmpezar.setPrefWidth(230); botonEmpezar.setPrefHeight(35); botonEmpezar.setScaleX(1.5); botonEmpezar.setScaleY(1.7); botonEmpezar.setScaleZ(1.5); botonEmpezar.setOnAction(new BotonEmpezarControlador(primaryStage)); botonSalir.setLayoutX(400); botonSalir.setLayoutY(501); botonSalir.setId("botonSalir"); botonSalir.setPrefWidth(120); botonSalir.setPrefHeight(18); botonSalir.setScaleX(1.2); botonSalir.setScaleY(1.3); botonSalir.setOnAction(new BotonSalirControlador()); //transparencias primaryStage.initStyle(StageStyle.TRANSPARENT); //quita la vista de la ventana de windows. scene.setFill(Color.TRANSPARENT); //estilos String css = (getClass().getResource("/estilos/botones.css")).toExternalForm(); scene.getStylesheets().add(css); arrastrarVentana(scene, primaryStage); musica = reproductorDeMusica(); primaryStage.setScene(scene); return primaryStage; } public AudioClip reproductorDeMusica(){ String direccionMusicaInicio = "docs/battlefield-1942-soundtrack-main-theme-by-joel-eriksson.mp3"; File dir = new File(direccionMusicaInicio); URI path = dir.toURI(); String direccionParaMedia = path.toString(); Media musica = new Media(direccionParaMedia); mediaPlayer = new AudioClip(musica.getSource()); mediaPlayer.setCycleCount(AudioClip.INDEFINITE); reproducirMusica(); mediaPlayer.setVolume(1); return mediaPlayer; } private void reproducirMusica(){ mediaPlayer.play(); } public static void pararMusica(){ mediaPlayer.stop(); } }
32.321918
106
0.671752
9b19cbc97fd8f1635836c52e40c6d20ddb0ae555
7,947
package application.controllers; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.ResourceBundle; import application.business.abstracts.CarService; import application.business.abstracts.CustomerService; import application.business.abstracts.RentalService; import application.business.abstracts.UserService; import application.business.concretes.CarManager; import application.business.concretes.CustomerManager; import application.business.concretes.RentalManager; import application.business.concretes.UserManager; import application.controllers.addControllers.AddRentalController; import application.controllers.updateControllers.UpdateCarController; import application.dataAccess.concretes.HibernateCarDao; import application.dataAccess.concretes.HibernateCustomerDao; import application.dataAccess.concretes.HibernateRentalDao; import application.dataAccess.concretes.HibernateUserDao; import application.entities.DTOs.CarDetailDto; import application.entities.concretes.Car; import application.entities.concretes.LocalStorage; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.scene.input.KeyEvent; public class CarsController { UserService userService=new UserManager(new HibernateUserDao()); CarService carService=new CarManager(new HibernateCarDao()); RentalService rentalService=new RentalManager(new HibernateRentalDao()); CustomerService customerService=new CustomerManager(new HibernateCustomerDao()); @FXML private ResourceBundle resources; @FXML private URL location; @FXML private VBox userVBox; @FXML private Label lbl_totalUsers; @FXML private VBox carVBox; @FXML private Label lbl_totalCars; @FXML private VBox rentalVBox; @FXML private Label lbl_totalRentals; @FXML private VBox customerVBox; @FXML private Label lbl_totalCustomers; @FXML private VBox pnItems; @FXML private TextField txt_search; @FXML private HBox hBox_buttons; @FXML void txt_searchKeyPress(KeyEvent event) { pnItems.getChildren().clear(); String temp=txt_search.getText().toLowerCase(); this.getTable(carService.getCarDetailsByName(temp)); } public void getTable(List<CarDetailDto> car) { lbl_totalUsers.setText(String.valueOf(userService.getAll().size())); lbl_totalCars.setText(String.valueOf(carService.getAll().size())); lbl_totalRentals.setText(String.valueOf(rentalService.getAll().size())); lbl_totalCustomers.setText(String.valueOf(customerService.getAll().size())); Node[] nodes = new Node[car.size()]; for (int i = 0; i < nodes.length; i++) { try { final int j = i; FXMLLoader loader = new FXMLLoader(getClass().getResource("../fxml/Item.fxml")); nodes[i]=loader.load(); ItemController item=loader.getController(); item.setColumn(car.get(i).getCarname()); item.setColumn(car.get(i).getColorName()); item.setColumn(String.valueOf(car.get(i).getDailyPrice())); item.setColumn(String.valueOf(car.get(i).getModelYear())); item.setColumn(String.valueOf(car.get(i).getDescription())); for (String authority : LocalStorage.getAuthority()) { if (authority.equals("admin")) { item.setSuccessButton("Add", "../fxml/addPages/AddCar.fxml"); Button updateButton=item.setUpdateButton("Update",String.valueOf(car.get(i).getCarId())); updateButton.setOnAction(event->{ try { FXMLLoader updatePageLoader = new FXMLLoader(getClass().getResource("../fxml/updatePages/UpdateCar.fxml")); AnchorPane root = (AnchorPane)updatePageLoader.load(); UpdateCarController updateController=updatePageLoader.getController(); updateController.setSelected(String.valueOf(updateButton.getId())); Scene scene = new Scene(root,539,570); Stage primaryStage=new Stage(); primaryStage.getIcons().add(new Image("file:src/application/images/logo.png")); primaryStage.setTitle("Update"); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } }); Button deleteButton=item.setDangerButton("Delete"); deleteButton.setId(String.valueOf(car.get(i).getCarId())); deleteButton.setOnAction(event->{ Car temp=carService.get(Integer.valueOf(updateButton.getId())); carService.delete(temp); pnItems.getChildren().clear(); this.getTable(carService.getCarDetails()); }); } else if(authority.equals("member")){ Button addButton=item.setSuccessButton("Rent it", "../fxml/addPages/AddCar.fxml"); addButton.setId(String.valueOf(car.get(i).getCarId())); addButton.setOnAction(event->{ try { FXMLLoader addPageLoader = new FXMLLoader(getClass().getResource("../fxml/addPages/AddRental.fxml")); AnchorPane root = (AnchorPane)addPageLoader.load(); AddRentalController addController=addPageLoader.getController(); addController.setCarId(Integer.valueOf(addButton.getId())); Scene scene = new Scene(root,539,570); Stage primaryStage=new Stage(); primaryStage.getIcons().add(new Image("file:src/application/images/logo.png")); primaryStage.setTitle("Rental"); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } }); } } //give the items some effect nodes[i].setOnMouseEntered(event -> { nodes[j].setStyle("-fx-background-color : #0A0E3F"); }); nodes[i].setOnMouseExited(event -> { nodes[j].setStyle("-fx-background-color : #02030A"); }); pnItems.getChildren().add(nodes[i]); } catch (IOException e) { e.printStackTrace(); } } } public void setAddButton() { } @FXML void initialize() { this.getTable(carService.getCarDetails()); //this.setAddButton(); } }
35.797297
139
0.568768
0cc73136f19a732e5eb7468d8f3a8016b36a7b51
3,442
/** * 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.am.service; import io.gravitee.am.identityprovider.api.User; import io.gravitee.am.model.Form; import io.gravitee.am.model.ReferenceType; import io.gravitee.am.service.model.NewForm; import io.gravitee.am.service.model.UpdateForm; import io.reactivex.Completable; import io.reactivex.Maybe; import io.reactivex.Single; import java.util.List; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author Alexandre FARIA (contact at alexandrefaria.net) * @author GraviteeSource Team */ public interface FormService { Maybe<Form> findById(String id); Single<List<Form>> findAll(ReferenceType referenceType, String referenceId); Single<List<Form>> findByDomain(String domain); Single<List<Form>> findByClient(ReferenceType referenceType, String referenceId, String client); Single<List<Form>> findByDomainAndClient(String domain, String client); Maybe<Form> findByTemplate(ReferenceType referenceType, String referenceId, String template); Maybe<Form> findByDomainAndTemplate(String domain, String template); Maybe<Form> findByClientAndTemplate(ReferenceType referenceType, String referenceId, String client, String template); Maybe<Form> findByDomainAndClientAndTemplate(String domain, String client, String template); Single<List<Form>> copyFromClient(String domain, String clientSource, String clientTarget); Single<Form> create(ReferenceType referenceType, String referenceId, NewForm newForm, User principal); Single<Form> create(String domain, NewForm form, User principal); Single<Form> create(String domain, String client, NewForm form, User principal); Single<Form> update(ReferenceType referenceType, String referenceId, String id, UpdateForm updateForm, User principal); Single<Form> update(String domain, String id, UpdateForm form, User principal); Single<Form> update(String domain, String client, String id, UpdateForm form, User principal); Completable delete(ReferenceType referenceType, String referenceId, String formId, User principal); Completable delete(String domain, String pageId, User principal); default Single<Form> create(String domain, NewForm form) { return create(domain, form, null); } default Single<Form> create(String domain, String client, NewForm form) { return create(domain, client, form, null); } default Single<Form> update(String domain, String id, UpdateForm form) { return update(domain, id, form, null); } default Single<Form> update(String domain, String client, String id, UpdateForm form) { return update(domain, client, id, form, null); } default Completable delete(String domain, String pageId) { return delete(domain, pageId, null); } }
37.010753
123
0.748402
1e34ebeee3f6e4eae6f28beaf35f19fb49c04cef
392
package com.zachsthings.libcomponents; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used on Components which are not intended to be loaded (Abstract Components) */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface TemplateComponent { }
26.133333
79
0.811224
529768fad4ca3471a921542a3091a5c5ff70533e
1,046
package com.lambkit.core.registry.consul; import com.lambkit.Lambkit; import com.lambkit.core.registry.ServiceDiscovery; import com.lambkit.core.rpc.RpcConfig; import com.google.common.net.HostAndPort; import com.orbitz.consul.Consul; import com.orbitz.consul.HealthClient; public class ConsulServiceDiscovery implements ServiceDiscovery { private Consul consul; public void init() { RpcConfig config = Lambkit.config(RpcConfig.class); consul = Consul.builder().withHostAndPort(HostAndPort.fromString(config.getRegistryAddress())).build(); } @Override public String discover(String name) { // TODO Auto-generated method stub HealthClient client = consul.healthClient(); //获取所有服务 System.out.println(client.getAllServiceInstances(name).getResponse().size()); //获取所有正常的服务(健康检测通过的) client.getHealthyServiceInstances(name).getResponse().forEach((resp) -> { System.out.println(resp); }); return name; } }
30.764706
108
0.689293
fb4db1c7efae1b257c8bfb9e9590a771cbf99654
6,258
package org.janelia.jacs2.asyncservice.impl; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.StringUtils; import org.hibernate.lob.ReaderInputStream; import org.janelia.jacs2.asyncservice.utils.FileUtils; import org.janelia.jacs2.dataservice.persistence.JacsServiceDataPersistence; import org.janelia.model.jacs2.DataInterval; import org.janelia.model.jacs2.EntityFieldValueHandler; import org.janelia.model.jacs2.SetFieldValueHandler; import org.janelia.model.jacs2.page.PageRequest; import org.janelia.model.jacs2.page.PageResult; import org.janelia.model.service.JacsServiceData; import org.janelia.jacs2.asyncservice.JacsServiceDataManager; import org.janelia.model.service.JacsServiceState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Stream; public class JacsServiceDataManagerImpl implements JacsServiceDataManager { private static final Logger LOG = LoggerFactory.getLogger(JacsServiceDataManagerImpl.class); private final JacsServiceDataPersistence jacsServiceDataPersistence; @Inject public JacsServiceDataManagerImpl(JacsServiceDataPersistence jacsServiceDataPersistence) { this.jacsServiceDataPersistence = jacsServiceDataPersistence; } @Override public JacsServiceData retrieveServiceById(Number instanceId) { return jacsServiceDataPersistence.findServiceHierarchy(instanceId); } @Override public long countServices(JacsServiceData ref, DataInterval<Date> creationInterval) { return jacsServiceDataPersistence.countMatchingServices(ref, creationInterval); } @Override public PageResult<JacsServiceData> searchServices(JacsServiceData ref, DataInterval<Date> creationInterval, PageRequest pageRequest) { return jacsServiceDataPersistence.findMatchingServices(ref, creationInterval, pageRequest); } @Override public long getServiceStdOutputSize(JacsServiceData serviceData) { return getServiceOutputSize(serviceData.getOutputPath()); } @Override public long getServiceStdErrorSize(JacsServiceData serviceData) { return getServiceOutputSize(serviceData.getErrorPath()); } private Stream<Path> streamOutputDir(String outputDir) { if (StringUtils.isBlank(outputDir) || Files.notExists(Paths.get(outputDir))) { return Stream.of(); } else { return FileUtils.lookupFiles(Paths.get(outputDir), 1, "glob:**/*") .filter(outputPath -> Files.isRegularFile(outputPath)) .filter(outputPath -> { try { return !Files.isHidden(outputPath); } catch (IOException e) { LOG.error("Error reading hidden attribute for {}", outputPath); return false; } }) ; } } private long getServiceOutputSize(String outputDir) { return streamOutputDir(outputDir) .map(outputPath -> { try { return Files.size(outputPath); } catch (IOException e) { LOG.error("Error get the size of {}", outputPath, e); throw new UncheckedIOException(e); } }) .reduce((s1, s2) -> s1 + s2) .orElse(0L); } @Override public Stream<InputStream> streamServiceStdOutput(JacsServiceData serviceData) { return streamServiceOutputFiles(serviceData.getOutputPath()); } @Override public Stream<InputStream> streamServiceStdError(JacsServiceData serviceData) { return streamServiceOutputFiles(serviceData.getErrorPath()); } private Stream<InputStream> streamServiceOutputFiles(String outputDir) { return streamOutputDir(outputDir) .map(outputPath -> { try { return new ReaderInputStream(Files.newBufferedReader(outputPath)); } catch (IOException e) { LOG.error("Error streaming {}", outputPath, e); throw new UncheckedIOException(e); } }); } @Override public JacsServiceData updateService(Number instanceId, JacsServiceData serviceData) { JacsServiceData existingService = jacsServiceDataPersistence.findServiceHierarchy(instanceId); if (existingService == null) { return null; } Map<String, EntityFieldValueHandler<?>> updates = new LinkedHashMap<>(); if (serviceData.getState() != null) { updates.putAll(existingService.updateState(serviceData.getState())); } if (serviceData.getServiceTimeout() != null) { existingService.setServiceTimeout(serviceData.getServiceTimeout()); updates.put("serviceTimeout", new SetFieldValueHandler<>(serviceData.getServiceTimeout())); } if (StringUtils.isNotBlank(serviceData.getWorkspace())) { existingService.setWorkspace(serviceData.getWorkspace()); updates.put("workspace", new SetFieldValueHandler<>(serviceData.getWorkspace())); } if (!updates.isEmpty()) { jacsServiceDataPersistence.update(existingService, updates); } if (serviceData.getPriority() != null) { Map<JacsServiceData, Integer> newPriorities = existingService.getNewServiceHierarchyPriorities(serviceData.getPriority()); newPriorities.entrySet().forEach(sdpEntry -> { JacsServiceData sd = sdpEntry.getKey(); sd.setPriority(sdpEntry.getValue()); jacsServiceDataPersistence.update(sd, ImmutableMap.of("priority", new SetFieldValueHandler<>(sd.getPriority()))); }); } return existingService; } }
40.901961
138
0.664589
0cb70cf7ed64aa9e00776ffbe1382997078263f9
13,733
/** * Copyright (c) 2008-2019 Bird Dog Games, Inc. * * This file is part of Ardor3D. * * Ardor3D is free software: you can redistribute it and/or modify it * under the terms of its license which may be found in the accompanying * LICENSE file or at <https://git.io/fjRmv>. */ package com.ardor3d.scenegraph.shape; import java.io.IOException; import com.ardor3d.math.MathUtils; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.util.export.InputCapsule; import com.ardor3d.util.export.OutputCapsule; import com.ardor3d.util.geom.BufferUtils; public class Tube extends Mesh { private int _axisSamples; private int _radialSamples; private double _outerRadius; private double _innerRadius; private double _height; protected boolean _viewInside; /** * Constructor meant for Savable use only. */ public Tube() {} public Tube(final String name, final double outerRadius, final double innerRadius, final double height, final int axisSamples, final int radialSamples) { super(name); _outerRadius = outerRadius; _innerRadius = innerRadius; _height = height; _axisSamples = axisSamples; _radialSamples = radialSamples; allocateVertices(); } public Tube(final String name, final double outerRadius, final double innerRadius, final double height) { this(name, outerRadius, innerRadius, height, 2, 20); } private void allocateVertices() { final int verts = (2 * (_axisSamples + 1) * (_radialSamples + 1) + _radialSamples * 4); _meshData.setVertexBuffer(BufferUtils.createVector3Buffer(_meshData.getVertexBuffer(), verts)); _meshData.setNormalBuffer(BufferUtils.createVector3Buffer(_meshData.getNormalBuffer(), verts)); _meshData.setTextureBuffer(BufferUtils.createVector2Buffer(_meshData.getTextureBuffer(0), verts), 0); final int tris = (4 * _radialSamples * (1 + _axisSamples)); if (_meshData.getIndices() == null || _meshData.getIndices().getBufferLimit() != 3 * tris) { _meshData.setIndices(BufferUtils.createIndexBufferData(3 * tris, verts - 1)); } setGeometryData(); setIndexData(); } public int getAxisSamples() { return _axisSamples; } public void setAxisSamples(final int axisSamples) { _axisSamples = axisSamples; allocateVertices(); } public int getRadialSamples() { return _radialSamples; } public void setRadialSamples(final int radialSamples) { _radialSamples = radialSamples; allocateVertices(); } public double getOuterRadius() { return _outerRadius; } public void setOuterRadius(final double outerRadius) { _outerRadius = outerRadius; allocateVertices(); } public double getInnerRadius() { return _innerRadius; } public void setInnerRadius(final double innerRadius) { _innerRadius = innerRadius; allocateVertices(); } public double getHeight() { return _height; } public void setHeight(final double height) { _height = height; allocateVertices(); } private void setGeometryData() { _meshData.getVertexBuffer().rewind(); _meshData.getNormalBuffer().rewind(); _meshData.getTextureCoords(0).getBuffer().rewind(); final double inverseRadial = 1.0 / _radialSamples; final double axisStep = _height / _axisSamples; final double axisTextureStep = 1.0 / _axisSamples; final double halfHeight = 0.5 * _height; final double innerOuterRatio = _innerRadius / _outerRadius; final double[] sin = new double[_radialSamples]; final double[] cos = new double[_radialSamples]; for (int radialCount = 0; radialCount < _radialSamples; radialCount++) { final double angle = MathUtils.TWO_PI * inverseRadial * radialCount; cos[radialCount] = MathUtils.cos(angle); sin[radialCount] = MathUtils.sin(angle); } // outer cylinder for (int radialCount = 0; radialCount < _radialSamples + 1; radialCount++) { for (int axisCount = 0; axisCount < _axisSamples + 1; axisCount++) { _meshData.getVertexBuffer().put((float) (cos[radialCount % _radialSamples] * _outerRadius)) .put((float) (axisStep * axisCount - halfHeight)) .put((float) (sin[radialCount % _radialSamples] * _outerRadius)); if (_viewInside) { _meshData.getNormalBuffer().put((float) cos[radialCount % _radialSamples]).put(0) .put((float) sin[radialCount % _radialSamples]); } else { _meshData.getNormalBuffer().put((float) -cos[radialCount % _radialSamples]).put(0) .put((float) -sin[radialCount % _radialSamples]); } _meshData.getTextureCoords(0).getBuffer().put((float) (radialCount * inverseRadial)) .put((float) (axisTextureStep * axisCount)); } } // inner cylinder for (int radialCount = 0; radialCount < _radialSamples + 1; radialCount++) { for (int axisCount = 0; axisCount < _axisSamples + 1; axisCount++) { _meshData.getVertexBuffer().put((float) (cos[radialCount % _radialSamples] * _innerRadius)) .put((float) (axisStep * axisCount - halfHeight)) .put((float) (sin[radialCount % _radialSamples] * _innerRadius)); if (_viewInside) { _meshData.getNormalBuffer().put((float) -cos[radialCount % _radialSamples]).put(0) .put((float) -sin[radialCount % _radialSamples]); } else { _meshData.getNormalBuffer().put((float) cos[radialCount % _radialSamples]).put(0) .put((float) sin[radialCount % _radialSamples]); } _meshData.getTextureCoords(0).getBuffer().put((float) (radialCount * inverseRadial)) .put((float) (axisTextureStep * axisCount)); } } // bottom edge for (int radialCount = 0; radialCount < _radialSamples; radialCount++) { _meshData.getVertexBuffer().put((float) (cos[radialCount] * _outerRadius)).put((float) -halfHeight) .put((float) (sin[radialCount] * _outerRadius)); _meshData.getVertexBuffer().put((float) (cos[radialCount] * _innerRadius)).put((float) -halfHeight) .put((float) (sin[radialCount] * _innerRadius)); if (_viewInside) { _meshData.getNormalBuffer().put(0).put(1).put(0); _meshData.getNormalBuffer().put(0).put(1).put(0); } else { _meshData.getNormalBuffer().put(0).put(-1).put(0); _meshData.getNormalBuffer().put(0).put(-1).put(0); } _meshData.getTextureCoords(0).getBuffer().put((float) (0.5 + 0.5 * cos[radialCount])) .put((float) (0.5 + 0.5 * sin[radialCount])); _meshData.getTextureCoords(0).getBuffer().put((float) (0.5 + innerOuterRatio * 0.5 * cos[radialCount])) .put((float) (0.5 + innerOuterRatio * 0.5 * sin[radialCount])); } // top edge for (int radialCount = 0; radialCount < _radialSamples; radialCount++) { _meshData.getVertexBuffer().put((float) (cos[radialCount] * _outerRadius)).put((float) halfHeight) .put((float) (sin[radialCount] * _outerRadius)); _meshData.getVertexBuffer().put((float) (cos[radialCount] * _innerRadius)).put((float) halfHeight) .put((float) (sin[radialCount] * _innerRadius)); if (_viewInside) { _meshData.getNormalBuffer().put(0).put(-1).put(0); _meshData.getNormalBuffer().put(0).put(-1).put(0); } else { _meshData.getNormalBuffer().put(0).put(1).put(0); _meshData.getNormalBuffer().put(0).put(1).put(0); } _meshData.getTextureCoords(0).getBuffer().put((float) (0.5 + 0.5 * cos[radialCount])) .put((float) (0.5 + 0.5 * sin[radialCount])); _meshData.getTextureCoords(0).getBuffer().put((float) (0.5 + innerOuterRatio * 0.5 * cos[radialCount])) .put((float) (0.5 + innerOuterRatio * 0.5 * sin[radialCount])); } } private void setIndexData() { _meshData.getIndices().rewind(); final int outerCylinder = (_axisSamples + 1) * (_radialSamples + 1); final int bottomEdge = 2 * outerCylinder; final int topEdge = bottomEdge + 2 * _radialSamples; // inner cylinder for (int radialCount = 0; radialCount < _radialSamples; radialCount++) { for (int axisCount = 0; axisCount < _axisSamples; axisCount++) { final int index0 = axisCount + (_axisSamples + 1) * radialCount; final int index1 = index0 + 1; final int index2 = index0 + (_axisSamples + 1); final int index3 = index2 + 1; if (_viewInside) { _meshData.getIndices().put(index0).put(index1).put(index2); _meshData.getIndices().put(index1).put(index3).put(index2); } else { _meshData.getIndices().put(index0).put(index2).put(index1); _meshData.getIndices().put(index1).put(index2).put(index3); } } } // outer cylinder for (int radialCount = 0; radialCount < _radialSamples; radialCount++) { for (int axisCount = 0; axisCount < _axisSamples; axisCount++) { final int index0 = outerCylinder + axisCount + (_axisSamples + 1) * radialCount; final int index1 = index0 + 1; final int index2 = index0 + (_axisSamples + 1); final int index3 = index2 + 1; if (_viewInside) { _meshData.getIndices().put(index0).put(index2).put(index1); _meshData.getIndices().put(index1).put(index2).put(index3); } else { _meshData.getIndices().put(index0).put(index1).put(index2); _meshData.getIndices().put(index1).put(index3).put(index2); } } } // bottom edge for (int radialCount = 0; radialCount < _radialSamples; radialCount++) { final int index0 = bottomEdge + 2 * radialCount; final int index1 = index0 + 1; final int index2 = bottomEdge + 2 * ((radialCount + 1) % _radialSamples); final int index3 = index2 + 1; if (_viewInside) { _meshData.getIndices().put(index0).put(index2).put(index1); _meshData.getIndices().put(index1).put(index2).put(index3); } else { _meshData.getIndices().put(index0).put(index1).put(index2); _meshData.getIndices().put(index1).put(index3).put(index2); } } // top edge for (int radialCount = 0; radialCount < _radialSamples; radialCount++) { final int index0 = topEdge + 2 * radialCount; final int index1 = index0 + 1; final int index2 = topEdge + 2 * ((radialCount + 1) % _radialSamples); final int index3 = index2 + 1; if (_viewInside) { _meshData.getIndices().put(index0).put(index1).put(index2); _meshData.getIndices().put(index1).put(index3).put(index2); } else { _meshData.getIndices().put(index0).put(index2).put(index1); _meshData.getIndices().put(index1).put(index2).put(index3); } } } /** * * @return true if the normals are inverted to point into the torus so that the face is oriented for a viewer inside * the torus. false (the default) for exterior viewing. */ public boolean isViewFromInside() { return _viewInside; } /** * * @param viewInside * if true, the normals are inverted to point into the torus so that the face is oriented for a viewer * inside the torus. Default is false (for outside viewing) */ public void setViewFromInside(final boolean viewInside) { if (viewInside != _viewInside) { _viewInside = viewInside; setGeometryData(); setIndexData(); } } @Override public void write(final OutputCapsule capsule) throws IOException { super.write(capsule); capsule.write(getAxisSamples(), "axisSamples", 0); capsule.write(getRadialSamples(), "radialSamples", 0); capsule.write(getOuterRadius(), "outerRadius", 0); capsule.write(getInnerRadius(), "innerRadius", 0); capsule.write(getHeight(), "height", 0); capsule.write(_viewInside, "viewInside", false); } @Override public void read(final InputCapsule capsule) throws IOException { super.read(capsule); setAxisSamples(capsule.readInt("axisSamples", 0)); setRadialSamples(capsule.readInt("radialSamples", 0)); setOuterRadius(capsule.readDouble("outerRadius", 0)); setInnerRadius(capsule.readDouble("innerRadius", 0)); setHeight(capsule.readDouble("height", 0)); _viewInside = capsule.readBoolean("viewInside", false); } }
43.050157
120
0.589893
015278ad2e62ac83b836faf4d3306df00aeb434e
3,250
package com.proj.users.mentor; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.proj.Utils.DBClass; /** * Servlet implementation class MentorRegisterServlet */ @WebServlet("/MentorRegisterServlet") @MultipartConfig(maxFileSize = 16177215) public class MentorRegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MentorRegisterServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); PrintWriter out=response.getWriter(); try { // input stream of the upload file Part filePart=request.getPart("photo"); // obtains the upload file part in this multipart request InputStream inputStream=filePart.getInputStream(); if(filePart!=null){ // prints out some information for debugging System.out.println(filePart.getName()); System.out.println(filePart.getSize()); System.out.println(filePart.getContentType()); inputStream=filePart.getInputStream(); // obtains input stream of the upload file } out.println("inside POST method.."); out.println(request.getParameter("fname")); out.println(request.getParameter("lname")); out.println(request.getParameter("phn")); out.println(request.getParameter("email")); out.println(request.getParameter("domain")); Connection con=DBClass.DBConnectMethod(); PreparedStatement ps=con.prepareStatement("update mentor set fname=?,lname=?,phn=?,email=?,domain=?,pic=? where uname=?"); ps.setString(1,request.getParameter("fname")); ps.setString(2,request.getParameter("lname")); ps.setString(3,request.getParameter("phn")); ps.setString(4,request.getParameter("email")); ps.setString(5,request.getParameter("domain")); //ps.setBlob(6,inputStream); // fetches input stream of the upload file for the blob column ps.setBinaryStream(6,inputStream); ps.setString(7,request.getParameter("uname")); ps.executeUpdate(); response.sendRedirect("mentorprofile.jsp"); } catch (Exception e) { // TODO: handle exception out.println(e); } } }
33.163265
126
0.716
ab4f7c0e7128f9f59ad7dd4cb154818aca3fc6bd
2,583
/* * Copyright 2014-2016 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package azkaban.jobtype.javautils; import java.util.Arrays; import java.util.Objects; import org.apache.commons.lang.StringUtils; import azkaban.utils.Props; /** * Utilities for Validation */ public class ValidationUtils { public static void validateNotEmpty(String s, String name) { if (StringUtils.isEmpty(s)) { throw new IllegalArgumentException(name + " cannot be empty."); } } /** * Validates if all of the keys exist of none of them exist * * @throws IllegalArgumentException only if some of the keys exist */ public static void validateAllOrNone(Props props, String... keys) { Objects.requireNonNull(keys); boolean allExist = true; boolean someExist = false; for (String key : keys) { Object val = props.get(key); allExist &= val != null; someExist |= val != null; } if (someExist && !allExist) { throw new IllegalArgumentException( "Either all of properties exist or none of them should exist for " + Arrays .toString(keys)); } } /** * Validates all keys present in props */ public static void validateAllNotEmpty(Props props, String... keys) { for (String key : keys) { props.getString(key); } } public static void validateAtleastOneNotEmpty(Props props, String... keys) { boolean exist = false; for (String key : keys) { Object val = props.get(key); exist |= val != null; } if (!exist) { throw new IllegalArgumentException( "At least one of these keys should exist " + Arrays.toString(keys)); } } public static void validateSomeValuesNotEmpty(int notEmptyVals, String... vals) { int count = 0; for (String val : vals) { if (!StringUtils.isEmpty(val)) { count++; } } if (count != notEmptyVals) { throw new IllegalArgumentException( "Number of not empty vals " + count + " is not desired number " + notEmptyVals); } } }
28.7
90
0.661247
54dcb2572048f3b0afcc48fc8096d3da1e1f9bc1
1,418
/* * Copyright (c) 2018 stnetix.com. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, without warranties or * conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the * specific language governing permissions and limitations under the License. */ package com.stnetix.ariaddna.desktopgui.views; import java.io.IOException; import javafx.scene.Node; /** * Left pane views factory * * @author slonikmak */ public enum ViewsFactory { MAIN("/com/stentix/ariaddna/desktopgui/fxmlViews/main.fxml"), LEFT_TREE("/com/stentix/ariaddna/desktopgui/fxmlViews/treeViewLeftPane.fxml"), LEFT_MAIN("/com/stentix/ariaddna/desktopgui/fxmlViews/mainLeftPane.fxml"), LEFT_SETTINGS("/com/stentix/ariaddna/desktopgui/fxmlViews/settingsLeftPane.fxml"); public String path; ViewsFactory(String path) { this.path = path; } /** * * @param loader * @return node * @throws IOException */ public Node getNode(FXMLLoaderProvider loader) throws IOException { return loader.get(path).load(); } }
30.170213
86
0.715092