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
|
---|---|---|---|---|---|
de2787be682fc502f2bfc0a332978c82d3e4f68a | 3,617 | /*
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaaproject.kaa.client.channel.impl.transports;
import org.kaaproject.kaa.client.channel.ConfigurationTransport;
import org.kaaproject.kaa.client.configuration.ConfigurationHashContainer;
import org.kaaproject.kaa.client.configuration.ConfigurationProcessor;
import org.kaaproject.kaa.client.schema.SchemaProcessor;
import org.kaaproject.kaa.common.TransportType;
import org.kaaproject.kaa.common.endpoint.gen.ConfigurationSyncRequest;
import org.kaaproject.kaa.common.endpoint.gen.ConfigurationSyncResponse;
import org.kaaproject.kaa.common.endpoint.gen.SyncResponseStatus;
import org.kaaproject.kaa.common.hash.EndpointObjectHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* The default implementation of the {@link ConfigurationTransport}.
*
* @author Yaroslav Zeygerman
*/
public class DefaultConfigurationTransport extends AbstractKaaTransport
implements ConfigurationTransport {
private static final Logger LOG = LoggerFactory.getLogger(DefaultConfigurationTransport.class);
private boolean resyncOnly;
private ConfigurationHashContainer hashContainer;
private ConfigurationProcessor configProcessor;
private SchemaProcessor schemaProcessor;
@Override
public void setConfigurationHashContainer(ConfigurationHashContainer container) {
this.hashContainer = container;
}
@Override
public void setConfigurationProcessor(ConfigurationProcessor processor) {
this.configProcessor = processor;
}
@Override
public void setSchemaProcessor(SchemaProcessor processor) {
this.schemaProcessor = processor;
}
@Override
public ConfigurationSyncRequest createConfigurationRequest() {
if (clientState != null && hashContainer != null) {
EndpointObjectHash hash = hashContainer.getConfigurationHash();
ConfigurationSyncRequest request = new ConfigurationSyncRequest();
if (hash != null) {
request.setConfigurationHash(ByteBuffer.wrap(hash.getData()));
}
request.setResyncOnly(resyncOnly);
return request;
}
return null;
}
@Override
public void onConfigurationResponse(ConfigurationSyncResponse response) throws IOException {
if (clientState != null && configProcessor != null) {
ByteBuffer schemaBody = response.getConfSchemaBody();
if (schemaBody != null && schemaProcessor != null) {
schemaProcessor.loadSchema(schemaBody);
}
ByteBuffer confBody = response.getConfDeltaBody();
if (confBody != null) {
configProcessor.processConfigurationData(confBody,
response.getResponseStatus().equals(SyncResponseStatus.RESYNC));
}
syncAck(response.getResponseStatus());
LOG.info("Processed configuration response.");
}
}
@Override
protected TransportType getTransportType() {
return TransportType.CONFIGURATION;
}
@Override
public void setResyncOnly(boolean resyncOnly) {
this.resyncOnly = resyncOnly;
}
}
| 34.447619 | 97 | 0.761681 |
f7bf2e31e2b2fd2cd4b51c882e7ca14705f7e3a6 | 4,816 | package gherkin.formatter;
import static gherkin.util.FixJava.readResource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import gherkin.JSONParser;
import gherkin.deps.com.google.gson.Gson;
import gherkin.formatter.model.Comment;
import gherkin.formatter.model.DocString;
import gherkin.formatter.model.Feature;
import gherkin.formatter.model.Match;
import gherkin.formatter.model.Result;
import gherkin.formatter.model.Scenario;
import gherkin.formatter.model.Step;
import gherkin.formatter.model.Tag;
import java.io.PrintStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class JSONFormatterTest {
@Test
public void shouldNotCloseProvidedStreamInDone() {
PrintStream out = mock(PrintStream.class);
Formatter formatter = new JSONFormatter(out);
formatter.done();
verify(out, never()).close();
}
@Test
public void shouldFlushAndCloseProvidedStreamInClose() {
PrintStream out = mock(PrintStream.class);
Formatter formatter = new JSONFormatter(out);
formatter.close();
verify(out).flush();
verify(out).close();
}
@Test
public void should_roundtrip_this_json() {
// From json_parser_spec.rb
String json = readResource("/gherkin/formatter/model/complicated.json");
checkJson(json);
}
private void checkJson(String json) {
Appendable io = new StringBuilder();
JSONPrettyFormatter f = new JSONPrettyFormatter(io);
JSONParser p = new JSONParser(f, f);
p.parse(json);
f.done();
Gson gson = new Gson();
List expected = gson.fromJson(new StringReader(json), List.class);
List actual = gson.fromJson(new StringReader(io.toString()), List.class);
assertEquals(expected, actual);
}
@SuppressWarnings("rawtypes")
@Test
public void testOrderingOfCalls() {
StringBuilder stringBuilder = new StringBuilder();
JSONFormatter jsonFormatter = new JSONPrettyFormatter(stringBuilder);
Feature feature = new Feature(new ArrayList<Comment>(), new ArrayList<Tag>(), "", "Test Feature", "", 12, "");
jsonFormatter.feature(feature);
jsonFormatter.before(new Match(null, null), new Result("passed", 565L, ""));
Scenario scenario = new Scenario(new ArrayList<Comment>(), new ArrayList<Tag>(), "", "Test Scenario", "", 13, "");
jsonFormatter.scenario(scenario);
Step step1 = new Step(new ArrayList<Comment>(), "Given", "Step 1", 14, null, new DocString("", "", 52));
jsonFormatter.step(step1);
final byte[] data = new byte[] {1, 2, 3};
jsonFormatter.embedding("mime-type", data);
Step step2 = new Step(new ArrayList<Comment>(), "Given", "Step 2", 15, null, new DocString("", "", 52));
jsonFormatter.step(step2);
jsonFormatter.match(new Match(new ArrayList<Argument>(), "xx"));
Result step1Result = new Result("passed", 565L, "");
jsonFormatter.result(step1Result);
jsonFormatter.match(new Match(new ArrayList<Argument>(), "yy"));
Result step2Result = new Result("failed", 45L, "");
jsonFormatter.result(step2Result);
final byte[] data1 = new byte[] {4};
jsonFormatter.embedding("mime-type-2", data1);
jsonFormatter.done();
jsonFormatter.close();
Gson gson = new Gson();
List result = gson.fromJson(stringBuilder.toString(), List.class);
Map featureJson = (Map) result.get(0);
assertEquals(feature.getName(), featureJson.get("name"));
Map scenarioJson = (Map) ((List) featureJson.get("elements")).get(0);
assertEquals(scenario.getName(), scenarioJson.get("name"));
Map step1Json = (Map) ((List)scenarioJson.get("steps")).get(0);
assertEquals(step1.getName(), step1Json.get("name"));
List embeddings1 = (List)step1Json.get("embeddings");
assertNotNull(embeddings1);
assertEquals(embeddings1.size(), 1);
Map step2Json = (Map) ((List)scenarioJson.get("steps")).get(1);
assertEquals(step2.getName(), step2Json.get("name"));
List embeddings2 = (List)step2Json.get("embeddings");
assertNotNull(embeddings2);
assertEquals(embeddings2.size(), 1);
Map step1ResultJson = (Map) step1Json.get("result");
assertEquals(step1Result.getStatus(), step1ResultJson.get("status"));
Map step2ResultJson = (Map) step2Json.get("result");
assertEquals(step2Result.getStatus(), step2ResultJson.get("status"));
}
}
| 35.940299 | 122 | 0.664659 |
207ce311799ccd7b34b6b1ef20e54fa0c2a813a4 | 5,327 | /*
* The MIT License
*
* Copyright (c) 2017, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugin.gitea.client.api;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.ServiceLoader;
import jenkins.model.Jenkins;
import org.jenkinsci.plugin.gitea.client.spi.GiteaConnectionFactory;
/**
* Entry point to the Gitea client API for opening a {@link GiteaConnection}.
*/
public final class Gitea {
/**
* The {@link JsonIgnoreProperties#ignoreUnknown()} to use. (For production use this should always be {@code true},
* but during testing of API changes it can be changed to {@code false} so that the API can be verified as
* correctly implemented.
*/
public static final boolean IGNORE_UNKNOWN_PROPERTIES = true;
/**
* The URL of the Gitea server.
*/
@NonNull
private final String serverUrl;
/**
* The {@link ClassLoader} to resolve {@link GiteaConnectionFactory} implementations from.
*/
@CheckForNull
private ClassLoader classLoader;
/**
* The authentication to connect with.
*/
@NonNull
private GiteaAuth authentication = new GiteaAuthNone();
/**
* Private constructor.
*
* @param serverUrl the URL of the Gitea server.
*/
private Gitea(@NonNull String serverUrl) {
this.serverUrl = serverUrl;
}
/**
* Creates a new {@link Gitea}.
*
* @param serverUrl URL of the Gitea server.
* @return the {@link Gitea}.
*/
@NonNull
public static Gitea server(@NonNull String serverUrl) {
return new Gitea(serverUrl).jenkinsPluginClassLoader();
}
/**
* Specify the authentication to connect to the server with.
* @param authentication the authentication.
* @return {@code this} for method chaining.
*/
@NonNull
public Gitea as(@CheckForNull GiteaAuth authentication) {
this.authentication = authentication == null ? new GiteaAuthNone() : authentication;
return this;
}
@NonNull
public String serverUrl() {
return serverUrl;
}
@NonNull
public GiteaAuth as() {
return authentication;
}
@CheckForNull
public ClassLoader classLoader() {
return classLoader;
}
/**
* Sets the {@link ClassLoader} that the SPI implementation will be resolved from.
*
* @param classLoader the {@link ClassLoader}
* @return {@code this} for method chaining.
*/
public Gitea classLoader(@CheckForNull ClassLoader classLoader) {
this.classLoader = classLoader;
return this;
}
/**
* Opens a {@link GiteaConnection} to the Gitea server.
* @return the connection.
* @throws IOException if the connection could not be established.
* @throws InterruptedException if interrupted while opening the connection.
*/
@NonNull
public GiteaConnection open() throws IOException, InterruptedException {
ServiceLoader<GiteaConnectionFactory> loader = ServiceLoader.load(GiteaConnectionFactory.class, classLoader);
long priority = 0L;
GiteaConnectionFactory best = null;
for (GiteaConnectionFactory factory : loader) {
if (factory.canOpen(this)) {
long p = factory.priority(this);
if (best == null || p > priority) {
best = factory;
priority = p;
}
}
}
if (best != null) {
return best.open(this);
}
throw new IOException("No implementation for connecting to " + serverUrl);
}
public Gitea jenkinsPluginClassLoader() {
// HACK for Jenkins
// by rights this should be the context classloader, but Jenkins does not expose plugins on that
// so we need instead to use the uberClassLoader as that will have the implementations
Jenkins instance = Jenkins.getInstance();
classLoader = instance == null ? getClass().getClassLoader() : instance.getPluginManager().uberClassLoader;
// END HACK
return this;
}
}
| 33.929936 | 119 | 0.66942 |
ff84976cf3414047ed78c02e55f3d6f1ba4f4f4e | 4,081 | package aguapotable.presentacion.controladores;
import aguapotable.logica.entidades.Ciclo;
import aguapotable.logica.funciones.FCiclo;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import master.logica.entidades.Usuario;
import master.logica.servicios.ServiciosUsuario;
import recursos.Util;
@ManagedBean
@ViewScoped
public class ControladorCicloAP implements Serializable {
private List<Ciclo> lstCiclos;
private Ciclo objCiclo;
private Ciclo cicloSel;
private Usuario sessionUsuario;
private HttpServletRequest httpServletRequest;
private FacesContext faceContext;
public ControladorCicloAP() throws Exception {
objCiclo = new Ciclo();
obtenerCiclos();
sessionUsuario = new Usuario();
faceContext = FacesContext.getCurrentInstance();
httpServletRequest = (HttpServletRequest) faceContext.getExternalContext().getRequest();
}
@PostConstruct
public void init() {
obtenerSession();
}
public void obtenerSession() {
try {
int intIdUsuario = (int) getHttpServletRequest().getSession().getAttribute("idUsuario");
setSessionUsuario(ServiciosUsuario.buscarUsuarioDadoId(intIdUsuario));
System.out.println("Usuario Logueado: " + getSessionUsuario().getApellidos());
} catch (Exception e) {
System.out.println("public void obtenerSession() dice: " + e.getMessage());
/*
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, message);
*/
}
}
public void obtenerCiclos() {
try {
setLstCiclos(FCiclo.obtenerCiclos());
} catch (Exception e) {
Util.addErrorMessage(e.getMessage());
System.out.println("public void obtenerCiclos() dice: " + e.getMessage());
}
}
/**
* @return the lstCiclos
*/
public List<Ciclo> getLstCiclos() {
return lstCiclos;
}
/**
* @param lstCiclos the lstCiclos to set
*/
public void setLstCiclos(List<Ciclo> lstCiclos) {
this.lstCiclos = lstCiclos;
}
/**
* @return the objCiclo
*/
public Ciclo getObjCiclo() {
return objCiclo;
}
/**
* @param objCiclo the objCiclo to set
*/
public void setObjCiclo(Ciclo objCiclo) {
this.objCiclo = objCiclo;
}
/**
* @return the sessionUsuario
*/
public Usuario getSessionUsuario() {
return sessionUsuario;
}
/**
* @param sessionUsuario the sessionUsuario to set
*/
public void setSessionUsuario(Usuario sessionUsuario) {
this.sessionUsuario = sessionUsuario;
}
/**
* @return the httpServletRequest
*/
public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
}
/**
* @param httpServletRequest the httpServletRequest to set
*/
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
/**
* @return the faceContext
*/
public FacesContext getFaceContext() {
return faceContext;
}
/**
* @param faceContext the faceContext to set
*/
public void setFaceContext(FacesContext faceContext) {
this.faceContext = faceContext;
}
/**
* @return the cicloSel
*/
public Ciclo getCicloSel() {
return cicloSel;
}
/**
* @param cicloSel the cicloSel to set
*/
public void setCicloSel(Ciclo cicloSel) {
this.cicloSel = cicloSel;
}
}
| 27.02649 | 108 | 0.620926 |
1ceaba9d7aff7ba14c9b8cbd06dd2605b0dbe905 | 12,729 | /*
* Copyright 2007-2021, CIIC Guanaitong, Co., Ltd.
* All rights reserved.
*/
package com.ciicgat.grus.boot.autoconfigure.data;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.mybatis.spring.mapper.ClassPathMapperScanner;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.util.List;
/**
* Created by August.Zhou on 2019-04-03 14:58.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties({MybatisProperties.class, DbProperties.class})
@AutoConfigureAfter(GrusDataAutoConfiguration.class)
@AutoConfigureBefore({MybatisAutoConfiguration.class})
@Import(GrusInterceptors.class)
public class GrusMybatisAutoConfiguration implements InitializingBean {
private static final Logger LOGGER = LoggerFactory.getLogger(GrusMybatisAutoConfiguration.class);
private final MybatisProperties properties;
private final Interceptor[] interceptors;
private final ResourceLoader resourceLoader;
private final DatabaseIdProvider databaseIdProvider;
private final List<ConfigurationCustomizer> configurationCustomizers;
public GrusMybatisAutoConfiguration(MybatisProperties properties,
ObjectProvider<Interceptor[]> interceptorsProvider,
ResourceLoader resourceLoader,
ObjectProvider<DatabaseIdProvider> databaseIdProvider,
ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider) {
this.properties = properties;
this.interceptors = interceptorsProvider.getIfAvailable();
this.resourceLoader = resourceLoader;
this.databaseIdProvider = databaseIdProvider.getIfAvailable();
this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable();
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "grus.db", value = "read-write-separation", havingValue = "false", matchIfMissing = true)
public class DisableReadWriteSeparationAutoConfiguration {
@Bean(name = {"sqlSessionFactory", "writeSqlSessionFactory"})
@ConditionalOnMissingBean(name = "writeSqlSessionFactory")
public SqlSessionFactory writeSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception {
return createFactory(masterDataSource);
}
@Bean(name = {"sqlSessionTemplate", "writeSqlSessionTemplate"})
@ConditionalOnMissingBean(name = "writeSqlSessionTemplate")
public SqlSessionTemplate writeSqlSessionTemplate(@Qualifier("writeSqlSessionFactory") SqlSessionFactory writeSqlSessionFactory) {
return new SqlSessionTemplate(writeSqlSessionFactory);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "grus.db", value = "read-write-separation", havingValue = "true", matchIfMissing = false)
public class EnableReadWriteSeparationAutoConfiguration {
@Bean(name = {"sqlSessionFactory", "writeSqlSessionFactory"})
@Primary
@ConditionalOnMissingBean(name = {"writeSqlSessionFactory"})
public SqlSessionFactory writeSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception {
return createFactory(masterDataSource);
}
@Bean(name = {"sqlSessionTemplate", "writeSqlSessionTemplate"})
@Primary
@ConditionalOnMissingBean(name = "writeSqlSessionTemplate")
public SqlSessionTemplate writeSqlSessionTemplate(@Qualifier("writeSqlSessionFactory") SqlSessionFactory writeSqlSessionFactory) {
return new SqlSessionTemplate(writeSqlSessionFactory);
}
@Bean
@ConditionalOnMissingBean(name = "readSqlSessionFactory")
public SqlSessionFactory readSqlSessionFactory(@Qualifier("slaveDataSource") DataSource slaveDataSource) throws Exception {
return createFactory(slaveDataSource);
}
@Bean
@ConditionalOnMissingBean(name = "readSqlSessionTemplate")
public SqlSessionTemplate readSqlSessionTemplate(@Qualifier("readSqlSessionFactory") SqlSessionFactory readSqlSessionFactory) throws Exception {
return new SqlSessionTemplate(readSqlSessionFactory);
}
}
@Bean
@Primary
@ConditionalOnMissingBean(name = "transactionManager")
public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource masterDataSource) {
return new GrusDataSourceTransactionManager(masterDataSource);
}
public SqlSessionFactory createFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {
factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
applyConfiguration(factory);
if (this.properties.getConfigurationProperties() != null) {
factory.setConfigurationProperties(this.properties.getConfigurationProperties());
}
if (!ObjectUtils.isEmpty(this.interceptors)) {
factory.setPlugins(this.interceptors);
}
if (this.databaseIdProvider != null) {
factory.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (this.properties.getTypeAliasesSuperType() != null) {
factory.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
Resource[] resources = this.properties.resolveMapperLocations();
if (!ObjectUtils.isEmpty(resources)) {
factory.setMapperLocations(resources);
}
return factory.getObject();
}
private void applyConfiguration(SqlSessionFactoryBean factory) {
org.apache.ibatis.session.Configuration configuration = this.properties.getConfiguration();
if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
configuration = new org.apache.ibatis.session.Configuration();
}
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
for (ConfigurationCustomizer customizer : this.configurationCustomizers) {
customizer.customize(configuration);
}
}
factory.setConfiguration(configuration);
}
@Override
public void afterPropertiesSet() {
checkConfigFileExists();
}
private void checkConfigFileExists() {
if (this.properties.isCheckConfigLocation() && StringUtils.hasText(this.properties.getConfigLocation())) {
Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());
Assert.state(resource.exists(), "Cannot find config location: " + resource
+ " (please add config file or check your Mybatis configuration)");
}
}
/**
* This will just scan the same base package as Spring Boot does. If you want
* more power, you can explicitly use
* {@link org.mybatis.spring.annotation.MapperScan} but this will get typed
* mappers working correctly, out-of-the-box, similar to using Spring Data JPA
* repositories.
*/
public static class AutoConfiguredMapperScannerRegistrar
implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware {
private BeanFactory beanFactory;
private ResourceLoader resourceLoader;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
if (!AutoConfigurationPackages.has(this.beanFactory)) {
LOGGER.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
return;
}
LOGGER.debug("Searching for mappers annotated with @Mapper");
List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
if (LOGGER.isDebugEnabled()) {
packages.forEach(pkg -> LOGGER.debug("Using auto-configuration base package '{}'", pkg));
}
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
if (this.resourceLoader != null) {
scanner.setResourceLoader(this.resourceLoader);
}
scanner.setAnnotationClass(Mapper.class);
scanner.registerFilters();
scanner.doScan(StringUtils.toStringArray(packages));
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
/**
* {@link org.mybatis.spring.annotation.MapperScan} ultimately ends up
* creating instances of {@link MapperFactoryBean}. If
* {@link org.mybatis.spring.annotation.MapperScan} is used then this
* auto-configuration is not needed. If it is _not_ used, however, then this
* will bring in a bean registrar and automatically register components based
* on the same component-scanning path as Spring Boot itself.
*/
@org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
@Import({AutoConfiguredMapperScannerRegistrar.class})
@ConditionalOnMissingBean(MapperFactoryBean.class)
public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {
@Override
public void afterPropertiesSet() {
LOGGER.debug("No {} found.", MapperFactoryBean.class.getName());
}
}
}
| 44.506993 | 152 | 0.735957 |
a28831125b5b3cdb0672a0db98e87ce1eb5cfc72 | 359 | package testclasses.exceptions.invoke.invokestatic;
import it.oblive.annotations.NativeObfuscation;
public class ThrowInvokeStaticLong {
public ThrowInvokeStaticLong() {
}
public static long normalDiv(int a, int b) {
return a / b;
}
@NativeObfuscation
public int div(int a) {
return (int) normalDiv(a, 0);
}
}
| 18.894737 | 51 | 0.671309 |
dddc1fb86767d265748345cc815479cab031ece5 | 2,194 | /**
* Autogenerated by Thrift Compiler (0.9.1)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.pivotal.gemfirexd.thrift;
import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;
public enum FieldType implements org.apache.thrift.TEnum {
BOOLEAN(1),
BYTE(2),
SHORT(3),
INTEGER(4),
LONG(5),
FLOAT(6),
DOUBLE(7),
CHAR(8),
STRING(9),
DECIMAL(10),
TIMESTAMP(11),
BINARY(12),
REF(13),
BOOLEAN_ARRAY(14),
CHAR_ARRAY(15),
SHORT_ARRAY(16),
INT_ARRAY(17),
LONG_ARRAY(18),
FLOAT_ARRAY(19),
DOUBLE_ARRAY(20),
STRING_ARRAY(21),
ARRAY(22),
ARRAY_OF_BINARY(23),
PDX_OBJECT(24),
NATIVE_OBJECT(25);
private final int value;
private FieldType(int value) {
this.value = value;
}
/**
* Get the integer value of this enum value, as defined in the Thrift IDL.
*/
public int getValue() {
return value;
}
/**
* Find a the enum type by its integer value, as defined in the Thrift IDL.
* @return null if the value is not found.
*/
public static FieldType findByValue(int value) {
switch (value) {
case 1:
return BOOLEAN;
case 2:
return BYTE;
case 3:
return SHORT;
case 4:
return INTEGER;
case 5:
return LONG;
case 6:
return FLOAT;
case 7:
return DOUBLE;
case 8:
return CHAR;
case 9:
return STRING;
case 10:
return DECIMAL;
case 11:
return TIMESTAMP;
case 12:
return BINARY;
case 13:
return REF;
case 14:
return BOOLEAN_ARRAY;
case 15:
return CHAR_ARRAY;
case 16:
return SHORT_ARRAY;
case 17:
return INT_ARRAY;
case 18:
return LONG_ARRAY;
case 19:
return FLOAT_ARRAY;
case 20:
return DOUBLE_ARRAY;
case 21:
return STRING_ARRAY;
case 22:
return ARRAY;
case 23:
return ARRAY_OF_BINARY;
case 24:
return PDX_OBJECT;
case 25:
return NATIVE_OBJECT;
default:
return null;
}
}
}
| 18.913793 | 77 | 0.580219 |
5e0a5fdf4c69f4469aa71fe68f0e1c12b675d6b0 | 1,497 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Andrew
*/
public class TurnTo extends CommandBase {
double target = 0;
int stableLoops = 0;
public TurnTo(double angle) {
target = angle;
requires(drivetrain);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
// turn 180 degrees
double current = drivetrain.getAngle();
double error = current-target;
System.out.println(error);
if ( Math.abs(error) < 10 )
{
stableLoops++;
}
else
{
stableLoops = 0;
}
error *= -0.01;
drivetrain.setMotors(error, -error);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return stableLoops > 20;
}
// Called once after isFinished returns true
protected void end() {
drivetrain.setMotors(0, 0);
drivetrain.reset();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
| 23.761905 | 79 | 0.606546 |
5e7762740f7212a9cbe8870a8f44e3b5a458aeec | 4,994 | package edu.mayo.mprc.swift.params2;
import edu.mayo.mprc.MprcException;
import edu.mayo.mprc.database.Change;
import edu.mayo.mprc.unimod.ModSet;
import edu.mayo.mprc.workspace.User;
import java.util.List;
import java.util.Map;
/**
* Static version of ParamsDao - does not enable any modifications, only serves default test values.
*/
public final class MockParamsDao implements ParamsDao {
@Override
public List<IonSeries> ionSeries() {
return IonSeries.getInitial();
}
private void notModifiable() {
throw new MprcException("MockParamsDao is not modifiable, method not implemented");
}
@Override
public void addIonSeries(final IonSeries ionSeries, final Change creation) {
notModifiable();
}
@Override
public IonSeries updateIonSeries(final IonSeries ionSeries, final Change creation) {
notModifiable();
return null;
}
@Override
public void deleteIonSeries(final IonSeries ionSeries, final Change deletion) {
notModifiable();
}
@Override
public List<Instrument> instruments() {
return Instrument.getInitial();
}
@Override
public Instrument getInstrumentByName(final String name) {
for (final Instrument instrument : Instrument.getInitial()) {
if (instrument.getName().equals(name)) {
return instrument;
}
}
return null;
}
@Override
public Instrument addInstrument(final Instrument instrument, final Change change) {
notModifiable();
return null;
}
@Override
public Instrument updateInstrument(final Instrument instrument, final Change change) {
notModifiable();
return null;
}
@Override
public void deleteInstrument(final Instrument instrument, final Change change) {
notModifiable();
}
@Override
public List<Protease> proteases() {
return Protease.getInitial();
}
@Override
public Protease getProteaseByName(final String name) {
for (final Protease protease : Protease.getInitial()) {
if (protease.getName().equals(name)) {
return protease;
}
}
return null;
}
@Override
public void addProtease(final Protease protease, final Change change) {
notModifiable();
}
@Override
public Protease updateProtease(final Protease protease, final Change change) {
notModifiable();
return null;
}
@Override
public void deleteProtease(final Protease protease, final Change change) {
notModifiable();
}
@Override
public StarredProteins addStarredProteins(final StarredProteins starredProteins) {
notModifiable();
return null;
}
@Override
public ExtractMsnSettings addExtractMsnSettings(final ExtractMsnSettings extractMsnSettings) {
notModifiable();
return null;
}
@Override
public ScaffoldSettings addScaffoldSettings(final ScaffoldSettings scaffoldSettings) {
notModifiable();
return null;
}
@Override
public SearchEngineConfig addSearchEngineConfig(SearchEngineConfig config) {
notModifiable();
return null;
}
@Override
public EnabledEngines addEnabledEngineSet(Iterable<SearchEngineConfig> searchEngineConfigs) {
notModifiable();
return null;
}
@Override
public EnabledEngines addEnabledEngines(EnabledEngines engines) {
notModifiable();
return null;
}
@Override
public ModSet updateModSet(final ModSet modSet) {
notModifiable();
return null;
}
@Override
public SearchEngineParameters addSearchEngineParameters(final SearchEngineParameters parameters) {
notModifiable();
return null;
}
@Override
public SearchEngineParameters getSearchEngineParameters(final int key) {
return null;
}
@Override
public List<SavedSearchEngineParameters> savedSearchEngineParameters() {
return null;
}
@Override
public List<SavedSearchEngineParameters> savedSearchEngineParametersNoData() {
return null;
}
@Override
public SavedSearchEngineParameters getSavedSearchEngineParameters(final int key) {
return null;
}
@Override
public SavedSearchEngineParameters findSavedSearchEngineParameters(final String name) {
return null;
}
@Override
public SavedSearchEngineParameters addSavedSearchEngineParameters(final SavedSearchEngineParameters params, final Change change) {
notModifiable();
return null;
}
@Override
public void deleteSavedSearchEngineParameters(final SavedSearchEngineParameters params, final Change change) {
notModifiable();
}
@Override
public SavedSearchEngineParameters findBestSavedSearchEngineParameters(final SearchEngineParameters parameters, final User user) {
return null;
}
@Override
public SearchEngineParameters mergeParameterSet(final SearchEngineParameters ps) {
return null;
}
@Override
public void begin() {
}
@Override
public void commit() {
}
@Override
public void rollback() {
}
@Override
public String qualifyTableName(final String table) {
return table;
}
@Override
public String check() {
return null;
}
@Override
public void install(final Map<String, String> params) {
}
@Override
public boolean isRunning() {
return false;
}
@Override
public void start() {
}
@Override
public void stop() {
}
}
| 20.983193 | 131 | 0.761714 |
96844f978416e932af0adc4225065dba5370072a | 621 | /*
* DefaultEntity.java
*
* Copyright 2017-2018 BCS-Technologies. All Rights Reserved.
*
* This software is the proprietary information of BCS-Technologies.
* Use is subject to license terms.
*/
package com.bcs.bm.catalog_of_instruments_rudata.repositories.entities;
import java.time.LocalDateTime;
public interface DefaultEntity {
String getId();
String getPrimaryKey();
void setId(String id);
String getClazz();
void setClazz(String type);
LocalDateTime getUpdatedate();
LocalDateTime getImporttime();
void setImporttime(LocalDateTime importtime);
default void init() {}
}
| 24.84 | 71 | 0.73591 |
d86ef957c09d62982b11333e738c30242eccaa67 | 4,006 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uipacontroleadotantes.gui.adotantes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import uipacontroleadotantes.banco.adotantes.AdotantesBean.AdotantesBean;
/**
*
* @author mckatoo
*/
public class AdotantesTableModel extends AbstractTableModel {
private final List<AdotantesBean> dados = new ArrayList<>();
private final String[] colunas = {"CÓDIGO", "NOME", "TELEFONE", "CELULAR", "ENDEREÇO", "BAIRRO", "CIDADE", "UF", "CPF", "RG", "SEXO", "EMAIL"};
@Override
public String getColumnName(int column) {
return colunas[column];
}
@Override
public int getRowCount() {
return dados.size();
}
@Override
public int getColumnCount() {
return colunas.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0:
return dados.get(rowIndex).getCodAdotante();
case 1:
return dados.get(rowIndex).getNome();
case 2:
return dados.get(rowIndex).getTelefone();
case 3:
return dados.get(rowIndex).getCelular();
case 4:
return dados.get(rowIndex).getEndereco();
case 5:
return dados.get(rowIndex).getBairro();
case 6:
return dados.get(rowIndex).getCidade();
case 7:
return dados.get(rowIndex).getUF();
case 8:
return dados.get(rowIndex).getCPF();
case 9:
return dados.get(rowIndex).getRG();
case 10:
return "" + Arrays.toString(dados.get(rowIndex).getSexo()).charAt(1);
case 11:
return dados.get(rowIndex).getEmail();
}
return null;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0:
dados.get(rowIndex).setCodAdotante(Integer.parseInt((String) aValue));
break;
case 1:
dados.get(rowIndex).setNome((String) aValue);
break;
case 2:
dados.get(rowIndex).setTelefone((String) aValue);
break;
case 3:
dados.get(rowIndex).setCelular((String) aValue);
break;
case 4:
dados.get(rowIndex).setEndereco((String) aValue);
break;
case 5:
dados.get(rowIndex).setBairro((String) aValue);
break;
case 6:
dados.get(rowIndex).setCidade((String) aValue);
break;
case 7:
dados.get(rowIndex).setUF((String) aValue);
break;
case 8:
dados.get(rowIndex).setCPF((String) aValue);
break;
case 9:
dados.get(rowIndex).setRG((String) aValue);
break;
case 10:
dados.get(rowIndex).setSexo(((String) aValue).toCharArray());
break;
case 11:
dados.get(rowIndex).setEmail((String) aValue);
break;
}
this.fireTableRowsUpdated(rowIndex, rowIndex);
}
public void addRow(AdotantesBean adotante) {
this.dados.add(adotante);
this.fireTableDataChanged();
}
public void removeRow(int linha) {
this.dados.remove(linha);
this.fireTableRowsDeleted(linha, linha);
}
public void limpar(){
for (int i = this.getRowCount() - 1; i > -1; i--) {
this.removeRow(i);
}
}
}
| 31.054264 | 147 | 0.537943 |
e2e531781f9da2356b26233cd255b9038bdd4761 | 1,471 | import java.util.Calendar;
import java.util.TimeZone;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("gx")
public class class204 {
@ObfuscatedName("qy")
@ObfuscatedGetter(
longValue = 697021873402356309L
)
static long field2603;
@ObfuscatedName("t")
public static final String[][] field2605;
@ObfuscatedName("q")
public static final String[] field2602;
@ObfuscatedName("i")
public static Calendar field2606;
@ObfuscatedName("fk")
static byte[][] field2601;
static {
field2605 = new String[][]{{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}, {"Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"}};
field2602 = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
Calendar.getInstance(TimeZone.getTimeZone("Europe/London"));
field2606 = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
}
@ObfuscatedName("a")
@ObfuscatedSignature(
signature = "(I)V",
garbageValue = "27015928"
)
public static void method3854() {
Varbit.varbits.reset();
}
@ObfuscatedName("js")
@ObfuscatedSignature(
signature = "(I)V",
garbageValue = "-1932277581"
)
static final void method3855() {
Client.field892 = Client.cycleCntr;
ScriptState.field726 = true;
}
}
| 30.020408 | 205 | 0.639701 |
73b2bde63d00796a6df216985ea5289dfa96c54c | 5,307 | package com.ebr163.probetools;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.PreferenceManager;
import com.ebr163.probetools.http.IProbeHttpInterceptor;
import com.ebr163.probetools.manager.AssetsManager;
import com.ebr163.probetools.manager.BaseManager;
import com.ebr163.probetools.manager.DBManager;
import com.ebr163.probetools.manager.HttpInterceptManager;
import com.ebr163.probetools.manager.IndexManager;
import com.ebr163.probetools.manager.ManagerFactory;
import com.ebr163.probetools.manager.PreferencesManager;
import com.ebr163.probetools.manager.TransitionManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import fi.iki.elonen.NanoHTTPD;
public final class Router {
private Map<Class<? extends BaseManager>, BaseManager> managers = new HashMap<>();
private ManagerFactory managerFactory;
private Context context;
private SharedPreferences preferences;
private Map<String, SQLiteOpenHelper> databases;
private IProbeHttpInterceptor httpInterceptor;
Router(Context context) {
this.context = context;
managers = new HashMap<>();
managerFactory = new ManagerFactory();
databases = new LinkedHashMap<>();
}
private ManagerFactory getManagerFactory() {
return managerFactory;
}
private <T extends BaseManager> T create(Class<T> controller) {
return getManagerFactory().build(context, controller);
}
public <T extends BaseManager> T registerController(T manager) {
managers.put(manager.getClass(), manager);
return (T) manager.setRouter(this);
}
public <T extends BaseManager> T getManager(Class<T> manager) {
if (!managers.containsKey(manager)) {
return registerController(create(manager));
}
return (T) managers.get(manager);
}
public void setPreferences(SharedPreferences preferences) {
this.preferences = preferences;
}
public SharedPreferences getPreferences() {
if (preferences == null) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
return preferences;
}
public SQLiteOpenHelper getSqLiteOpenHelper(String name) {
return databases.get(name);
}
void putDatabase(String name, SQLiteOpenHelper sqLiteOpenHelper) {
databases.put(name, sqLiteOpenHelper);
}
void setHttpInterceptor(IProbeHttpInterceptor httpInterceptor) {
this.httpInterceptor = httpInterceptor;
}
public List<String> getDatabaseNames() {
return new ArrayList<>(databases.keySet());
}
public IProbeHttpInterceptor getProbeHttpInterceptor() {
return httpInterceptor;
}
NanoHTTPD.Response route(NanoHTTPD.IHTTPSession session) throws Exception {
if (session.getUri().contains(".html") && "GET".equals(session.getMethod().name())) {
return getManager(TransitionManager.class).transition(session);
} else if (session.getUri().matches("/assets/.*")) {
return getManager(AssetsManager.class).asset(session);
} else if (session.getUri().matches("/") && "GET".equals(session.getMethod().name())) {
return getManager(IndexManager.class).transition(session);
} else if (session.getUri().matches("/db/download/database") && "GET".equals(session.getMethod().name())) {
return getManager(DBManager.class).download(session);
} else if (session.getUri().matches("/preferences/loadAll") && "GET".equals(session.getMethod().name())) {
return getManager(PreferencesManager.class).loadAllPreferences(session);
} else if (session.getUri().matches("/addPreference") && "POST".equals(session.getMethod().name())) {
return getManager(PreferencesManager.class).addPreference(session);
} else if (session.getUri().matches("/loadTableNames") && "GET".equals(session.getMethod().name())) {
return getManager(DBManager.class).loadAllTableNames(session);
} else if (session.getUri().matches("/loadTable") && "GET".equals(session.getMethod().name())) {
return getManager(DBManager.class).loadTable(session);
} else if (session.getUri().matches("/runSQL") && "POST".equals(session.getMethod().name())) {
return getManager(DBManager.class).runSQL(session);
} else if (session.getUri().matches("/loadDatabases") && "GET".equals(session.getMethod().name())) {
return getManager(DBManager.class).loadDatabases(session);
} else if (session.getUri().contains("database") && "GET".equals(session.getMethod().name())) {
return getManager(DBManager.class).transition(session);
} else if (session.getUri().contains("/http/request") && "GET".equals(session.getMethod().name())) {
return getManager(HttpInterceptManager.class).getRequestData(session);
} else if (session.getUri().contains("/http/response") && "GET".equals(session.getMethod().name())) {
return getManager(HttpInterceptManager.class).getResponseData(session);
}
return null;
}
}
| 41.787402 | 115 | 0.693235 |
b6413f3d830b626379e97104b21bbdf221e96b3c | 1,753 | package com.runer.toumai.dao;
import android.content.Context;
import com.fasterxml.jackson.databind.JsonNode;
import com.orhanobut.logger.Logger;
import com.runer.net.JsonUtil;
import com.runer.net.RequestCode;
import com.runer.net.interf.INetResult;
import com.runer.toumai.bean.AliPayResultBean;
import com.runer.toumai.bean.WechatPayBean;
import com.runer.toumai.net.NetInter;
import com.runer.toumai.net.RunerBaseRequest;
import com.runer.toumai.net.RunnerParam;
import java.io.IOException;
/**
* Created by szhua on 2017/9/1/001.
* github:https://github.com/szhua
* TouMaiNetApp
* PayDao
*/
public class PayDao extends RunerBaseRequest {
private WechatPayBean wechatPayBean ;
public WechatPayBean getWechatPayBean() {
return wechatPayBean;
}
private AliPayResultBean aliPayResultBean ;
public AliPayResultBean getAliPayResultBean() {
return aliPayResultBean;
}
public PayDao(Context context, INetResult iNetResult) {
super(context, iNetResult);
}
@Override
public void onRequestSuccess(JsonNode result, int requestCode) throws IOException {
if(requestCode==RequestCode.AliPay){
aliPayResultBean = JsonUtil.node2pojo(result,AliPayResultBean.class) ;
}else if(requestCode==RequestCode.WEchatPay){
wechatPayBean =JsonUtil.node2pojo(result,WechatPayBean.class);
}
}
public void aliPay(String id){
RunnerParam param =new RunnerParam() ;
param.put("id",id);
request(NetInter.aliPay,param, RequestCode.AliPay);
}
public void wechatPay(String id){
RunnerParam param =new RunnerParam() ;
param.put("id",id) ;
request(NetInter.wechatPay,param,RequestCode.WEchatPay);
}
}
| 31.303571 | 87 | 0.72105 |
b08a12d081579208bdad62a7f7dbbd2619d22cf1 | 831 | package concurrent;
/**
* A Runnable class used to test the performance of each concurrent ListSet
* implementation. This thread simply hits the list with a large number of
* remove.
*/
public class RemoveTestThread extends TestThread implements Runnable {
private int nSuccessful = 0;
private int nFailed = 0;
public RemoveTestThread(final SequenceGenerator seq, final int seqToUse, final ListSet setL) {
super(seq, seqToUse, setL);
}
@Override
public void run() {
for (int i = 0; i < nums.length; i++) {
if (l.remove(nums[i])) {
nSuccessful++;
} else {
nFailed++;
}
}
}
public int getNSuccessful() {
return nSuccessful;
}
public int getNFailed() {
return nFailed;
}
}
| 23.742857 | 98 | 0.593261 |
e00b10dd3cd55da1838b09b973a4fe221e887035 | 181 | package org.dao.generator.base;
/**
*
* @author <a href=mailto:[email protected]>lazyp</a>
*
*/
public interface DBHandler {
public TableMeta getTableMeta(String tableName);
}
| 16.454545 | 50 | 0.701657 |
4d59dbe7aced4b4c405a9cd267aa1d1a5cbbf3e4 | 897 | package io.bdeploy.common.cli.data;
import java.util.ArrayList;
import java.util.List;
/**
* Builds a table row cell by cell.
*/
public class DataTableRowBuilder {
private final DataTable target;
private final List<DataTableCell> cells = new ArrayList<>();
DataTableRowBuilder(DataTable target) {
this.target = target;
}
/**
* @param data a cell to add. If the cell is a {@link DataTableCell} it is applied as is, otherwise {@link #toString()} is
* called on the data.
*/
public DataTableRowBuilder cell(Object data) {
if (data instanceof DataTableCell) {
cells.add((DataTableCell) data);
} else {
cells.add(new DataTableCell(data != null ? data.toString() : ""));
}
return this;
}
public DataTable build() {
target.row(cells);
return target;
}
} | 24.916667 | 126 | 0.608696 |
4aca27c9b16010345f15cde9a32e9dada95a0971 | 1,387 | package com.gwac.action;
import com.gwac.dao.MultimediaResourceDao;
import com.gwac.model.MultimediaResource;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.Result;
@Result(name = "error", location = "/error.jsp")
@ExceptionMapping(exception = "java.lang.Exception", result = "error")
public class GetAlarmList extends ActionSupport {
private static final long serialVersionUID = -3454448234588641394L;
private static final Log log = LogFactory.getLog(GetAlarmList.class);
@Resource
private MultimediaResourceDao mrDao;
/**
* 返回结果
*/
private List<MultimediaResource> multimediaResources;
@Actions({
@Action(value = "/get-ot-alarm", results = {
@Result(name = "json", type = "json")})
})
@SuppressWarnings("unchecked")
public String execute() throws Exception {
multimediaResources = mrDao.findAll();
return "json";
}
/**
* @return the multimediaResources
*/
public List<MultimediaResource> getMultimediaResources() {
return multimediaResources;
}
}
| 28.895833 | 71 | 0.756309 |
57ef122faf1e2a4da69d227aea157fa54063c9b6 | 493 | /**
* An activity for a Respondent while he is waiting to be connected to someone
* */
package com.test.glasgowteam12.Activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.test.glasgowteam12.R;
public class RespondentCallWait extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_respondent_call_wait);
}
}
| 23.47619 | 78 | 0.762677 |
a5d75597196ae3f0d8fbcd84872471787e81d5d3 | 2,728 | package com.mohsinkd786.projection;
import com.mohsinkd786.entity.BankAccount;
import com.mohsinkd786.event.AccountCreatedEvent;
import com.mohsinkd786.event.MoneyCreditedEvent;
import com.mohsinkd786.event.MoneyDebitedEvent;
import com.mohsinkd786.exception.AccountNotFoundException;
import com.mohsinkd786.query.FindBankAccountQuery;
import com.mohsinkd786.repository.BankAccountRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.queryhandling.QueryHandler;
import org.axonframework.queryhandling.QueryUpdateEmitter;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Slf4j
@RequiredArgsConstructor
@Component
public class BankAccountProjection {
private final BankAccountRepository repository;
private final QueryUpdateEmitter updateEmitter;
@EventHandler
public void on(AccountCreatedEvent event) {
log.debug("Handling a Bank Account creation command {}", event.getId());
BankAccount bankAccount = new BankAccount(
event.getId(),
event.getOwner(),
event.getInitialBalance()
);
this.repository.save(bankAccount);
}
@EventHandler
public void on(MoneyCreditedEvent event) throws AccountNotFoundException {
log.debug("Handling a Bank Account Credit command {}", event.getId());
Optional<BankAccount> optionalBankAccount = this.repository.findById(event.getId());
if (optionalBankAccount.isPresent()) {
BankAccount bankAccount = optionalBankAccount.get();
bankAccount.setBalance(bankAccount.getBalance().add(event.getCreditAmount()));
this.repository.save(bankAccount);
} else {
throw new AccountNotFoundException(event.getId());
}
}
@EventHandler
public void on(MoneyDebitedEvent event) throws AccountNotFoundException {
log.debug("Handling a Bank Account Debit command {}", event.getId());
Optional<BankAccount> optionalBankAccount = this.repository.findById(event.getId());
if (optionalBankAccount.isPresent()) {
BankAccount bankAccount = optionalBankAccount.get();
bankAccount.setBalance(bankAccount.getBalance().subtract(event.getDebitAmount()));
this.repository.save(bankAccount);
} else {
throw new AccountNotFoundException(event.getId());
}
}
@QueryHandler
public BankAccount handle(FindBankAccountQuery query) {
log.debug("Handling FindBankAccountQuery query: {}", query);
return this.repository.findById(query.getAccountId()).orElse(null);
}
}
| 38.422535 | 94 | 0.723607 |
25382c41a902fe7295d076019cb9702ace785b81 | 156 | package io.github.codejanovic.functions.map;
public interface MapFunction3<From1, From2, From3, To> {
To map(From1 from1, From2 from2, From3 from3);
}
| 26 | 56 | 0.75 |
bf39b23fb63de3a6c5e4dee5251013dd4a35336f | 1,037 | import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int soma = 0, somaM = 0, somaF = 0, contM = 0, contF = 0, contJ = 0;
for (int x = 0; x < 3; x++) {
System.out.println("Digite o sexo: ");
int sexo = entrada.nextInt();
System.out.println("Digite a idade: ");
int idade = entrada.nextInt();
System.out.println("Digite a altura: ");
int altura = entrada.nextInt();
soma += idade;
if (sexo == 1) {
somaM += idade;
contM++;
} else if (sexo == 0) {
somaF += altura;
contF++;
}
if (idade >= 18 && idade <= 35) contJ++;
}
System.out.println("Média da idade (geral) " + ((double)soma / 3));
System.out.println("Média da altura (feminino) " + ((double)somaF / contF));
System.out.println("Média da idade (masculino) " + ((double)somaM / contM));
System.out.println("Percentual de pessoas com idade entre 18-35 anos: " + (100 / 3 * (double)contJ));
}
}
//https://pt.stackoverflow.com/q/319183/101
| 32.40625 | 103 | 0.610415 |
ae7374ab2a9a43f5ad96bddd5614e076be68714d | 1,749 | package com.yeamy.pattern.feature.demo;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.Toast;
import com.yeamy.pattern.data.DemoBean;
import com.yeamy.pattern.task.HttpRequest;
import com.yeamy.pattern.task.TaskCallback;
import com.yeamy.pattern.task.TaskExecutor;
/**
* 处理APP的业务逻辑,实现View的"业务逻辑实现"接口和任务的"结果回调"接口
*/
public class DemoActivity extends Activity implements DemoView.ActionImpl, TaskCallback<DemoBeanRequest> {
private DemoView contentView = new DemoView(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(contentView.createView(this, savedInstanceState));
contentView.showBean(new DemoBean("NULL", 1));
}
@Override
public void actionBack() {
TaskExecutor.execute(new HttpRequest(), new TaskCallback<HttpRequest>() {
@Override
public void onSuccess(HttpRequest request) {
finish();
}
@Override
public void onError(HttpRequest request) {
finish();
}
});
}
@Override
public void showName() {
TaskExecutor.execute(new DemoBeanRequest(), this);
}
@Override
public void onSuccess(DemoBeanRequest request) {
if (request.isSuccess()) {
contentView.showBean(request.bean);
} else {
showToast(request.bean.msg);
}
}
@Override
public void onError(DemoBeanRequest request) {
showToast("失败");
}
private void showToast(CharSequence msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
| 27.328125 | 106 | 0.656375 |
49d9106ead853af81ebdc429bc7920bf435a7d93 | 8,090 | /*
Copyright (c) 2012 Aaron Perkins
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package jmeplanet;
import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.light.DirectionalLight;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.post.filters.BloomFilter;
import com.jme3.post.filters.FogFilter;
import com.jme3.renderer.Camera;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.shadow.CompareMode;
import com.jme3.shadow.DirectionalLightShadowRenderer;
import com.jme3.shadow.EdgeFilteringMode;
import java.util.ArrayList;
import java.util.List;
/**
* PlanetAppState
*
*/
public class PlanetAppState extends AbstractAppState {
protected Application app;
protected List<Planet> planets;
protected Planet nearestPlanet;
protected FilterPostProcessor nearFilter;
protected FilterPostProcessor farFilter;
protected FogFilter nearFog;
protected FogFilter farFog;
protected BloomFilter farBloom;
protected Spatial scene;
protected DirectionalLight sun;
protected ViewPort nearViewPort;
protected ViewPort farViewPort;
protected Camera nearCam;
protected Camera farCam;
protected boolean shadowsEnabled;
protected DirectionalLightShadowRenderer dlsr;
public PlanetAppState(Spatial scene, DirectionalLight sun) {
this.scene = scene;
this.sun = sun;
this.planets = new ArrayList<Planet>();
}
@Override
public void initialize(AppStateManager stateManager, Application app) {
super.initialize(stateManager, app);
this.app = app;
farViewPort = app.getViewPort();
farCam = app.getCamera();
nearCam = this.farCam.clone();
nearCam.setFrustumPerspective(45f, (float)nearCam.getWidth()/nearCam.getHeight(), 1f, 310f);
farCam.setFrustumPerspective(45f, (float)farCam.getWidth()/farCam.getHeight(), 300f, 1e7f);
nearCam.setViewPort(0f, 1f, 0.0f, 1.0f);
nearViewPort = this.app.getRenderManager().createMainView("NearView", nearCam);
nearViewPort.setBackgroundColor(ColorRGBA.BlackNoAlpha);
nearViewPort.setClearFlags(false, true, true);
nearViewPort.attachScene(this.scene);
nearFilter=new FilterPostProcessor(app.getAssetManager());
nearViewPort.addProcessor(nearFilter);
nearFog = new FogFilter();
//nearFilter.addFilter(nearFog);
farFilter=new FilterPostProcessor(app.getAssetManager());
farViewPort.addProcessor(farFilter);
farFog = new FogFilter();
farFilter.addFilter(farFog);
farBloom=new BloomFilter();
farBloom.setDownSamplingFactor(2);
farBloom.setBlurScale(1.37f);
farBloom.setExposurePower(3.30f);
farBloom.setExposureCutOff(0.1f);
farBloom.setBloomIntensity(1.45f);
farFilter.addFilter(farBloom);
if (sun != null) {
dlsr = new DirectionalLightShadowRenderer(app.getAssetManager(), 1024, 3);
dlsr.setLight(sun);
dlsr.setLambda(0.55f);
dlsr.setShadowIntensity(0.6f);
dlsr.setEdgeFilteringMode(EdgeFilteringMode.PCFPOISSON);
dlsr.setShadowCompareMode(CompareMode.Hardware);
dlsr.setShadowZExtend(100f);
if (shadowsEnabled) {
nearViewPort.addProcessor(dlsr);
}
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
}
@Override
public void update(float tpf) {
nearCam.setLocation(farCam.getLocation());
nearCam.setRotation(farCam.getRotation());
this.nearestPlanet = findNearestPlanet();
for (Planet planet: this.planets ) {
planet.setCameraPosition(this.app.getCamera().getLocation());
}
updateFogAndBloom();
}
@Override
public void cleanup() {
super.cleanup();
}
public void addPlanet(Planet planet) {
this.planets.add(planet);
}
public List<Planet> getPlanets() {
return this.planets;
}
public Planet getNearestPlanet() {
return this.nearestPlanet;
}
public Vector3f getGravity() {
Planet planet = getNearestPlanet();
if (planet != null && planet.getPlanetToCamera() != null) {
return planet.getPlanetToCamera().normalize().mult(-9.81f);
}
return Vector3f.ZERO;
}
public void setShadowsEnabled(boolean enabled) {
this.shadowsEnabled = enabled;
if (dlsr != null)
{
if (enabled) {
nearViewPort.addProcessor(dlsr);
}
else {
nearViewPort.removeProcessor(dlsr);
}
}
}
protected Planet findNearestPlanet() {
Planet cPlanet = null;
for (Planet planet: this.planets ) {
if (cPlanet == null || cPlanet.getDistanceToCamera() > planet.getDistanceToCamera()) {
cPlanet = planet;
}
}
return cPlanet;
}
protected void updateFogAndBloom() {
if (this.nearestPlanet == null) {
return;
}
Planet planet = this.nearestPlanet;
if (planet.getIsInOcean()) {
// turn on underwater fogging
nearFog.setFogColor(planet.getUnderwaterFogColor());
nearFog.setFogDistance(planet.getUnderwaterFogDistance());
nearFog.setFogDensity(planet.getUnderwaterFogDensity());
nearFog.setEnabled(true);
farFog.setFogColor(planet.getUnderwaterFogColor());
farFog.setFogDistance(planet.getUnderwaterFogDistance());
farFog.setFogDensity(planet.getUnderwaterFogDensity());
farFog.setEnabled(true);
farBloom.setEnabled(true);
} else {
if (planet.getIsInAtmosphere()) {
// turn on atomosphere fogging
nearFog.setFogColor(planet.getAtmosphereFogColor());
nearFog.setFogDistance(planet.getAtmosphereFogDistance());
nearFog.setFogDensity(planet.getAtmosphereFogDensity());
nearFog.setEnabled(true);
farFog.setFogColor(planet.getAtmosphereFogColor());
farFog.setFogDistance(planet.getAtmosphereFogDistance());
farFog.setFogDensity(planet.getAtmosphereFogDensity());
farFog.setEnabled(true);
farBloom.setEnabled(false);
} else {
// in space
nearFog.setEnabled(false);
farFog.setEnabled(false);
farBloom.setEnabled(true);
}
}
}
}
| 34.57265 | 100 | 0.639555 |
08a6ed2c7e831bc7ff4f165c096a48faced136f5 | 3,592 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.end2end;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.phoenix.query.BaseTest;
import org.apache.phoenix.util.QueryBuilder;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.ReadOnlyProps;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Category;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Base class for tests whose methods run in parallel with
* 1. Statistics enabled on server side (QueryServices#STATS_COLLECTION_ENABLED is true)
* 2. Guide Post Width for all relevant tables is 0. Stats are disabled at table level.
*
* See {@link org.apache.phoenix.schema.stats.NoOpStatsCollectorIT} for tests that disable
* stats collection from server side.
*
* You must create unique names using {@link #generateUniqueName()} for each
* table and sequence used to prevent collisions.
*/
@Category(ParallelStatsDisabledTest.class)
public abstract class ParallelStatsDisabledIT extends BaseTest {
@BeforeClass
public static synchronized void doSetup() throws Exception {
Map<String, String> props = Maps.newHashMapWithExpectedSize(1);
setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
}
@AfterClass
public static synchronized void freeResources() throws Exception {
BaseTest.freeResourcesIfBeyondThreshold();
}
protected ResultSet executeQuery(Connection conn, QueryBuilder queryBuilder) throws SQLException {
PreparedStatement statement = conn.prepareStatement(queryBuilder.build());
ResultSet rs = statement.executeQuery();
return rs;
}
protected ResultSet executeQueryThrowsException(Connection conn, QueryBuilder queryBuilder,
String expectedPhoenixExceptionMsg, String expectedSparkExceptionMsg) {
ResultSet rs = null;
try {
rs = executeQuery(conn, queryBuilder);
fail();
}
catch(Exception e) {
assertTrue(e.getMessage().contains(expectedPhoenixExceptionMsg));
}
return rs;
}
protected void validateQueryPlan(Connection conn, QueryBuilder queryBuilder, String expectedPhoenixPlan, String expectedSparkPlan) throws SQLException {
if (StringUtils.isNotBlank(expectedPhoenixPlan)) {
ResultSet rs = conn.createStatement().executeQuery("EXPLAIN " + queryBuilder.build());
assertEquals(expectedPhoenixPlan, QueryUtil.getExplainPlan(rs));
}
}
}
| 38.212766 | 156 | 0.745824 |
35f8d0df63e4e4e840eb6433719eaedb1a4fcc10 | 5,442 | /*
* Copyright (c) 2018-2019, BEPAL
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of California, Berkeley nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package pro.bepal.crypto;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by 10254 on 2017-08-02.
*/
public class AES {
/**
* AES 加密
*/
public static byte[] encrypt(byte[] content, byte[] key) {
try {
Cipher cipher = Cipher.getInstance("AES");
key = Arrays.copyOf(key, 16);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* AES CBC 加密
*/
public static byte[] encryptCBC(byte[] content, byte[] sksBytes, byte[] ivBytes) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(sksBytes, "AES");
IvParameterSpec iv = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* AES 解密
*/
public static byte[] decrypt(byte[] content, byte[] key) {
try {
Cipher cipher = Cipher.getInstance("AES");
key = Arrays.copyOf(key, 16);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* AES CBC 解密
*/
public static byte[] decryptCBC(byte[] content, byte[] sksBytes, byte[] ivBytes) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(sksBytes, "AES");
IvParameterSpec iv = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* AES 加密
*/
public static byte[] encryptRandom(byte[] content, byte[] key) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec skey = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skey);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* AES 解密
*/
public static byte[] decryptRandom(byte[] content, byte[] key) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec skey = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skey);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
| 36.52349 | 86 | 0.620911 |
55ee20407438b0e6d42b8baa88728633abcf7385 | 2,260 | package com.pattern.tutor.syntax.action.newfeature.java8.chap5;
import static java.util.stream.Collectors.toList;
import java.util.Arrays;
import java.util.List;
import com.pattern.tutor.syntax.action.newfeature.java8.entity.Dish;
import com.pattern.tutor.syntax.action.newfeature.java8.entity.Pair;
public class MappingExample {
public static void main(String[] args) {
/*
* println(getNameList());
* System.out.println("-----------------------------------");
*
* println(getNameLengthList());
* System.out.println("-----------------------------------");
*
* println(getLengthList());
* System.out.println("-----------------------------------");
*
* println(getUniqueCharacterList());
* System.out.println("-----------------------------------");
*/
println(map());
System.out.println("-----------------------------------");
println(flatMap());
System.out.println("-----------------------------------");
println(flatMapAndThreeMultiple());
}
public static List<String> getNameList() {
return Dish.menu.stream().map(Dish::getName).collect(toList());
}
public static List<Integer> getNameLengthList() {
return Dish.menu.stream().map(Dish::getName).map(String::length).collect(toList());
}
public static List<Integer> getLengthList() {
return Arrays.asList("Java 8", "Lambda", "In", "Action").stream().map(String::length).collect(toList());
}
public static List<String> getUniqueCharacterList() {
String[] arrayOfWords = { "Hello", "World" };
return Arrays.stream(arrayOfWords).map(word -> word.split("")).flatMap(Arrays::stream).distinct()
.collect(toList());
}
public static List<Integer> map() {
return Arrays.asList(1, 2, 3, 4, 5).stream().map(n -> n * n).collect(toList());
}
public static List<Pair> flatMap() {
List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(3, 4);
return numbers1.stream().flatMap(i -> numbers2.stream().map(j -> new Pair<Integer>(i, j))).collect(toList());
}
public static List<Pair> flatMapAndThreeMultiple() {
return flatMap().stream().filter(pair -> (pair.sum() % 3 == 0)).collect(toList());
}
public static <T> void println(List<T> list) {
list.forEach(System.out::println);
}
}
| 30.958904 | 111 | 0.615044 |
2d30e5458462288c922d684d80948c32945aa412 | 326 | package com.artos.spi.core;
import com.artos.api.core.server.IMembershipService;
import com.exametrika.common.utils.ByteArray;
import com.exametrika.common.utils.ICompletionHandler;
public interface IGroupChannel extends IMembershipService {
void publish(ByteArray value, ICompletionHandler<ByteArray> commitHandler);
}
| 32.6 | 79 | 0.834356 |
e10622f1fefe4feb3b1b49987cb5ff9e1addcf85 | 12,843 | package me.deecaad.weaponmechanics.mechanics.defaultmechanics;
import me.deecaad.core.compatibility.CompatibilityAPI;
import me.deecaad.core.file.SerializeData;
import me.deecaad.core.file.SerializerEnumException;
import me.deecaad.core.file.SerializerException;
import me.deecaad.core.file.SerializerVersionException;
import me.deecaad.core.placeholder.PlaceholderAPI;
import me.deecaad.core.utils.EnumUtil;
import me.deecaad.core.utils.StringUtil;
import me.deecaad.weaponmechanics.WeaponMechanics;
import me.deecaad.weaponmechanics.mechanics.CastData;
import me.deecaad.weaponmechanics.mechanics.IMechanic;
import me.deecaad.weaponmechanics.mechanics.Mechanics;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.hover.content.Content;
import net.md_5.bungee.api.chat.hover.content.Text;
import org.bukkit.Bukkit;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
public class MessageMechanic implements IMechanic<MessageMechanic> {
private boolean sendGlobally;
private boolean sendGloballyForWorld;
private ChatData chatData;
private String actionBar;
private int actionBarTime;
private TitleData titleData;
private BossBarData bossBarData;
/**
* Empty constructor to be used as serializer
*/
public MessageMechanic() {
if (Mechanics.hasMechanic(getKeyword())) return;
Mechanics.registerMechanic(WeaponMechanics.getPlugin(), this);
}
public MessageMechanic(boolean sendGlobally, boolean sendGloballyForWorld, ChatData chatData, String actionBar, int actionBarTime, TitleData titleData, BossBarData bossBarData) {
this.sendGlobally = sendGlobally;
this.sendGloballyForWorld = sendGloballyForWorld;
this.chatData = chatData;
this.actionBar = actionBar;
this.actionBarTime = actionBarTime;
this.titleData = titleData;
this.bossBarData = bossBarData;
}
@Override
public void use(CastData castData) {
if (sendGlobally) {
for (Player player : Bukkit.getOnlinePlayers()) {
send(castData, player);
}
return;
} else if (sendGloballyForWorld) {
for (Player player : castData.getCastLocation().getWorld().getPlayers()) {
send(castData, player);
}
return;
}
send(castData, (Player) castData.getCaster());
}
private void send(CastData castData, Player player) {
Map<String, String> tempPlaceholders = null;
String shooterName = castData.getData(CommonDataTags.SHOOTER_NAME.name(), String.class);
String victimName = castData.getData(CommonDataTags.VICTIM_NAME.name(), String.class);
if (shooterName != null || victimName != null) {
tempPlaceholders = new HashMap<>();
tempPlaceholders.put("%shooter%", shooterName != null ? shooterName : player.getName());
tempPlaceholders.put("%victim%", victimName);
}
if (chatData != null) {
String chatMessage = PlaceholderAPI.applyPlaceholders(chatData.message, player, castData.getWeaponStack(), castData.getWeaponTitle(), null, tempPlaceholders);
TextComponent chatMessageComponent = new TextComponent(chatMessage);
if (chatData.clickEventAction != null) {
chatMessageComponent.setClickEvent(new ClickEvent(chatData.clickEventAction,
PlaceholderAPI.applyPlaceholders(chatData.clickEventValue, player, castData.getWeaponStack(), castData.getWeaponTitle(), null, tempPlaceholders)));
}
if (chatData.hoverEventValue != null) {
Content content = new Text(TextComponent.fromLegacyText(
PlaceholderAPI.applyPlaceholders(chatData.hoverEventValue, player, castData.getWeaponStack(), castData.getWeaponTitle(), null, tempPlaceholders)));
chatMessageComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, content));
}
player.spigot().sendMessage(ChatMessageType.CHAT, chatMessageComponent);
}
if (actionBar != null) {
String actionBarMessage = PlaceholderAPI.applyPlaceholders(actionBar, player, castData.getWeaponStack(), castData.getWeaponTitle(), null, tempPlaceholders);
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(actionBarMessage));
if (actionBarTime > 40) {
Map<String, String> finalTempPlaceholders = tempPlaceholders;
new BukkitRunnable() {
int ticker = 0;
@Override
public void run() {
String actionBarMessage = PlaceholderAPI.applyPlaceholders(actionBar, player, castData.getWeaponStack(), castData.getWeaponTitle(), null, finalTempPlaceholders);
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(actionBarMessage));
ticker += 40;
if (ticker >= actionBarTime) {
cancel();
}
}
}.runTaskTimerAsynchronously(WeaponMechanics.getPlugin(), 40, 40);
}
}
if (titleData != null) {
String titleMessage = PlaceholderAPI.applyPlaceholders(titleData.title, player, castData.getWeaponStack(), castData.getWeaponTitle(), null, tempPlaceholders);
String subtitleMessage = PlaceholderAPI.applyPlaceholders(titleData.subtitle, player, castData.getWeaponStack(), castData.getWeaponTitle(), null, tempPlaceholders);
if (CompatibilityAPI.getVersion() < 1.11) {
player.sendTitle(titleMessage, subtitleMessage);
} else {
player.sendTitle(titleMessage, subtitleMessage, titleData.fadeIn, titleData.stay, titleData.fadeOut);
}
}
if (bossBarData != null) {
String bossBarMessage = PlaceholderAPI.applyPlaceholders(bossBarData.title, player, castData.getWeaponStack(), castData.getWeaponTitle(), null, tempPlaceholders);
BossBar bossBar = Bukkit.createBossBar(bossBarMessage, bossBarData.barColor, bossBarData.barStyle);
bossBar.addPlayer(player);
new BukkitRunnable() {
public void run() {
bossBar.removeAll();
}
}.runTaskLaterAsynchronously(WeaponMechanics.getPlugin(), bossBarData.time);
}
}
public boolean hasBossBar() {
return bossBarData != null;
}
@Override
public boolean requirePlayer() {
// Make it require player IF global send isn't enabled
// Since then this message is always directly for player
return !sendGlobally && !sendGloballyForWorld;
}
@Override
public String getKeyword() {
return "Message";
}
@Override
@Nonnull
public MessageMechanic serialize(SerializeData data) throws SerializerException {
// CHAT
ChatData chatData = null;
String chatMessage = data.of("Chat.Message").assertType(String.class).get(null);
if (chatMessage != null) {
ClickEvent.Action clickEventAction = null;
String clickEventValue = null;
String hoverEventValue = data.of("Chat.Hover_Text").assertType(String.class).get(null);
if (hoverEventValue != null) hoverEventValue = StringUtil.color(hoverEventValue);
String clickEventString = data.of("Chat.Click").assertType(String.class).get(null);
if (clickEventString != null) {
String[] split = clickEventString.split("-", 2);
if (split.length != 2) {
throw data.exception(null, "Chat Click Action should be formatted like: <ClickEvent.Action>-<value>",
SerializerVersionException.forValue(clickEventString));
}
clickEventAction = EnumUtil.getIfPresent(ClickEvent.Action.class, split[0])
.orElseThrow(() -> new SerializerEnumException(this, ClickEvent.Action.class, split[0], false, data.of("Chat.Click").getLocation()));
clickEventValue = StringUtil.color(split[1]);
}
chatData = new ChatData(StringUtil.color(chatMessage), clickEventAction, clickEventValue, hoverEventValue);
}
// ACTION BAR
String actionBarMessage = data.of("Action_Bar.Message").assertType(String.class).get(null);
if (actionBarMessage != null) actionBarMessage = StringUtil.color(actionBarMessage);
int actionBarTime = data.of("Action_Bar.Time").assertRange(40, Integer.MAX_VALUE).getInt(0);
// TITLE
TitleData titleData = null;
String titleMessage = data.of("Title.Title").assertType(String.class).get(null);
String subtitleMessage = data.of("Title.Subtitle").assertType(String.class).get(null);
if (titleMessage != null || subtitleMessage != null) {
int fadeIn = data.of("Title.Fade_In").assertPositive().getInt(0);
int stay = data.of("Title.Stay").assertPositive().getInt(40);
int fadeOut = data.of("Title.Fade_Out").assertPositive().getInt(0);
titleData = new TitleData(titleMessage != null ? StringUtil.color(titleMessage) : null, subtitleMessage != null ? StringUtil.color(subtitleMessage) : null, fadeIn, stay, fadeOut);
}
// BOSS BAR
BossBarData bossBarData = null;
String bossBarMessage = data.of("Boss_Bar.Title").assertType(String.class).get(null);
if (bossBarMessage != null) {
BarColor barColor = data.of("Boss_Bar.Bar_Color").getEnum(BarColor.class, BarColor.WHITE);
BarStyle barStyle = data.of("Boss_Bar.Bar_Style").getEnum(BarStyle.class, BarStyle.SEGMENTED_20);
int time = data.of("Boss_Bar.Time").assertExists().assertPositive().getInt();
bossBarData = new BossBarData(StringUtil.color(bossBarMessage), barColor, barStyle, time);
}
if (chatData == null && actionBarMessage == null && titleData == null && bossBarData == null) {
throw data.exception(null, "Tried to use a Message Mechanic without any messages added!",
"If you do not want to send any messages, please remove the key from your config.");
}
boolean sendGlobally = data.of("Send_Globally").getBool(false);
boolean sendGloballyForWorld = data.of("Send_Globally_For_World").getBool(false);
return new MessageMechanic(sendGlobally, sendGloballyForWorld, chatData, actionBarMessage, actionBarTime, titleData, bossBarData);
}
private static class ChatData {
public String message;
public ClickEvent.Action clickEventAction;
public String clickEventValue;
// No need for HoverEvent.Action since only SHOW_TEXT is usable
public String hoverEventValue;
public ChatData(String message, ClickEvent.Action clickEventAction, String clickEventValue, String hoverEventValue) {
this.message = message;
this.clickEventAction = clickEventAction;
this.clickEventValue = clickEventValue;
this.hoverEventValue = hoverEventValue;
}
}
private static class TitleData {
public String title;
public String subtitle;
public int fadeIn;
public int stay;
public int fadeOut;
public TitleData(String title, String subtitle, int fadeIn, int stay, int fadeOut) {
this.title = title;
this.subtitle = subtitle;
if (this.subtitle != null && this.title == null) {
this.title = "";
}
this.fadeIn = fadeIn == 0 ? 10 : fadeIn;
this.stay = stay == 0 ? 20 : stay;
this.fadeOut = fadeOut == 0 ? 10 : fadeOut;
}
}
private static class BossBarData {
public String title;
public BarColor barColor;
public BarStyle barStyle;
public int time;
public BossBarData(String title, BarColor barColor, BarStyle barStyle, int time) {
this.title = title;
this.barColor = barColor == null ? BarColor.WHITE : barColor;
this.barStyle = barStyle == null ? BarStyle.SOLID : barStyle;
this.time = time == 0 ? 20 : time;
}
}
} | 45.381625 | 191 | 0.654831 |
2689c4615516d2498d2e30fdcbd1002f43405efb | 7,710 | package com.example.healthify;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import Model.BaseFirestore;
import Model.Customer;
import Model.PromoCodes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class login extends AppCompatActivity {
TextView email;
TextView password;
Button signin;
TextView signup;
Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
PromoCodes c1 = new PromoCodes("AA123", 0.1);
c1.sendToFirestore();
SharedPreferences sharedPreferences = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
BaseFirestore.db.collection("PromoCodes").document(c1.getID()).update("Code", "AB123");
System.out.println("PROMO SHOULD BE UPDATED NOW--------------------");
email = findViewById(R.id.edittext_login_enail);
password = findViewById(R.id.editText_password);
signup = findViewById(R.id.text_signup);
System.out.println("sharedPreferences" + sharedPreferences.getString("customerType", "null"));
email.setText(sharedPreferences.getString("email", ""));
password.setText(sharedPreferences.getString("password", ""));
if (sharedPreferences.getString("customerType", "null").equals("Customer")) {
go_to_Customet_Home();
} else if (sharedPreferences.getString("customerType", "null").equals("Delivery")) {
got_to_DeliveryPerson_Home();
}
signup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(login.this, signup.class);
startActivity(intent);
}
});
System.out.println("INSIDE LOGIN CLASS -----------------------");
System.out.println("Initially : " + signin);
signin = findViewById(R.id.button_signin);
System.out.println("Finally : " + signin);
signin.setOnClickListener(new View.OnClickListener() {
//Toast.makeText(getApplicationContext(),"User exists with password :",Toast.LENGTH_SHORT).show();
@Override
public void onClick(View view) {
final String e_mail = email.getText().toString();
DocumentReference docref = Customer.db.collection("Customer").document(e_mail);
docref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
String pa = doc.getString("password");
Customer c = doc.toObject(Customer.class);
//System.out.println(c);
if (pa.equals(password.getText().toString())) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("email", email.getText().toString());
editor.putString("password", pa);
editor.putString("customerType", "Customer");
editor.commit();
go_to_Customet_Home();
} else {
Toast.makeText(getApplicationContext(),
"Incorrect Password customer",
Toast.LENGTH_SHORT).show();
}
} else {
final DocumentReference doc2 = BaseFirestore.db.collection("DeliveryPartner").document(e_mail);
doc2.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot ref = task.getResult();
if (ref.exists()) {
String pa = ref.getString("password");
if (pa.equals(password.getText().toString())) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("email", email.getText().toString());
editor.putString("password", pa);
editor.putString("customerType", "Delivery");
editor.commit();
got_to_DeliveryPerson_Home();
} else {
Toast.makeText(getApplicationContext(), "Incorrect Password delivery", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "User does not exist , please sign up", Toast.LENGTH_SHORT).show();
// finish();
}
} else {
}
}
});
//Toast.makeText(getApplicationContext(),"User does not exist , please sign up",Toast.LENGTH_SHORT).show();
//finish();
//go to previous activity
}
} else {
//now check DileveryPartner collection.
Toast.makeText(getApplicationContext(), "Error connecting to servers", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
public void go_to_Customet_Home() {
// Bundle b = new Bundle();
// b.putString("user_name",email.getText().toString());
// Intent i = new Intent(context,ChooseMapAfterSignup.class);
Intent i = new Intent(context, CustomerHome.class);
i.putExtra("user_email", email.getText().toString());
startActivity(i);
finish();
}
public void got_to_DeliveryPerson_Home() {
System.out.println("Inside Delivery Partner!" + email.getText().toString());
Intent it = new Intent(context, DeliveryPartnerHome.class);
it.putExtra("user_name", email.getText().toString());
startActivity(it);
finish();
}
}
| 49.741935 | 155 | 0.505707 |
2ab6da94a799362086ce3bc1a68d99c11715409f | 7,100 | package meteordevelopment.nbt;
import meteordevelopment.nbt.tags.*;
import java.io.*;
public class NbtWriter implements Closeable, AutoCloseable {
private final OutputStream stream;
private final DataOutput out;
public NbtWriter(String name, OutputStream stream) {
this.stream = stream;
this.out = new DataOutputStream(stream);
writeCompoundStart(name == null ? "" : name);
}
public NbtWriter(String name, File file) throws FileNotFoundException {
this(name, new FileOutputStream(file));
}
public void writeCompoundStart(String name) {
try {
writeHeader(TagId.Compound.ordinal(), name);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeCompoundStart() { writeCompoundStart(null); }
public void writeCompoundEnd() {
try {
out.writeByte(TagId.End.ordinal());
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeByte(String name, byte v) {
try {
writeHeader(TagId.Byte.ordinal(), name);
out.writeByte(v);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeByte(byte v) { writeByte(null, v); }
public void writeBool(String name, boolean v) {
writeByte(name, (byte) (v ? 1 : 0));
}
public void writeBool(boolean v) { writeBool(null, v); }
public void writeShort(String name, short v) {
try {
writeHeader(TagId.Short.ordinal(), name);
out.writeShort(v);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeShort(short v) { writeShort(null, v); }
public void writeInt(String name, int v) {
try {
writeHeader(TagId.Int.ordinal(), name);
out.writeInt(v);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeInt(int v) { writeInt(null, v); }
public void writeLong(String name, long v) {
try {
writeHeader(TagId.Long.ordinal(), name);
out.writeLong(v);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeLong(long v) { writeLong(null, v); }
public void writeFloat(String name, float v) {
try {
writeHeader(TagId.Float.ordinal(), name);
out.writeFloat(v);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFloat(float v) { writeFloat(null, v); }
public void writeDouble(String name, double v) {
try {
writeHeader(TagId.Double.ordinal(), name);
out.writeDouble(v);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeDouble(double v) { writeDouble(null, v); }
public void writeString(String name, String v) {
try {
writeHeader(TagId.String.ordinal(), name);
out.writeUTF(v);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeString(String v) { writeString(null, v); }
public void writeByteArray(String name, byte[] v) {
try {
writeHeader(TagId.ByteArray.ordinal(), name);
out.writeInt(v.length);
out.write(v);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeByteArray(byte[] v) { writeByteArray(null, v); }
public void writeIntArray(String name, int[] v) {
try {
writeHeader(TagId.IntArray.ordinal(), name);
out.writeInt(v.length);
for (int j : v) out.writeInt(j);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeIntArray(int[] v) { writeIntArray(null, v); }
public void writeLongArray(String name, long[] v) {
try {
writeHeader(TagId.LongArray.ordinal(), name);
out.writeInt(v.length);
for (long l : v) out.writeLong(l);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeLongArray(long[] v) { writeLongArray(null, v); }
public void writeList(String name, int type, int size) {
try {
writeHeader(TagId.List.ordinal(), name);
out.writeByte(type);
out.writeInt(size);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeList(int type, int size) { writeList(null, type, size); }
public void writeList(String name, TagId type, int size) { writeList(name, type.ordinal(), size); }
public void writeList(TagId type, int size) { writeList(null, type.ordinal(), size); }
public void write(String name, Tag tag) {
try {
writeHeader(tag.getId(), name);
switch (TagId.valueOf(tag.getId())) {
case Byte -> out.writeByte(((ByteTag) tag).value);
case Short -> out.writeShort(((ShortTag) tag).value);
case Int -> out.writeInt(((IntTag) tag).value);
case Long -> out.writeLong(((LongTag) tag).value);
case Float -> out.writeFloat(((FloatTag) tag).value);
case Double -> out.writeDouble(((DoubleTag) tag).value);
case String -> out.writeUTF(((StringTag) tag).value);
case ByteArray -> {
ByteArrayTag t = (ByteArrayTag) tag;
out.writeInt(t.value.length);
out.write(t.value);
}
case IntArray -> {
IntArrayTag t = (IntArrayTag) tag;
out.writeInt(t.value.length);
for (int v : t.value) out.writeInt(v);
}
case LongArray -> {
LongArrayTag t = (LongArrayTag) tag;
out.writeInt(t.value.length);
for (long v : t.value) out.writeLong(v);
}
case Compound -> {
CompoundTag t = (CompoundTag) tag;
for (String key : t.keySet()) {
write(key, t.get(key));
}
writeCompoundEnd();
}
case List -> {
ListTag<?> t = (ListTag<?>) tag;
out.writeByte(t.id);
out.writeInt(t.size());
for (Tag ta : t) write(ta);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(Tag tag) { write(null, tag); }
private void writeHeader(int id, String name) throws IOException {
if (name != null) {
out.writeByte(id);
out.writeUTF(name);
}
}
@Override
public void close() throws IOException {
writeCompoundEnd();
stream.flush();
stream.close();
}
}
| 31.004367 | 103 | 0.525352 |
f5ccdcfb4499be056daf104348849995c0ebfe8c | 1,381 | /*
* Waxeye Parser Generator
* www.waxeye.org
* Copyright (C) 2008-2010 Orlando Hill
* Licensed under the MIT license. See 'LICENSE' for details.
*/
package org.waxeye.parser;
import org.waxeye.ast.IAST;
/**
* The result of a parse.
*
* @param <E> The AST type.
*
* @author Orlando Hill
*/
public final class ParseResult <E extends Enum<?>>
{
/** The AST of a successful parse. */
private final IAST<E> ast;
/** The error of an unsuccessful parse. */
private final ParseError error;
/**
* Creates a new ParseResult.
*
* @param ast The AST of a successful parse.
*
* @param error The error of an unsuccessful parse.
*/
public ParseResult(final IAST<E> ast, final ParseError error)
{
this.ast = ast;
this.error = error;
}
/**
* Returns the ast.
*
* @return Returns the ast.
*/
public IAST<E> getAST()
{
return ast;
}
/**
* Returns the error.
*
* @return Returns the error.
*/
public ParseError getError()
{
return error;
}
/** {@inheritDoc} */
public String toString()
{
if (ast != null)
{
return ast.toString();
}
if (error != null)
{
return error.toString();
}
return "ParseResult(null, null)";
}
}
| 18.413333 | 65 | 0.541636 |
af77f6ce54a9d1b6b3c5384e331fa5954122c5de | 1,951 | package com.windacc.wind.auth.service.impl;
import com.windacc.wind.toolkit.entity.LoginUser;
import com.windacc.wind.api.feign.IUserClient;
import com.windacc.wind.auth.service.IUserDetailsService;
import com.windacc.wind.security.entity.LoginUserDetails;
import com.windacc.wind.toolkit.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class UserDetailServiceImpl implements IUserDetailsService {
@Autowired
private IUserClient userClient;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LoginUser result = userClient.findByUsername(username);
return checkUser(result);
}
private LoginUserDetails checkUser(LoginUser loginUser) {
if (loginUser == null) {
throw new BusinessException("服务繁忙请稍后重试");
}
LoginUserDetails loginUserDetails = new LoginUserDetails();
BeanUtils.copyProperties(loginUser, loginUserDetails);
if (!loginUserDetails.isAccountNonExpired()) {
throw new UsernameNotFoundException("用户已失效");
} else if (!loginUserDetails.isAccountNonLocked()) {
throw new UsernameNotFoundException("用户被锁定");
} else if (!loginUserDetails.isEnabled()) {
throw new DisabledException("用户已作废");
}
return loginUserDetails;
}
@Override
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
return null;
}
}
| 36.811321 | 95 | 0.758585 |
876b2384dd5c431479f4943d7babdaadac7d093b | 5,982 | package com.blogspot.direinem.infrastructure.repository;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import com.blogspot.direinem.domain.model.Order;
import com.blogspot.direinem.domain.model.OrderPosition;
import com.blogspot.direinem.domain.model.Pizza;
import com.blogspot.direinem.domain.model.User;
/**
* Represents a repository to access and manipulate the order objects and all
* objects in the hierarchy of it.
*
* @author Dirk Reinemann
*/
@Stateless
public class OrderRepository extends AbstractRepository {
private static final Logger LOG = Logger.getLogger(OrderRepository.class);
/**
* Loads all orders that belongs to the given email address of the user.
*
* @param email the email address of the user
* @return the list of orders
*/
@SuppressWarnings("unchecked")
public Order findOrderByEmail(String email) {
Query query = entityManager.createQuery("SELECT o FROM Order o WHERE o.user.email=:email ORDER BY o.orderTime DESC", Order.class);
query.setParameter("email", email);
List<Order> orders = query.getResultList();
return orders.isEmpty() ? null : orders.get(0);
}
/**
* Saves the given order to the database. Iterates all order positions and
* checks whether the pizza already exists in the database. Replaces it if
* true.
*
* @param order the order to save
* @throws Exception an exception while saving the order
*/
public void saveOrder(Order order) throws Exception {
try {
for (OrderPosition orderPosition : order.getOrderPositions()) {
orderPosition.getPizza().setId(findExistingPizzaId(orderPosition.getPizza()));
}
entityManager.merge(order);
}
catch (Exception e) {
LOG.error("saveOrder(): Exception", e);
throw e;
}
}
/**
* Queries the database for a pizza with identical ingredients like the
* given pizza to prevent unnecessary memory usage.
*
* @param pizza the pizza to check
* @return the primary key of the pizza with identical ingredients
*/
private long findExistingPizzaId(Pizza pizza) {
long result = 0;
try {
List<Long> ids = pizza.getIngredientIds();
Query query = entityManager.createQuery("SELECT p.id FROM Pizza p INNER JOIN p.ingredients i WHERE i.id IN :ids GROUP BY p.id HAVING COUNT(p.id)=:count");
query.setParameter("ids", ids);
query.setParameter("count", ids.size());
result = (Long) query.getSingleResult();
}
catch (NoResultException e) {
LOG.info("findExistingPizzaId(): No result found for " + pizza);
}
return result;
}
/**
* Queries the database for a user.
*
* @param user the user to search for
* @return the primary key of the user or 0
*/
public long findExsitingUserId(User user) {
int result = 0;
try {
Query query = entityManager.createQuery("SELECT u.id FROM User u WHERE u.firstname=:firstname AND u.lastname=:lastname AND u.street=:street AND u.zip=:zip AND u.phone=:phone");
query.setParameter("firstname", user.getFirstname());
query.setParameter("lastname", user.getLastname());
query.setParameter("street", user.getStreet());
query.setParameter("zip", user.getZip());
query.setParameter("phone", user.getPhone());
result = (Integer) query.getSingleResult();
}
catch (NoResultException e) {
LOG.info("findExsitingUserId(): No result found for " + user);
}
return result;
}
/**
* Loads all orders from the database and the count of order positions.
* Sets the count of order positions to the order.
*
* @return the list of orders
*/
@SuppressWarnings("unchecked")
public List<Order> getAllOrdersAndPizzaCount() {
List<Object[]> tuples = entityManager.createQuery("SELECT o, COUNT(o.orderPositions) FROM Order o").getResultList();
List<Order> orders = new LinkedList<Order>();
for (Object[] tuple : tuples) {
Order order = (Order) tuple[0];
Long pizzaCount = (Long) tuple[1];
order.setPizzaCount(pizzaCount.intValue());
orders.add(order);
}
return orders;
}
/**
* Loads all orders from the database ordered by the order date.
*
* @return the list of orders
*/
@SuppressWarnings("unchecked")
public List<Order> getAllOrdersOrderedByNewest() {
return entityManager.createQuery("SELECT o FROM Order o ORDER BY o.orderTime ASC").getResultList();
}
/**
* Loads the order with the given primary key from the database.
*
* @param idOrder the primary key of the order
* @return the order or null if it was not found
*/
public Order getOrder(long idOrder) {
return entityManager.find(Order.class, idOrder);
}
/**
* Updates the given order in the database.
*
* @param order the order to update
*/
public void updateOrder(Order order) {
entityManager.merge(order);
}
/**
* Loads the given number of orders from the user with the given email
* address from the database ordered by the delivery time.
*
* @param email the email address of the user
* @param count the number of orders to load
* @return the list of orders
*/
@SuppressWarnings("unchecked")
public List<Order> getRecentOrdersByUser(String email, int count) {
Query query = entityManager.createQuery("SELECT o FROM Order o WHERE o.user.email=:email ORDER BY o.deliveryTime ASC");
query.setMaxResults(count);
query.setParameter("email", email);
return query.getResultList();
}
} | 34.77907 | 183 | 0.651622 |
3f6cc1555695396fc4cfd60238b691b3b9c43469 | 1,061 | package com.github.mickeer.codegen.fieldnames;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* For each class annotated with this annotation, a class with class' name
* postfixed with "FieldNames" is generated. The generated class contains fields
* which names correspond to the fields of the annotated class and each field's
* value is the name of the field.
*
* <p> E.g. for class {@code MyClass} with a field {@code date}, a class
* {@code MyClassFieldNames} is generated with field {@code date} with value
* {@code "date"}.
*
* <p> The intention of this is to provide compiler-safe way to refer to fields of
* a class for reflection usage. Whenever field's name changes, this generated
* class also changes and anything referring to these generated fields will break
* and notify developer.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface GenerateFieldNames {
}
| 39.296296 | 83 | 0.746466 |
c8f943e27fa00eb493560e453e1e515886ade2ea | 9,993 | package jetbrains.mps.lang.structure.typesystem;
/*Generated by MPS */
import jetbrains.mps.lang.typesystem.runtime.AbstractNonTypesystemRule_Runtime;
import jetbrains.mps.lang.typesystem.runtime.NonTypesystemRule_Runtime;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.typesystem.inference.TypeCheckingContext;
import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SModuleOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.errors.messageTargets.MessageTarget;
import jetbrains.mps.errors.messageTargets.NodeMessageTarget;
import jetbrains.mps.errors.IErrorReporter;
import jetbrains.mps.errors.BaseQuickFixProvider;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SModelOperations;
import jetbrains.mps.internal.collections.runtime.IWhereFilter;
import java.util.Objects;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SProperty;
import org.jetbrains.mps.openapi.language.SContainmentLink;
public class check_AbstractConceptDeclaration_Ids_NonTypesystemRule extends AbstractNonTypesystemRule_Runtime implements NonTypesystemRule_Runtime {
public check_AbstractConceptDeclaration_Ids_NonTypesystemRule() {
}
public void applyRule(final SNode acd, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) {
if (!(SModuleOperations.isAspect(SNodeOperations.getModel(acd), "structure"))) {
return;
}
if (isEmptyString(SPropertyOperations.getString(acd, PROPS.conceptId$rrGe))) {
{
final MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(acd, "Concept id is not defined.\n" + "Please run MainMenu->Migration->Migrations->Language Migrations->j.m.lang.structure->Set Ids\n" + "If this concept was created manually, invoke the \"Generate IDs\" intention on it", "r:00000000-0000-4000-0000-011c8959028f(jetbrains.mps.lang.structure.typesystem)", "1587916991969781666", null, errorTarget);
{
BaseQuickFixProvider intentionProvider = new BaseQuickFixProvider("jetbrains.mps.lang.structure.typesystem.GenerateConceptIds_QuickFix", "1587916991969947421", false);
intentionProvider.putArgument("c", acd);
_reporter_2309309498.addIntentionProvider(intentionProvider);
}
}
} else {
if (ListSequence.fromList(SModelOperations.nodes(SNodeOperations.getModel(acd), CONCEPTS.AbstractConceptDeclaration$KA)).any(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return it != acd && Objects.equals(SPropertyOperations.getString(it, PROPS.conceptId$rrGe), SPropertyOperations.getString(acd, PROPS.conceptId$rrGe));
}
})) {
{
final MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(acd, "Duplicate concept id.\n" + "Please invoke the \"Correct ID\" intention on it", "r:00000000-0000-4000-0000-011c8959028f(jetbrains.mps.lang.structure.typesystem)", "5424895381998262898", null, errorTarget);
{
BaseQuickFixProvider intentionProvider = new BaseQuickFixProvider("jetbrains.mps.lang.structure.typesystem.CorrectDuplicateId_QuickFix", "5424895381998262899", false);
intentionProvider.putArgument("c", acd);
_reporter_2309309498.addIntentionProvider(intentionProvider);
}
}
}
}
for (final SNode p : ListSequence.fromList(SLinkOperations.getChildren(acd, LINKS.propertyDeclaration$YUgg))) {
if (isEmptyString(SPropertyOperations.getString(p, PROPS.propertyId$m5HU))) {
{
final MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(p, "Property id is not defined.\n" + "Please run MainMenu->Migration->Migrations->Language Migrations->j.m.lang.structure->Set Ids\n" + "If this property was created manually, invoke the \"Generate IDs\" intention on it", "r:00000000-0000-4000-0000-011c8959028f(jetbrains.mps.lang.structure.typesystem)", "241647608299548534", null, errorTarget);
{
BaseQuickFixProvider intentionProvider = new BaseQuickFixProvider("jetbrains.mps.lang.structure.typesystem.GenerateConceptIds_QuickFix", "241647608299548535", false);
intentionProvider.putArgument("c", acd);
_reporter_2309309498.addIntentionProvider(intentionProvider);
}
}
} else {
if (ListSequence.fromList(SLinkOperations.getChildren(acd, LINKS.propertyDeclaration$YUgg)).any(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return it != p && Objects.equals(SPropertyOperations.getString(it, PROPS.propertyId$m5HU), SPropertyOperations.getString(p, PROPS.propertyId$m5HU));
}
})) {
{
final MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(p, "Duplicate property id.\n" + "Please invoke the \"Correct ID\" intention on it", "r:00000000-0000-4000-0000-011c8959028f(jetbrains.mps.lang.structure.typesystem)", "5424895381998286923", null, errorTarget);
{
BaseQuickFixProvider intentionProvider = new BaseQuickFixProvider("jetbrains.mps.lang.structure.typesystem.CorrectDuplicateId_QuickFix", "5424895381998296115", false);
intentionProvider.putArgument("p", p);
_reporter_2309309498.addIntentionProvider(intentionProvider);
}
}
}
}
}
for (final SNode l : ListSequence.fromList(SLinkOperations.getChildren(acd, LINKS.linkDeclaration$YU1f))) {
if (isEmptyString(SPropertyOperations.getString(l, PROPS.linkId$mi9g))) {
{
final MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(l, "Link id is not defined.\n" + "Please run MainMenu->Migration->Migrations->Language Migrations->j.m.lang.structure->Set Ids\n" + "If this link was created manually, invoke the \"Generate IDs\" intention on it", "r:00000000-0000-4000-0000-011c8959028f(jetbrains.mps.lang.structure.typesystem)", "241647608299555835", null, errorTarget);
{
BaseQuickFixProvider intentionProvider = new BaseQuickFixProvider("jetbrains.mps.lang.structure.typesystem.GenerateConceptIds_QuickFix", "241647608299555836", false);
intentionProvider.putArgument("c", acd);
_reporter_2309309498.addIntentionProvider(intentionProvider);
}
}
} else {
if (ListSequence.fromList(SLinkOperations.getChildren(acd, LINKS.linkDeclaration$YU1f)).any(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return it != l && Objects.equals(SPropertyOperations.getString(it, PROPS.linkId$mi9g), SPropertyOperations.getString(l, PROPS.linkId$mi9g));
}
})) {
{
final MessageTarget errorTarget = new NodeMessageTarget();
IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(l, "Duplicate link id.\n" + "Please invoke the \"Correct ID\" intention on it", "r:00000000-0000-4000-0000-011c8959028f(jetbrains.mps.lang.structure.typesystem)", "5424895381998288260", null, errorTarget);
{
BaseQuickFixProvider intentionProvider = new BaseQuickFixProvider("jetbrains.mps.lang.structure.typesystem.CorrectDuplicateId_QuickFix", "5424895381998288261", false);
intentionProvider.putArgument("l", l);
_reporter_2309309498.addIntentionProvider(intentionProvider);
}
}
}
}
}
}
public SAbstractConcept getApplicableConcept() {
return CONCEPTS.AbstractConceptDeclaration$KA;
}
public IsApplicableStatus isApplicableAndPattern(SNode argument) {
return new IsApplicableStatus(argument.getConcept().isSubConceptOf(getApplicableConcept()), null);
}
public boolean overrides() {
return false;
}
private static boolean isEmptyString(String str) {
return str == null || str.isEmpty();
}
private static final class CONCEPTS {
/*package*/ static final SConcept AbstractConceptDeclaration$KA = MetaAdapterFactory.getConcept(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, "jetbrains.mps.lang.structure.structure.AbstractConceptDeclaration");
}
private static final class PROPS {
/*package*/ static final SProperty conceptId$rrGe = MetaAdapterFactory.getProperty(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, 0x5d2e6079771f8cc0L, "conceptId");
/*package*/ static final SProperty propertyId$m5HU = MetaAdapterFactory.getProperty(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0xf979bd086bL, 0x35a81382d82a4d9L, "propertyId");
/*package*/ static final SProperty linkId$mi9g = MetaAdapterFactory.getProperty(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0xf979bd086aL, 0x35a81382d82a4e4L, "linkId");
}
private static final class LINKS {
/*package*/ static final SContainmentLink propertyDeclaration$YUgg = MetaAdapterFactory.getContainmentLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, 0xf979c3ba6cL, "propertyDeclaration");
/*package*/ static final SContainmentLink linkDeclaration$YU1f = MetaAdapterFactory.getContainmentLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, 0xf979c3ba6bL, "linkDeclaration");
}
}
| 65.743421 | 430 | 0.751626 |
560119546c37a6e929c558d3ba6f1d194f4f3836 | 53,247 | package projects.zunawe.pokesorter;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Comparator;
import java.util.Collections;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import projects.zunawe.pokesorter.pokemon.BasicPokemon;
import projects.zunawe.pokesorter.pokemon.Pokemon;
import projects.zunawe.util.JNumberTextField;
public class ViewFrame extends JFrame{
private static final long serialVersionUID = -5749047949539597881L;
private ArrayList<Pokemon> list = new ArrayList<Pokemon>();
private JPanel panel;
private final JFrame frame = this;
private JComboBox<Pokemon> box;
private JComboBox<String> altsBox;
private BufferedImage image = null;
private JLabel[] stats = new JLabel[6];
private JLabel[] IVs = new JLabel[6];
private JLabel[] EVs = new JLabel[6];
private JLabel pokemonImage;
private JLabel level;
private JLabel nature;
private JLabel statLabel = new JLabel("Stats:");
private JLabel IVLabel = new JLabel("IVs:");
private JLabel EVLabel = new JLabel("EVs:");
private JLabel levelLabel = new JLabel("Level:");
private JLabel natureLabel = new JLabel("Nature:");
private JLabel[] statCategories = {new JLabel("Hit Points:"),
new JLabel("Attack:"),
new JLabel("Defense:"),
new JLabel("Speed:"),
new JLabel("Sp. Attack:"),
new JLabel("Sp. Defense:")};
private JLabel[] IVCategories = {new JLabel("Hit Points:"),
new JLabel("Attack:"),
new JLabel("Defense:"),
new JLabel("Speed:"),
new JLabel("Sp. Attack:"),
new JLabel("Sp. Defense:")};
private JLabel[] EVCategories = {new JLabel("Hit Points:"),
new JLabel("Attack:"),
new JLabel("Defense:"),
new JLabel("Speed:"),
new JLabel("Sp. Attack:"),
new JLabel("Sp. Defense:")};
private Pokemon selectedPokemon;
public ViewFrame(String frameName){
super(frameName);
panel = new JPanel();
SpringLayout layout = new SpringLayout();
panel.setLayout(layout);
String[] pokeNames = new String[list.size()];
for(int i = 0; i < list.size(); i ++){
Pokemon current = list.get(i);
pokeNames[i] = current.getNumber() + " " + current.getName();
}
Pokemon[] pokemonArray = new Pokemon[list.size()];
for(int i = 0; i < list.size(); i ++)
pokemonArray[i] = list.get(i);
box = new JComboBox<Pokemon>(pokemonArray);
box.setEditable(false);
box.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox<Pokemon> cb = (JComboBox<Pokemon>)e.getSource();
int index = cb.getSelectedIndex();
if(index == -1)
selectedPokemon = null;
else
selectedPokemon = (Pokemon)cb.getSelectedItem();
updateAltsBox();
updateLabels();
}
});
altsBox = new JComboBox<String>();
altsBox.setEditable(false);
altsBox.setVisible(false);
altsBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox<String> cb = (JComboBox<String>)e.getSource();
int index = cb.getSelectedIndex();
if(index == -1)
selectedPokemon.setCurrentForm(0);
else
selectedPokemon.setCurrentForm(index);
updateLabels();
}
});
int index = box.getSelectedIndex();
if(index == -1)
selectedPokemon = null;
else
selectedPokemon = list.get(index);
if(selectedPokemon != null){
level = new JLabel("" + selectedPokemon.getLevel());
nature = new JLabel(selectedPokemon.getNature());
}
else{
level = new JLabel("0");
nature = new JLabel("N/A");
}
try{
if(selectedPokemon != null){
try{
image = ImageIO.read(new File(selectedPokemon.getPictureFilePath()));
}
catch(Exception e){
image = ImageIO.read(new File("data/sprites/0.png"));
}
for(int i = 0; i < stats.length; i ++)
stats[i] = new JLabel("" + selectedPokemon.getStat(i));
for(int i = 0; i < IVs.length; i ++)
IVs[i] = new JLabel("" + selectedPokemon.getIV(i));
for(int i = 0; i < EVs.length; i ++)
EVs[i] = new JLabel("" + selectedPokemon.getEV(i));
}
else{
image = ImageIO.read(new File("data/sprites/0.png"));
for(int i = 0; i < stats.length; i ++){
stats[i] = new JLabel("" + 0);
IVs[i] = new JLabel("" + 0);
EVs[i] = new JLabel("" + 0);
}
}
pokemonImage = new JLabel(new ImageIcon(image));
}
catch(IOException ioe){
JOptionPane.showMessageDialog(null, "There was an error loading the pokemon's image.", null, JOptionPane.ERROR_MESSAGE);
}
JButton addButton = new JButton("Add Pokemon");
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
AddDialog dialog = new AddDialog(frame);
dialog.setVisible(true);
}
});
JButton editButton = new JButton("Modify Pokemon");
editButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(list.size() == 0){
JOptionPane.showMessageDialog(null, "There are no pokemon to modify!", null, JOptionPane.WARNING_MESSAGE);
return;
}
EditDialog dialog = new EditDialog(frame);
dialog.setVisible(true);
}
});
JButton removeButton = new JButton("Remove Pokemon");
removeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(list.size() == 0){
JOptionPane.showMessageDialog(null, "There are no pokemon to remove!", null, JOptionPane.WARNING_MESSAGE);
return;
}
int decider = JOptionPane.showConfirmDialog(null, "Are you sure you wish to remove the currently displayed pokemon?", null, JOptionPane.YES_NO_OPTION);
if(decider == JOptionPane.NO_OPTION)
return;
list.remove(selectedPokemon);
updateComboBox();
}
});
editButton.setPreferredSize(removeButton.getPreferredSize());
addButton.setPreferredSize(removeButton.getPreferredSize());
panel.add(box);
panel.add(altsBox);
panel.add(levelLabel);
panel.add(level);
panel.add(natureLabel);
panel.add(nature);
panel.add(statLabel);
panel.add(IVLabel);
panel.add(EVLabel);
for(int i = 0; i < stats.length; i ++){
panel.add(stats[i]);
panel.add(IVs[i]);
panel.add(EVs[i]);
panel.add(statCategories[i]);
panel.add(IVCategories[i]);
panel.add(EVCategories[i]);
}
panel.add(addButton);
panel.add(editButton);
panel.add(removeButton);
panel.add(pokemonImage);
//Menu Bar
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenu helpMenu = new JMenu("Help");
JMenuItem save = new JMenuItem("Save");
JMenuItem open = new JMenuItem("Open File...");
JMenuItem clear = new JMenuItem("Clear List");
JMenuItem append = new JMenuItem("Append List");
JMenuItem contents = new JMenuItem("Contents");
JMenuItem version = new JMenuItem("Version 1.2");
save.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
JFileChooser fc = new JFileChooser();
PokemonFileFilter filter = new PokemonFileFilter();
fc.addChoosableFileFilter(filter);
fc.setFileFilter(filter);
fc.setAcceptAllFileFilterUsed(false);
int result = fc.showSaveDialog(new JFrame("Save"));
if(result == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
String filePath = file.getPath();
if(!filePath.endsWith(".pok"))
file = new File(filePath + ".pok");
if(file.exists()){
int reply = JOptionPane.showConfirmDialog(null, "That file already exists.\nWould you like to overwrite?", "Select an Option", JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION){
file.delete();
try{
file.createNewFile();
}catch(IOException ioe){
JOptionPane.showMessageDialog(null, "There was a problem overwriting the file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else{
try {
file.createNewFile();
} catch (IOException ioe){
JOptionPane.showMessageDialog(null, "There was a problem creating the file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
try{
FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fout);
for(Pokemon p: list)
oos.writeObject(p);
oos.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "There was a problem overwriting the file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
});
open.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
JFileChooser fc = new JFileChooser();
PokemonFileFilter filter = new PokemonFileFilter();
fc.addChoosableFileFilter(filter);
fc.setFileFilter(filter);
fc.setAcceptAllFileFilterUsed(false);
int result = fc.showOpenDialog(new JFrame("Open"));
if(result == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
String filePath = file.getPath();
if(!filePath.endsWith(".pok")){
JOptionPane.showMessageDialog(null, "You cannot choose a directory.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(!file.exists()){
JOptionPane.showMessageDialog(null, "There was a problem opening the file.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try{
list.clear();
FileInputStream fin = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fin);
while(true){
try{
list.add((Pokemon)ois.readObject());
}catch(Exception e1){
break;
}
}
ois.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "There was a problem reading the file.", "Error", JOptionPane.ERROR_MESSAGE);
}
updateComboBox();
sortList();
}
}
});
clear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int decider = JOptionPane.showConfirmDialog(null, "Are you sure you want to remove all pokemon from the current list?", null, JOptionPane.YES_NO_OPTION);
if(decider == JOptionPane.NO_OPTION)
return;
list.clear();
updateComboBox();
}
});
append.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
JFileChooser fc = new JFileChooser();
PokemonFileFilter filter = new PokemonFileFilter();
fc.addChoosableFileFilter(filter);
fc.setFileFilter(filter);
fc.setAcceptAllFileFilterUsed(false);
int result = fc.showOpenDialog(new JFrame("Append"));
fc.setApproveButtonText("Append");
if(result == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
String filePath = file.getPath();
if(!filePath.endsWith(".pok")){
JOptionPane.showMessageDialog(null, "You cannot choose a directory.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(!file.exists()){
JOptionPane.showMessageDialog(null, "There was a problem opening the file.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try{
FileInputStream fin = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fin);
while(true){
try{
list.add((Pokemon)ois.readObject());
}
catch(Exception e1){
break;
}
}
ois.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "There was a problem reading the file.", "Error", JOptionPane.ERROR_MESSAGE);
}
updateComboBox();
sortList();
}
}
});
contents.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
HelpDialog help = new HelpDialog(frame);
help.setVisible(true);
}
});
fileMenu.add(save);
fileMenu.add(open);
editMenu.add(clear);
editMenu.add(append);
helpMenu.add(contents);
helpMenu.addSeparator();
helpMenu.add(version);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
//Setting the size and overall view
setContentPane(panel);
setJMenuBar(menuBar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(350, 440);
ImageIcon img = new ImageIcon("CherishBall.png");
setIconImage(img.getImage());
Dimension resolution = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((int)((resolution.getWidth() - getWidth()) / 2), (int)((resolution.getHeight() - getHeight()) / 2));
setResizable(false);
//Setting the layout of the panel
//Combo Box
layout.putConstraint(SpringLayout.WEST, box, 10, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, box, 10, SpringLayout.NORTH, panel);
//Alts Combo Box
layout.putConstraint(SpringLayout.WEST, altsBox, 10, SpringLayout.EAST, box);
layout.putConstraint(SpringLayout.NORTH, altsBox, 0, SpringLayout.NORTH, box);
//Level Label
layout.putConstraint(SpringLayout.WEST, levelLabel, 0, SpringLayout.WEST, box);
layout.putConstraint(SpringLayout.NORTH, levelLabel, 10, SpringLayout.SOUTH, box);
//Level
layout.putConstraint(SpringLayout.WEST, level, 2, SpringLayout.EAST, levelLabel);
layout.putConstraint(SpringLayout.NORTH, level, 0, SpringLayout.NORTH, levelLabel);
//Nature Label
layout.putConstraint(SpringLayout.WEST, natureLabel, 0, SpringLayout.WEST, levelLabel);
layout.putConstraint(SpringLayout.NORTH, natureLabel, 15, SpringLayout.SOUTH, levelLabel);
//Nature
layout.putConstraint(SpringLayout.WEST, nature, 2, SpringLayout.EAST, natureLabel);
layout.putConstraint(SpringLayout.NORTH, nature, 0, SpringLayout.NORTH, natureLabel);
//Stats Label
layout.putConstraint(SpringLayout.WEST, statLabel, 0, SpringLayout.WEST, natureLabel);
layout.putConstraint(SpringLayout.NORTH, statLabel, 15, SpringLayout.SOUTH, natureLabel);
//Stats
layout.putConstraint(SpringLayout.WEST, stats[0], 100, SpringLayout.WEST, statLabel);
layout.putConstraint(SpringLayout.NORTH, stats[0], 2, SpringLayout.SOUTH, statLabel);
for(int i = 1; i < stats.length; i ++){
layout.putConstraint(SpringLayout.WEST, stats[i], 100, SpringLayout.WEST, statLabel);
layout.putConstraint(SpringLayout.NORTH, stats[i], 2, SpringLayout.SOUTH, stats[i - 1]);
}
//Stat Labels
layout.putConstraint(SpringLayout.EAST, statCategories[0], -10, SpringLayout.WEST, stats[0]);
layout.putConstraint(SpringLayout.NORTH, statCategories[0], 2, SpringLayout.SOUTH, statLabel);
for(int i = 1; i < stats.length; i ++){
layout.putConstraint(SpringLayout.EAST, statCategories[i], -10, SpringLayout.WEST, stats[i]);
layout.putConstraint(SpringLayout.NORTH, statCategories[i], 2, SpringLayout.SOUTH, stats[i - 1]);
}
//IVs Label
layout.putConstraint(SpringLayout.WEST, IVLabel, 0, SpringLayout.WEST, statLabel);
layout.putConstraint(SpringLayout.NORTH, IVLabel, 20, SpringLayout.SOUTH, stats[stats.length - 1]);
//IVs
layout.putConstraint(SpringLayout.WEST, IVs[0], 0, SpringLayout.WEST, stats[0]);
layout.putConstraint(SpringLayout.NORTH, IVs[0], 2, SpringLayout.SOUTH, IVLabel);
for(int i = 1; i < IVs.length; i ++){
layout.putConstraint(SpringLayout.WEST, IVs[i], 0, SpringLayout.WEST, stats[i]);
layout.putConstraint(SpringLayout.NORTH, IVs[i], 2, SpringLayout.SOUTH, IVs[i - 1]);
}
//IV Labels
layout.putConstraint(SpringLayout.EAST, IVCategories[0], -10, SpringLayout.WEST, IVs[0]);
layout.putConstraint(SpringLayout.NORTH, IVCategories[0], 2, SpringLayout.SOUTH, IVLabel);
for(int i = 1; i < IVs.length; i ++){
layout.putConstraint(SpringLayout.EAST, IVCategories[i], -10, SpringLayout.WEST, IVs[i]);
layout.putConstraint(SpringLayout.NORTH, IVCategories[i], 2, SpringLayout.SOUTH, IVs[i - 1]);
}
//EVs Label
layout.putConstraint(SpringLayout.WEST, EVLabel, 200, SpringLayout.WEST, IVLabel);
layout.putConstraint(SpringLayout.NORTH, EVLabel, 0, SpringLayout.NORTH, IVLabel);
//EVs
layout.putConstraint(SpringLayout.WEST, EVs[0], 100, SpringLayout.WEST, EVLabel);
layout.putConstraint(SpringLayout.NORTH, EVs[0], 2, SpringLayout.SOUTH, EVLabel);
for(int i = 1; i < EVs.length; i ++){
layout.putConstraint(SpringLayout.WEST, EVs[i], 0, SpringLayout.WEST, EVs[i - 1]);
layout.putConstraint(SpringLayout.NORTH, EVs[i], 2, SpringLayout.SOUTH, EVs[i - 1]);
}
//EV Labels
layout.putConstraint(SpringLayout.EAST, EVCategories[0], -10, SpringLayout.WEST, EVs[0]);
layout.putConstraint(SpringLayout.NORTH, EVCategories[0], 2, SpringLayout.SOUTH, EVLabel);
for(int i = 1; i < EVs.length; i ++){
layout.putConstraint(SpringLayout.EAST, EVCategories[i], -10, SpringLayout.WEST, EVs[i]);
layout.putConstraint(SpringLayout.NORTH, EVCategories[i], 2, SpringLayout.SOUTH, EVs[i - 1]);
}
//Pokemon Picture
layout.putConstraint(SpringLayout.EAST, pokemonImage, -10, SpringLayout.EAST, panel);
layout.putConstraint(SpringLayout.NORTH, pokemonImage, 10, SpringLayout.NORTH, panel);
//Add Pokemon Button
layout.putConstraint(SpringLayout.EAST, addButton, -10, SpringLayout.EAST, panel);
layout.putConstraint(SpringLayout.NORTH, addButton, 20, SpringLayout.SOUTH, pokemonImage);
//Edit Pokemon Button
layout.putConstraint(SpringLayout.EAST, editButton, 0, SpringLayout.EAST, addButton);
layout.putConstraint(SpringLayout.NORTH, editButton, 10, SpringLayout.SOUTH, addButton);
//Remove Pokemon Button
layout.putConstraint(SpringLayout.EAST, removeButton, 0, SpringLayout.EAST, editButton);
layout.putConstraint(SpringLayout.NORTH, removeButton, 10, SpringLayout.SOUTH, editButton);
updateComboBox();
}
public void updateComboBox(){
sortList();
if(list.size() >= 0)
box.removeAllItems();
for(Pokemon item: list)
box.addItem(item);
if(list.size() == 0)
box.setPreferredSize(new Dimension(110, 25));
else
box.setPreferredSize(null);
updateAltsBox();
updateLabels();
}
public void updateAltsBox(){
if(selectedPokemon == null){
altsBox.setVisible(false);
return;
}
if(selectedPokemon.hasAlts()){
altsBox.removeAllItems();
for(String item: selectedPokemon.getAltNames())
altsBox.addItem(item);
altsBox.setVisible(true);
}
else{
altsBox.setVisible(false);
}
updateLabels();
}
public void updateLabels(){
try{
if(selectedPokemon != null){
try{
image = ImageIO.read(new File(selectedPokemon.getPictureFilePath()));
}
catch(Exception e){
image = ImageIO.read(new File("data/sprites/0.png"));
}
nature.setText(selectedPokemon.getNature());
level.setText("" + selectedPokemon.getLevel());
for(int i = 0; i < stats.length; i ++)
stats[i].setText("" + selectedPokemon.getStat(i));
for(int i = 0; i < IVs.length; i ++)
IVs[i].setText("" + selectedPokemon.getIV(i));
for(int i = 0; i < EVs.length; i ++)
EVs[i].setText("" + selectedPokemon.getEV(i));
}
else{
image = ImageIO.read(new File("data/sprites/0.png"));
nature.setText("N/A");
level.setText("" + 0);
for(int i = 0; i < stats.length; i ++){
stats[i].setText("" + 0);
IVs[i].setText("" + 0);
EVs[i].setText("" + 0);
}
}
pokemonImage.setIcon(new ImageIcon(image));
}
catch(IOException ioe){
JOptionPane.showMessageDialog(null, "There was an error loading the pokemon's image.", null, JOptionPane.ERROR_MESSAGE);
}
}
public void sortList(){
Comparator<Pokemon> comparator = new Comparator<Pokemon>(){
@Override
public int compare(Pokemon poke1, Pokemon poke2){
int temp = poke1.getNumber() - poke2.getNumber();
return temp;
}
};
Collections.sort(list, comparator);
}
public class AddDialog extends JDialog{
private static final long serialVersionUID = 9203359372448814899L;
private JPanel panel;
private JCheckBox shinyCheck;
private JComboBox addBox;
private JComboBox<String> natureBox;
private String[] natures = {"Hardy", "Lonely", "Brave", "Adamant", "Naughty",
"Bold", "Docile", "Relaxed", "Impish", "Lax",
"Timid", "Hasty", "Serious", "Jolly", "Naive",
"Modest", "Mild", "Quiet", "Bashful", "Rash",
"Calm", "Gentle", "Sassy", "Careful", "Quirky"};
private ArrayList<BasicPokemon> allPokes;
private BasicPokemon selectedBasicPokemon;
private int natureIndex;
private boolean shiny;
private JLabel[] baseStats = new JLabel[6];
private JNumberTextField[] IVFields = new JNumberTextField[6];
private JNumberTextField[] EVFields = new JNumberTextField[6];
private JNumberTextField levelField;
private JLabel baseStatLabel = new JLabel("Base Stats:");
private JLabel IVLabel = new JLabel("IVs:");
private JLabel EVLabel = new JLabel("EVs:");
private JLabel levelLabel = new JLabel("Level:");
private JLabel[] categories = {new JLabel("HP"),
new JLabel("Att"),
new JLabel("Def"),
new JLabel("Speed"),
new JLabel("Sp. Att"),
new JLabel("Sp. Def")};
public AddDialog(JFrame owner){
super(owner, "Add Pokemon");
SpringLayout layout = new SpringLayout();
panel = new JPanel();
panel.setLayout(layout);
setContentPane(panel);
setSize(425, 240);
setResizable(false);
Dimension resolution = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((int)((resolution.getWidth() - getWidth()) / 2), (int)((resolution.getHeight() - getHeight()) / 2));
allPokes = getAllPokemon();
String[] pokeNames = new String[allPokes.size()];
for(int i = 0; i < allPokes.size(); i ++){
BasicPokemon current = allPokes.get(i);
pokeNames[i] = current.getNumber() + " " + current.getName();
}
addBox = new JComboBox(allPokes.toArray());
addBox.setEditable(false);
addBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox cb = (JComboBox)e.getSource();
selectedBasicPokemon = allPokes.get(cb.getSelectedIndex());
updateBaseStatLabels();
}
});
shinyCheck = new JCheckBox("Shiny");
shinyCheck.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.DESELECTED)
shiny = false;
else
shiny = true;
}
});
natureBox = new JComboBox<String>(natures);
natureBox.setEditable(false);
natureBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox<String> cb = (JComboBox<String>)e.getSource();
natureIndex = cb.getSelectedIndex();
}
});
selectedBasicPokemon = allPokes.get(addBox.getSelectedIndex());
for(int i = 0; i < baseStats.length; i ++)
baseStats[i] = new JLabel("" + selectedBasicPokemon.getBaseStat(i));
for(int i = 0; i < IVFields.length; i ++){
IVFields[i] = new JNumberTextField(2);
IVFields[i].setColumns(3);
IVFields[i].setAllowNegative(false);
EVFields[i] = new JNumberTextField(3);
EVFields[i].setColumns(3);
EVFields[i].setAllowNegative(false);
}
levelField = new JNumberTextField(3);
levelField.setColumns(3);
JButton finishedButton = new JButton("Add");
finishedButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
int[] IVs = new int[IVFields.length];
int[] EVs = new int[EVFields.length];
for(int i = 0; i < IVFields.length; i ++){
if(IVFields[i].getText().length() == 0){
JOptionPane.showMessageDialog(null, "One of the IV fields is empty.", null, JOptionPane.WARNING_MESSAGE);
return;
}
IVs[i] = IVFields[i].getInt();
}
for(int i = 0; i < EVFields.length; i ++){
if(EVFields[i].getText().length() == 0){
JOptionPane.showMessageDialog(null, "One of the EV fields is empty.", null, JOptionPane.WARNING_MESSAGE);
return;
}
EVs[i] = EVFields[i].getInt();
}
if(levelField.getText().length() == 0){
JOptionPane.showMessageDialog(null, "The level field is empty.", null, JOptionPane.WARNING_MESSAGE);
return;
}
if(levelField.getInt() > 100){
JOptionPane.showMessageDialog(null, "You can't have more than 100 levels.", null, JOptionPane.WARNING_MESSAGE);
return;
}
for(int i = 0; i < IVFields.length; i ++){
if(IVFields[i].getInt() > 31 || IVFields[i].getInt() < 0){
JOptionPane.showMessageDialog(null, "You can't have more than 31 in an IV.", null, JOptionPane.WARNING_MESSAGE);
return;
}
}
int totalEVs = 0;
for(int i = 0; i < EVFields.length; i ++){
totalEVs += EVFields[i].getInt();
if(EVFields[i].getInt() > 255 || EVFields[i].getInt() < 0){
JOptionPane.showMessageDialog(null, "You can't have more than 255 in an EV.", null, JOptionPane.WARNING_MESSAGE);
return;
}
}
if(totalEVs > 510){
JOptionPane.showMessageDialog(null, "You can't have more than 510 total EVs.", null, JOptionPane.WARNING_MESSAGE);
return;
}
int level = levelField.getInt();
list.add(new Pokemon(selectedBasicPokemon.getNumber(), level, IVs, EVs, natureIndex, shiny));
updateComboBox();
dispose();
}catch (IOException ioe){
JOptionPane.showMessageDialog(null, "There was an error loading one of the fields.", null, JOptionPane.ERROR_MESSAGE);
}
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
for(JLabel label: baseStats)
add(label);
for(JNumberTextField field: IVFields)
add(field);
for(JNumberTextField field: EVFields)
add(field);
add(addBox);
add(natureBox);
add(shinyCheck);
add(levelField);
add(baseStatLabel);
add(IVLabel);
add(EVLabel);
add(levelLabel);
for(JLabel label: categories)
add(label);
add(finishedButton);
add(cancelButton);
//Combo addBox
layout.putConstraint(SpringLayout.WEST, addBox, 10, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, addBox, 10, SpringLayout.NORTH, panel);
//Nature Combo addBox
layout.putConstraint(SpringLayout.WEST, natureBox, 10, SpringLayout.EAST, addBox);
layout.putConstraint(SpringLayout.NORTH, natureBox, 0, SpringLayout.NORTH, addBox);
//Shiny Checkbox
layout.putConstraint(SpringLayout.WEST, shinyCheck, 10, SpringLayout.EAST, natureBox);
layout.putConstraint(SpringLayout.NORTH, shinyCheck, 0, SpringLayout.NORTH, natureBox);
//Level Label
layout.putConstraint(SpringLayout.WEST, levelLabel, 0, SpringLayout.WEST, addBox);
layout.putConstraint(SpringLayout.NORTH, levelLabel, 10, SpringLayout.SOUTH, addBox);
//Level Field
layout.putConstraint(SpringLayout.WEST, levelField, 5, SpringLayout.EAST, levelLabel);
layout.putConstraint(SpringLayout.NORTH, levelField, 0, SpringLayout.NORTH, levelLabel);
//Categories
layout.putConstraint(SpringLayout.WEST, categories[0], 20, SpringLayout.EAST, baseStatLabel);
layout.putConstraint(SpringLayout.NORTH, categories[0], 0, SpringLayout.NORTH, levelLabel);
for(int i = 1; i < categories.length; i ++){
layout.putConstraint(SpringLayout.WEST, categories[i], 50 * i, SpringLayout.WEST, categories[0]);
layout.putConstraint(SpringLayout.NORTH, categories[i], 0, SpringLayout.NORTH, categories[i - 1]);
}
//Stats Label
layout.putConstraint(SpringLayout.WEST, baseStatLabel, 0, SpringLayout.WEST, levelLabel);
layout.putConstraint(SpringLayout.NORTH, baseStatLabel, 10, SpringLayout.SOUTH, categories[0]);
//Stats
layout.putConstraint(SpringLayout.WEST, baseStats[0], 0, SpringLayout.WEST, categories[0]);
layout.putConstraint(SpringLayout.NORTH, baseStats[0], 0, SpringLayout.NORTH, baseStatLabel);
for(int i = 1; i < baseStats.length; i ++){
layout.putConstraint(SpringLayout.WEST, baseStats[i], 0, SpringLayout.WEST, categories[i]);
layout.putConstraint(SpringLayout.NORTH, baseStats[i], 0, SpringLayout.NORTH, baseStatLabel);
}
//IVs Label
layout.putConstraint(SpringLayout.WEST, IVLabel, 0, SpringLayout.WEST, baseStatLabel);
layout.putConstraint(SpringLayout.NORTH, IVLabel, 10, SpringLayout.SOUTH, baseStatLabel);
//IV Fields
layout.putConstraint(SpringLayout.WEST, IVFields[0], 0, SpringLayout.WEST, categories[0]);
layout.putConstraint(SpringLayout.NORTH, IVFields[0], 0, SpringLayout.NORTH, IVLabel);
for(int i = 1; i < IVFields.length; i ++){
layout.putConstraint(SpringLayout.WEST, IVFields[i], 0, SpringLayout.WEST, baseStats[i]);
layout.putConstraint(SpringLayout.NORTH, IVFields[i], 0, SpringLayout.NORTH, IVFields[i - 1]);
}
//EVs Label
layout.putConstraint(SpringLayout.WEST, EVLabel, 0, SpringLayout.WEST, IVLabel);
layout.putConstraint(SpringLayout.NORTH, EVLabel, 10, SpringLayout.SOUTH, IVLabel);
//EV Fields
layout.putConstraint(SpringLayout.WEST, EVFields[0], 0, SpringLayout.WEST, categories[0]);
layout.putConstraint(SpringLayout.NORTH, EVFields[0], 0, SpringLayout.NORTH, EVLabel);
for(int i = 1; i < EVFields.length; i ++){
layout.putConstraint(SpringLayout.WEST, EVFields[i], 0, SpringLayout.WEST, IVFields[i]);
layout.putConstraint(SpringLayout.NORTH, EVFields[i], 0, SpringLayout.NORTH, EVFields[i - 1]);
}
//Button
layout.putConstraint(SpringLayout.WEST, finishedButton, 0, SpringLayout.WEST, levelLabel);
layout.putConstraint(SpringLayout.NORTH, finishedButton, 20, SpringLayout.SOUTH, EVLabel);
//Cancel Button
layout.putConstraint(SpringLayout.WEST, cancelButton, 10, SpringLayout.EAST, finishedButton);
layout.putConstraint(SpringLayout.NORTH, cancelButton, 0, SpringLayout.NORTH, finishedButton);
}
public void updateBaseStatLabels(){
if(selectedBasicPokemon != null){
for(int i = 0; i < baseStats.length; i ++)
baseStats[i].setText("" + selectedBasicPokemon.getBaseStat(i));
}
else{
for(int i = 0; i < baseStats.length; i ++)
baseStats[i].setText("" + 0);
}
}
public ArrayList<BasicPokemon> getAllPokemon(){
ArrayList<BasicPokemon> pokes = new ArrayList<BasicPokemon>();
try{
FileInputStream in = new FileInputStream("data/database.bpok");
ObjectInputStream ois = new ObjectInputStream(in);
while(true){
try{
pokes.add((BasicPokemon)ois.readObject());
}
catch(Exception e1){
break;
}
}
for(int i = 0; i < pokes.size() - 1; i ++)
if(pokes.get(i).getNumber() == pokes.get(i + 1).getNumber()){
pokes.remove(i + 1);
i --;
}
ois.close();
}catch(Exception e){
e.printStackTrace();
}
return pokes;
}
}
public class EditDialog extends JDialog{
private static final long serialVersionUID = 5903170603141690106L;
private JPanel panel;
private JCheckBox shinyCheck;
private JComboBox editBox;
private JComboBox<String> natureBox;
private String[] natures = {"Hardy", "Lonely", "Brave", "Adamant", "Naughty",
"Bold", "Docile", "Relaxed", "Impish", "Lax",
"Timid", "Hasty", "Serious", "Jolly", "Naive",
"Modest", "Mild", "Quiet", "Bashful", "Rash",
"Calm", "Gentle", "Sassy", "Careful", "Quirky"};
private Pokemon selectedEditPokemon;
private int natureIndex;
private boolean shiny;
private JLabel[] baseStats = new JLabel[6];
private JNumberTextField[] IVFields = new JNumberTextField[6];
private JNumberTextField[] EVFields = new JNumberTextField[6];
private JNumberTextField levelField;
private JLabel baseStatLabel = new JLabel("Base Stats:");
private JLabel IVLabel = new JLabel("IVs:");
private JLabel EVLabel = new JLabel("EVs:");
private JLabel levelLabel = new JLabel("Level:");
private JLabel[] categories = {new JLabel("HP"),
new JLabel("Att"),
new JLabel("Def"),
new JLabel("Speed"),
new JLabel("Sp. Att"),
new JLabel("Sp. Def")};
public EditDialog(JFrame owner){
super(owner, "Modify Pokemon");
SpringLayout layout = new SpringLayout();
panel = new JPanel();
panel.setLayout(layout);
setContentPane(panel);
setSize(425, 240);
setResizable(false);
Dimension resolution = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((int)((resolution.getWidth() - getWidth()) / 2), (int)((resolution.getHeight() - getHeight()) / 2));
editBox = new JComboBox(list.toArray());
editBox.setEditable(false);
editBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox cb = (JComboBox)e.getSource();
selectedEditPokemon = list.get(cb.getSelectedIndex());
updateNumbers();
}
});
shinyCheck = new JCheckBox("Shiny");
shinyCheck.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.DESELECTED)
shiny = false;
else if(e.getStateChange() == ItemEvent.SELECTED)
shiny = true;
}
});
natureBox = new JComboBox<String>(natures);
natureBox.setEditable(false);
natureBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox<String> cb = (JComboBox<String>)e.getSource();
natureIndex = cb.getSelectedIndex();
}
});
selectedEditPokemon = (Pokemon)editBox.getSelectedItem();
shinyCheck.setSelected(selectedEditPokemon.isShiny());
for(int i = 0; i < baseStats.length; i ++)
baseStats[i] = new JLabel("" + selectedEditPokemon.getBaseStat(i));
for(int i = 0; i < IVFields.length; i ++){
IVFields[i] = new JNumberTextField(2);
IVFields[i].setColumns(3);
IVFields[i].setAllowNegative(false);
EVFields[i] = new JNumberTextField(3);
EVFields[i].setColumns(3);
EVFields[i].setAllowNegative(false);
}
levelField = new JNumberTextField(3);
levelField.setColumns(3);
JButton finishedButton = new JButton("Done");
finishedButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
list.remove(selectedEditPokemon);
int[] IVs = new int[IVFields.length];
int[] EVs = new int[EVFields.length];
for(int i = 0; i < IVFields.length; i ++){
if(IVFields[i].getText().length() == 0){
JOptionPane.showMessageDialog(null, "One of the IV fields is empty.", null, JOptionPane.WARNING_MESSAGE);
return;
}
IVs[i] = IVFields[i].getInt();
}
for(int i = 0; i < EVFields.length; i ++){
if(EVFields[i].getText().length() == 0){
JOptionPane.showMessageDialog(null, "One of the EV fields is empty.", null, JOptionPane.WARNING_MESSAGE);
return;
}
EVs[i] = EVFields[i].getInt();
}
if(levelField.getText().length() == 0){
JOptionPane.showMessageDialog(null, "The level field is empty.", null, JOptionPane.WARNING_MESSAGE);
return;
}
if(levelField.getInt() > 100){
JOptionPane.showMessageDialog(null, "You can't have more than 100 levels.", null, JOptionPane.WARNING_MESSAGE);
return;
}
for(int i = 0; i < IVFields.length; i ++){
if(IVFields[i].getInt() > 31 || IVFields[i].getInt() < 0){
JOptionPane.showMessageDialog(null, "You can't have more than 31 in an IV.", null, JOptionPane.WARNING_MESSAGE);
return;
}
}
int totalEVs = 0;
for(int i = 0; i < EVFields.length; i ++){
totalEVs += EVFields[i].getInt();
if(EVFields[i].getInt() > 255 || EVFields[i].getInt() < 0){
JOptionPane.showMessageDialog(null, "You can't have more than 255 in an EV.", null, JOptionPane.WARNING_MESSAGE);
return;
}
}
if(totalEVs > 510){
JOptionPane.showMessageDialog(null, "You can't have more than 510 total EVs.", null, JOptionPane.WARNING_MESSAGE);
return;
}
int level = levelField.getInt();
list.add(new Pokemon(selectedEditPokemon.getNumber(), level, IVs, EVs, natureIndex, shiny));
updateComboBox();
dispose();
}catch (IOException ioe){
JOptionPane.showMessageDialog(null, "There was an error loading one of the fields.", null, JOptionPane.ERROR_MESSAGE);
}
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
updateNumbers();
for(JLabel label: baseStats)
add(label);
for(JNumberTextField field: IVFields)
add(field);
for(JNumberTextField field: EVFields)
add(field);
add(editBox);
add(natureBox);
add(shinyCheck);
add(levelField);
add(baseStatLabel);
add(IVLabel);
add(EVLabel);
add(levelLabel);
for(JLabel label: categories)
add(label);
add(finishedButton);
add(cancelButton);
//Combo addBox
layout.putConstraint(SpringLayout.WEST, editBox, 10, SpringLayout.WEST, panel);
layout.putConstraint(SpringLayout.NORTH, editBox, 10, SpringLayout.NORTH, panel);
//Nature Combo addBox
layout.putConstraint(SpringLayout.WEST, natureBox, 10, SpringLayout.EAST, editBox);
layout.putConstraint(SpringLayout.NORTH, natureBox, 0, SpringLayout.NORTH, editBox);
//Shiny Checkbox
layout.putConstraint(SpringLayout.WEST, shinyCheck, 10, SpringLayout.EAST, natureBox);
layout.putConstraint(SpringLayout.NORTH, shinyCheck, 0, SpringLayout.NORTH, natureBox);
//Level Label
layout.putConstraint(SpringLayout.WEST, levelLabel, 0, SpringLayout.WEST, editBox);
layout.putConstraint(SpringLayout.NORTH, levelLabel, 10, SpringLayout.SOUTH, editBox);
//Level Field
layout.putConstraint(SpringLayout.WEST, levelField, 5, SpringLayout.EAST, levelLabel);
layout.putConstraint(SpringLayout.NORTH, levelField, 0, SpringLayout.NORTH, levelLabel);
//Categories
layout.putConstraint(SpringLayout.WEST, categories[0], 20, SpringLayout.EAST, baseStatLabel);
layout.putConstraint(SpringLayout.NORTH, categories[0], 0, SpringLayout.NORTH, levelLabel);
for(int i = 1; i < categories.length; i ++){
layout.putConstraint(SpringLayout.WEST, categories[i], 50 * i, SpringLayout.WEST, categories[0]);
layout.putConstraint(SpringLayout.NORTH, categories[i], 0, SpringLayout.NORTH, categories[i - 1]);
}
//Stats Label
layout.putConstraint(SpringLayout.WEST, baseStatLabel, 0, SpringLayout.WEST, levelLabel);
layout.putConstraint(SpringLayout.NORTH, baseStatLabel, 10, SpringLayout.SOUTH, categories[0]);
//Stats
layout.putConstraint(SpringLayout.WEST, baseStats[0], 0, SpringLayout.WEST, categories[0]);
layout.putConstraint(SpringLayout.NORTH, baseStats[0], 0, SpringLayout.NORTH, baseStatLabel);
for(int i = 1; i < baseStats.length; i ++){
layout.putConstraint(SpringLayout.WEST, baseStats[i], 0, SpringLayout.WEST, categories[i]);
layout.putConstraint(SpringLayout.NORTH, baseStats[i], 0, SpringLayout.NORTH, baseStatLabel);
}
//IVs Label
layout.putConstraint(SpringLayout.WEST, IVLabel, 0, SpringLayout.WEST, baseStatLabel);
layout.putConstraint(SpringLayout.NORTH, IVLabel, 10, SpringLayout.SOUTH, baseStatLabel);
//IV Fields
layout.putConstraint(SpringLayout.WEST, IVFields[0], 0, SpringLayout.WEST, categories[0]);
layout.putConstraint(SpringLayout.NORTH, IVFields[0], 0, SpringLayout.NORTH, IVLabel);
for(int i = 1; i < IVFields.length; i ++){
layout.putConstraint(SpringLayout.WEST, IVFields[i], 0, SpringLayout.WEST, baseStats[i]);
layout.putConstraint(SpringLayout.NORTH, IVFields[i], 0, SpringLayout.NORTH, IVFields[i - 1]);
}
//EVs Label
layout.putConstraint(SpringLayout.WEST, EVLabel, 0, SpringLayout.WEST, IVLabel);
layout.putConstraint(SpringLayout.NORTH, EVLabel, 10, SpringLayout.SOUTH, IVLabel);
//EV Fields
layout.putConstraint(SpringLayout.WEST, EVFields[0], 0, SpringLayout.WEST, categories[0]);
layout.putConstraint(SpringLayout.NORTH, EVFields[0], 0, SpringLayout.NORTH, EVLabel);
for(int i = 1; i < EVFields.length; i ++){
layout.putConstraint(SpringLayout.WEST, EVFields[i], 0, SpringLayout.WEST, IVFields[i]);
layout.putConstraint(SpringLayout.NORTH, EVFields[i], 0, SpringLayout.NORTH, EVFields[i - 1]);
}
//Button
layout.putConstraint(SpringLayout.WEST, finishedButton, 0, SpringLayout.WEST, levelLabel);
layout.putConstraint(SpringLayout.NORTH, finishedButton, 20, SpringLayout.SOUTH, EVLabel);
//Cancel Button
layout.putConstraint(SpringLayout.WEST, cancelButton, 10, SpringLayout.EAST, finishedButton);
layout.putConstraint(SpringLayout.NORTH, cancelButton, 0, SpringLayout.NORTH, finishedButton);
}
public void updateNumbers(){
if(selectedEditPokemon != null){
natureBox.setSelectedItem(selectedEditPokemon.getNature());
levelField.setNumber(selectedEditPokemon.getLevel());
for(int i = 0; i < IVFields.length; i ++){
IVFields[i].setNumber(selectedEditPokemon.getIV(i));
EVFields[i].setNumber(selectedEditPokemon.getEV(i));
}
for(int i = 0; i < baseStats.length; i ++)
baseStats[i].setText("" + selectedEditPokemon.getBaseStat(i));
}
else{
for(int i = 0; i < baseStats.length; i ++)
baseStats[i].setText("" + 0);
}
}
public ArrayList<BasicPokemon> getAllPokemon(){
ArrayList<BasicPokemon> pokes = new ArrayList<BasicPokemon>();
try{
FileInputStream in = new FileInputStream("data/database.bpok");
ObjectInputStream ois = new ObjectInputStream(in);
while(true){
try{
pokes.add((BasicPokemon)ois.readObject());
}
catch(Exception e1){
break;
}
}
ois.close();
}catch(Exception e){
e.printStackTrace();
}
return pokes;
}
}
} | 44.115162 | 178 | 0.546866 |
bb85167070a3d6420cdc4806ade46aaea842df5d | 3,510 | /*
* Project Sc2gears
*
* Copyright (c) 2010 Andras Belicza <[email protected]>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the authors permission
* is prohibited and protected by Law.
*/
package hu.belicza.andras.sc2gearsdb.datastore;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import com.google.appengine.api.datastore.Key;
/**
* Top score table of the Mouse practice game.
*
* <p><b>Class format version history:</b>
* <ol>
* <li>Added the class format version <code>"v"</code> property.
* <br>Made <code>userAgent</code>, <code>country</code> properties unindexed (as part of {@link ClientTrackedObject}).
* <br>Made {@link #userName}, {@link #accuracy}, {@link #hits}, {@link #gameLength}, {@link #gameVersion}, {@link #randomSeed} properties unindexed.
* </ol></p>
*
* @author Andras Belicza
*/
@PersistenceCapable
public class MousePracticeGameScore extends ClientTrackedObject {
/** Key of the account. */
@Persistent
private Key accountKey;
/** User name to appear in the top score table. */
@Persistent
@Extension(vendorName="datanucleus", key="gae.unindexed", value="true")
private String userName;
/** Score. */
@Persistent
private int score;
/** Accuracy. */
@Persistent
@Extension(vendorName="datanucleus", key="gae.unindexed", value="true")
private float accuracy;
/** Hits. */
@Persistent
@Extension(vendorName="datanucleus", key="gae.unindexed", value="true")
private int hits;
/** Game length in milliseconds. */
@Persistent
@Extension(vendorName="datanucleus", key="gae.unindexed", value="true")
private int gameLength;
/** Version of the game. */
@Persistent
@Extension(vendorName="datanucleus", key="gae.unindexed", value="true")
private String gameVersion;
/** Start random seed of the game. */
@Persistent
@Extension(vendorName="datanucleus", key="gae.unindexed", value="true")
private Long randomSeed;
/**
* Creates a new MousePracticeGameScore.
*/
public MousePracticeGameScore() {
setV( 1 );
}
public Key getAccountKey() {
return accountKey;
}
public void setAccountKey( Key accountKey ) {
this.accountKey = accountKey;
}
public String getUserName() {
return userName;
}
public void setUserName( String userName ) {
this.userName = userName;
}
public int getScore() {
return score;
}
public void setScore( int score ) {
this.score = score;
}
public void setAccuracy( float accuracy ) {
this.accuracy = accuracy;
}
public float getAccuracy() {
return accuracy;
}
public int getHits() {
return hits;
}
public void setHits( int hits ) {
this.hits = hits;
}
public int getGameLength() {
return gameLength;
}
public void setGameLength( int gameLength ) {
this.gameLength = gameLength;
}
public String getGameVersion() {
return gameVersion;
}
public void setGameVersion( String gameVersion ) {
this.gameVersion = gameVersion;
}
public void setRandomSeed( Long randomSeed ) {
this.randomSeed = randomSeed;
}
public Long getRandomSeed() {
return randomSeed;
}
}
| 24.545455 | 153 | 0.64188 |
4c0d36eaa928fbe053f767122cc12914613eb3a1 | 1,328 | package com.github.dockerjava.jaxrs;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import javax.ws.rs.client.WebTarget;
import org.apache.commons.codec.binary.Base64;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.AuthConfigurations;
public abstract class AbstrDockerCmdExec {
private WebTarget baseResource;
public AbstrDockerCmdExec(WebTarget baseResource) {
checkNotNull(baseResource, "baseResource was not specified");
this.baseResource = baseResource;
}
protected WebTarget getBaseResource() {
return baseResource;
}
protected String registryAuth(AuthConfig authConfig) {
try {
return Base64.encodeBase64String(new ObjectMapper().writeValueAsString(authConfig).getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
protected String registryConfigs(AuthConfigurations authConfigs) {
try {
String json = new ObjectMapper().writeValueAsString(authConfigs.getConfigs());
return Base64.encodeBase64String(json.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 28.869565 | 107 | 0.708584 |
6d24dd8622d107967e030ab02d048b65439cf522 | 316 | package com.facebook.jni;
import com.facebook.proguard.annotations.DoNotStrip;
@DoNotStrip
public class NativeRunnable implements Runnable {
private final HybridData mHybridData;
public native void run();
private NativeRunnable(HybridData hybridData) {
this.mHybridData = hybridData;
}
}
| 21.066667 | 52 | 0.753165 |
943911908e5b78bd1a2703397ecbfadeb4059f97 | 4,391 | package com.c4soft.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <h1>/!\ Do not use for production purpose /!\</h1> Helper class for CSV
* records (i.e. CSV lines).<br>
* Unquoted empty values are interpreted as null values.<br>
* Non double-quoted values are trimmed.<br>
* Double quotes are not allowed in fields values (no possible escaping) =>
* results in hazardous CSV line interpretation or Runtime exception when
* constructing from fields.
*
* @author ch4mp
*/
public class CsvRecord {
/**
* Capture pattern for any field but the last one
*/
public static final Pattern FIELDS_REGEX = Pattern.compile("(?:(?:\\s*\"([^\"]*)\"[^,\"]*)|([^,\"]*)),");
/**
* Capture pattern for the last field
*/
public static final Pattern LAST_FIELD_REGEX = Pattern.compile(",?(?:(?:\\s*\"([^\"]*)\"[^,\"]*)|([^,\"]*))$");
private final List<String> fields;
/**
* Splits a CSV line into records and constructs a record out of it
*
* @param line
* a CSV line
*/
public CsvRecord(String line) {
Matcher fieldsMatcher = FIELDS_REGEX.matcher(line);
fields = new ArrayList<String>();
while (fieldsMatcher.find()) {
fields.add(extractField(fieldsMatcher));
}
Matcher lastFieldMatcher = LAST_FIELD_REGEX.matcher(line);
if (lastFieldMatcher.find()) {
fields.add(extractField(lastFieldMatcher));
}
}
/**
* Constructs a record out of it's values
*
* @param someFields
* array containing fields values
* @throws NotImplementedException
* if a field contains double quotes
*/
public CsvRecord(String[] someFields) {
this.fields = new ArrayList<String>(someFields.length);
for (String field : someFields) {
if (field.contains("\"")) {
throw new NotImplementedException("CsvRecord does not currently allow quotes in fields: " + field);
}
this.fields.add(field);
}
}
/**
* Constructs a record out of it's values
*
* @param someFields
* collection containing fields values
* @throws NotImplementedException
* if a field contains double quotes
*/
public CsvRecord(Collection<String> someFields) {
this(someFields.toArray(new String[someFields.size()]));
}
/**
* Returns the field at the specified position in this record.
*
* @param idx
* index of the element to return
* @return the field at the specified position in this record
* @throws IndexOutOfBoundsException
* - if the index is out of range (idx < 0 || idx >= size())
*/
public String get(int idx) {
return fields.get(idx);
}
/**
* Returns the number of fields in this record.
*
* @return the number of fields in this record
*/
public int size() {
return fields.size();
}
/**
* Turns a collection of fields into a CSV line
*
* @return CSV line (quoted fields with comma separator)
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (String field : fields) {
if (isFirst) {
isFirst = false;
} else {
sb.append(',');
}
if (field != null) {
sb.append('"');
sb.append(field);
sb.append('"');
}
}
return sb.toString();
}
private static String extractField(Matcher m) {
String quotedField = m.group(1);
if (quotedField != null) {
return quotedField;
}
String unquotedField = m.group(2);
if (unquotedField == null || unquotedField.length() == 0) {
return null;
}
return unquotedField.trim();
}
public static final class NotImplementedException extends RuntimeException {
private static final long serialVersionUID = 4326901378545053667L;
public NotImplementedException(String msg) {
super(msg);
}
}
}
| 28.888158 | 115 | 0.571624 |
1a38c13f5bf40a2c9a496af44f91e12a1ece3ef3 | 2,042 | import java.util.Scanner;
/*
Program 388z Rock Paper Scissors
Wesley Rogers
2/8/16
Java 1.8u25, using Eclipse Mars
Windows 7
Plays a game of rock paper scissors against the computer.
What I learned: Not much, pretty simple.
Difficulties: The requirements for the program that were laid out in the doc were rather unintuitive as there are much better ways to store the information such as,
making the CPU just another player object, passing the player in a constructor so that we don't need to keep track of the name and throw, and ACTUALLY using the player object rather than it being there and doing nothing.
I knda had to shoehorn it in and it felt... awkward.
*/
public class GameDrive {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("What is your name? ");
String name = input.nextLine();
Player p = new Player(name);
System.out.println("1. Rock, 2. Paper, 3. Scissors");
System.out.print("What is your guess? ");
switch (input.nextInt()){
case 1: p.makeThrow('r'); break;
case 2: p.makeThrow('p'); break;
case 3: p.makeThrow('s'); break;
default: System.out.println("Play a number above!"); System.exit(1); //If they don't play a number from 1-3, exit out.
}
Game game = new Game();
game.makeCompThrow();
game.announceWinner(p.getName(), p.getThrow());
}
}
/*
What is your name? wes
1. Rock, 2. Paper, 3. Scissors
What is your guess? 1
The computer rolls: Paper!
The Computer wins!
What is your name? wes
1. Rock, 2. Paper, 3. Scissors
What is your guess? 2
The computer rolls: Paper!
There's a tie! Nobody wins!
What is your name? wes
1. Rock, 2. Paper, 3. Scissors
What is your guess? 3
The computer rolls: Paper!
wes wins!
*/ | 31.90625 | 225 | 0.619491 |
9e1975add3d802d8c6aab23ec8086d76e156a2ca | 1,390 | package com.riskvis.db.dao;
import java.util.List;
import com.riskvis.entity.TurnsHistoryHasPlacesrisksId;
/**
* @author <a href="http://machadolucas.me">machadolucas</a>
*
*/
public interface ITurnsHistoryHasPlacesrisksIdDAO {
/**
* Add TurnsHistoryHasPlacesrisksId
*
* @param TurnsHistoryHasPlacesrisksId
* turnsHistoryHasPlacesrisksId
*/
public void addTurnsHistoryHasPlacesrisksId(
TurnsHistoryHasPlacesrisksId turnsHistoryHasPlacesrisksId);
/**
* Update TurnsHistoryHasPlacesrisksId
*
* @param TurnsHistoryHasPlacesrisksId
* turnsHistoryHasPlacesrisksId
*/
public void updateTurnsHistoryHasPlacesrisksId(
TurnsHistoryHasPlacesrisksId turnsHistoryHasPlacesrisksId);
/**
* Delete TurnsHistoryHasPlacesrisksId
*
* @param TurnsHistoryHasPlacesrisksId
* turnsHistoryHasPlacesrisksId
*/
public void deleteTurnsHistoryHasPlacesrisksId(
TurnsHistoryHasPlacesrisksId turnsHistoryHasPlacesrisksId);
/**
* Get TurnsHistoryHasPlacesrisksId
*
* @param int TurnsHistoryHasPlacesrisksId Id
*/
public TurnsHistoryHasPlacesrisksId getTurnsHistoryHasPlacesrisksIdById(
int id);
/**
* Get TurnsHistoryHasPlacesrisksId List
*
*/
public List<TurnsHistoryHasPlacesrisksId> getTurnsHistoryHasPlacesrisksIds();
/**
* Get amount of turnsHistoryHasPlacesrisksId
*
*/
public int getCount();
}
| 23.166667 | 78 | 0.764029 |
b05b47b5be7e3bea8b2a031397a15351875d3f4e | 10,127 | /*
* Copyright © 2012-2014 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.tephra.persist;
import co.cask.tephra.ChangeId;
import co.cask.tephra.TransactionManager;
import co.cask.tephra.TransactionType;
import co.cask.tephra.TxConstants;
import co.cask.tephra.metrics.TxMetricsCollector;
import co.cask.tephra.snapshot.DefaultSnapshotCodec;
import co.cask.tephra.snapshot.SnapshotCodecProvider;
import co.cask.tephra.snapshot.SnapshotCodecV4;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.hadoop.conf.Configuration;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Runs transaction persistence tests against the {@link LocalFileTransactionStateStorage} and
* {@link LocalFileTransactionLog} implementations.
*/
public class LocalTransactionStateStorageTest extends AbstractTransactionStateStorageTest {
@ClassRule
public static TemporaryFolder tmpDir = new TemporaryFolder();
@Override
protected Configuration getConfiguration(String testName) throws IOException {
File testDir = tmpDir.newFolder(testName);
Configuration conf = new Configuration();
conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_LOCAL_DIR, testDir.getAbsolutePath());
conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, SnapshotCodecV4.class.getName());
return conf;
}
@Override
protected AbstractTransactionStateStorage getStorage(Configuration conf) {
return new LocalFileTransactionStateStorage(conf, new SnapshotCodecProvider(conf), new TxMetricsCollector());
}
// v2 TransactionEdit
@SuppressWarnings("deprecation")
private class TransactionEditV2 extends TransactionEdit {
public TransactionEditV2(long writePointer, long visibilityUpperBound, State state, long expirationDate,
Set<ChangeId> changes, long commitPointer, boolean canCommit, TransactionType type) {
super(writePointer, visibilityUpperBound, state, expirationDate, changes, commitPointer, canCommit, type,
null, 0L, 0L, null);
}
@Override
public void write(DataOutput out) throws IOException {
TransactionEditCodecs.encode(this, out, new TransactionEditCodecs.TransactionEditCodecV2());
}
}
// Note: this test cannot run in AbstractTransactionStateStorageTest, since SequenceFile throws exception saying
// TransactionEditV2 is not TransactionEdit. Since the code path this test is verifying is the same path between
// HDFS and Local Storage, having this only over here is fine.
@SuppressWarnings("deprecation")
@Test
public void testLongTxnBackwardsCompatibility() throws Exception {
Configuration conf = getConfiguration("testLongTxnBackwardsCompatibility");
// Use SnapshotCodec version 1
String latestSnapshotCodec = conf.get(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES);
conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, DefaultSnapshotCodec.class.getName());
TransactionStateStorage storage = null;
try {
storage = getStorage(conf);
storage.startAndWait();
// Create transaction snapshot and transaction edits with version when long running txns had -1 expiration.
Collection<Long> invalid = Lists.newArrayList();
NavigableMap<Long, TransactionManager.InProgressTx> inProgress = Maps.newTreeMap();
long time1 = System.currentTimeMillis();
long wp1 = time1 * TxConstants.MAX_TX_PER_MS;
inProgress.put(wp1, new TransactionManager.InProgressTx(wp1 - 5, -1L));
long time2 = time1 + 100;
long wp2 = time2 * TxConstants.MAX_TX_PER_MS;
inProgress.put(wp2, new TransactionManager.InProgressTx(wp2 - 50, time2 + 1000));
Map<Long, Set<ChangeId>> committing = Maps.newHashMap();
Map<Long, Set<ChangeId>> committed = Maps.newHashMap();
TransactionSnapshot snapshot = new TransactionSnapshot(time2, 0, wp2, invalid,
inProgress, committing, committed);
long time3 = time1 + 200;
long wp3 = time3 * TxConstants.MAX_TX_PER_MS;
TransactionEdit edit1 = new TransactionEditV2(wp3, wp3 - 10, TransactionEdit.State.INPROGRESS, -1L,
null, 0L, false, null);
long time4 = time1 + 300;
long wp4 = time4 * TxConstants.MAX_TX_PER_MS;
TransactionEdit edit2 = new TransactionEditV2(wp4, wp4 - 10, TransactionEdit.State.INPROGRESS, time4 + 1000,
null, 0L, false, null);
// write snapshot and transaction edit
storage.writeSnapshot(snapshot);
TransactionLog log = storage.createLog(time2);
log.append(edit1);
log.append(edit2);
log.close();
// Start transaction manager
conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, latestSnapshotCodec);
long longTimeout = TimeUnit.SECONDS.toMillis(conf.getLong(TxConstants.Manager.CFG_TX_LONG_TIMEOUT,
TxConstants.Manager.DEFAULT_TX_LONG_TIMEOUT));
TransactionManager txm = new TransactionManager(conf, storage, new TxMetricsCollector());
txm.startAndWait();
try {
// Verify that the txns in old format were read correctly.
// There should be four in-progress transactions, and no invalid transactions
TransactionSnapshot snapshot1 = txm.getCurrentState();
Assert.assertEquals(ImmutableSortedSet.of(wp1, wp2, wp3, wp4), snapshot1.getInProgress().keySet());
verifyInProgress(snapshot1.getInProgress().get(wp1), TransactionType.LONG, time1 + longTimeout);
verifyInProgress(snapshot1.getInProgress().get(wp2), TransactionType.SHORT, time2 + 1000);
verifyInProgress(snapshot1.getInProgress().get(wp3), TransactionType.LONG, time3 + longTimeout);
verifyInProgress(snapshot1.getInProgress().get(wp4), TransactionType.SHORT, time4 + 1000);
Assert.assertEquals(0, snapshot1.getInvalid().size());
} finally {
txm.stopAndWait();
}
} finally {
if (storage != null) {
storage.stopAndWait();
}
}
}
// Note: this test cannot run in AbstractTransactionStateStorageTest, since SequenceFile throws exception saying
// TransactionEditV2 is not TransactionEdit. Since the code path this test is verifying is the same path between
// HDFS and Local Storage, having this only over here is fine.
@SuppressWarnings("deprecation")
@Test
public void testAbortEditBackwardsCompatibility() throws Exception {
Configuration conf = getConfiguration("testAbortEditBackwardsCompatibility");
TransactionStateStorage storage = null;
try {
storage = getStorage(conf);
storage.startAndWait();
// Create edits for transaction type addition to abort
long time1 = System.currentTimeMillis();
long wp1 = time1 * TxConstants.MAX_TX_PER_MS;
TransactionEdit edit1 = new TransactionEditV2(wp1, wp1 - 10, TransactionEdit.State.INPROGRESS, -1L,
null, 0L, false, null);
TransactionEdit edit2 = new TransactionEditV2(wp1, 0L, TransactionEdit.State.ABORTED, 0L,
null, 0L, false, null);
long time2 = time1 + 400;
long wp2 = time2 * TxConstants.MAX_TX_PER_MS;
TransactionEdit edit3 = new TransactionEditV2(wp2, wp2 - 10, TransactionEdit.State.INPROGRESS, time2 + 10000,
null, 0L, false, null);
TransactionEdit edit4 = new TransactionEditV2(wp2, 0L, TransactionEdit.State.INVALID, 0L, null, 0L, false, null);
// Simulate case where we cannot determine txn state during abort
TransactionEdit edit5 = new TransactionEditV2(wp2, 0L, TransactionEdit.State.ABORTED, 0L, null, 0L, false, null);
// write snapshot and transaction edit
TransactionLog log = storage.createLog(time1);
log.append(edit1);
log.append(edit2);
log.append(edit3);
log.append(edit4);
log.append(edit5);
log.close();
// Start transaction manager
TransactionManager txm = new TransactionManager(conf, storage, new TxMetricsCollector());
txm.startAndWait();
try {
// Verify that the txns in old format were read correctly.
// Both transactions should be in invalid state
TransactionSnapshot snapshot1 = txm.getCurrentState();
Assert.assertEquals(ImmutableList.of(wp1, wp2), snapshot1.getInvalid());
Assert.assertEquals(0, snapshot1.getInProgress().size());
Assert.assertEquals(0, snapshot1.getCommittedChangeSets().size());
Assert.assertEquals(0, snapshot1.getCommittingChangeSets().size());
} finally {
txm.stopAndWait();
}
} finally {
if (storage != null) {
storage.stopAndWait();
}
}
}
private void verifyInProgress(TransactionManager.InProgressTx inProgressTx, TransactionType type,
long expiration) throws Exception {
Assert.assertEquals(type, inProgressTx.getType());
Assert.assertTrue(inProgressTx.getExpiration() == expiration);
}
}
| 46.242009 | 119 | 0.705342 |
b7df28a2e73bceaa56cc0af15bc4e23c190fef0e | 11,521 | package com.ufranco.userservice.services;
import com.ufranco.userservice.models.dto.QueryParams;
import com.ufranco.userservice.models.dto.Response;
import com.ufranco.userservice.models.dto.UserQueryResponse;
import com.ufranco.userservice.models.entities.User;
import com.ufranco.userservice.models.exceptions.InvalidField;
import com.ufranco.userservice.models.exceptions.InvalidQueryParametersException;
import com.ufranco.userservice.models.exceptions.InvalidUserFieldsException;
import com.ufranco.userservice.models.exceptions.abstracts.InvalidFieldsException;
import com.ufranco.userservice.repositories.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@Service
@Slf4j
public class UserService {
@Autowired
UserRepository repository;
public UserQueryResponse getUsers(QueryParams params) throws InvalidQueryParametersException {
validateForQuery(params);
Sort sort = Sort.by(
Sort.Direction.fromString(params.getOrder()),
params.getSortBy()
);
Pageable pageable = PageRequest.of(
params.getPage(),
params.getLimit(),
sort
);
log.debug("Executing User query under parameters: \n " + params);
List<User> queryResult = params.getName().isBlank() ?
repository.findAll(pageable).getContent() :
repository.findAllContainingIgnoreCase(params.getName(), pageable);
return new UserQueryResponse(
queryResult,
queryResult.size(),
List.of()
);
}
public Response getUser(Long id) throws InvalidUserFieldsException {
validateForGet(id);
User user = repository.findById(id).orElse(null);
return new Response(user, List.of());
}
public Response createUser(User user) throws InvalidUserFieldsException {
validateForCreate(user);
user = repository.save(user);
return new Response(user, List.of("User was created successfully."));
}
public Response updateUser(User user) throws InvalidFieldsException {
validateForUpdate(user);
user = repository.save(user);
return new Response(user, List.of("User was updated successfully"));
}
public Response deleteUser(Long id) throws InvalidUserFieldsException {
validateForDelete(id);
repository.deleteById(id);
User userDeleted = User.builder()
.id(id)
.build();
return new Response(
userDeleted,
List.of("User was deleted successfully.")
);
}
private void validateForQuery(QueryParams params) throws InvalidQueryParametersException {
List<InvalidField> invalidFields = new ArrayList<>();
validatePaginationParameters(params, invalidFields);
validateSortParameters(params, invalidFields);
if (!invalidFields.isEmpty()) throw new InvalidQueryParametersException(invalidFields);
}
private void validatePaginationParameters(QueryParams params, List<InvalidField> invalidFields) {
if (params.getPage() < 0) {
invalidFields.add(
InvalidField.builder()
.fieldName("page")
.messages(List.of("Page number cannot be negative."))
.build()
);
}
if(params.getLimit() < 1) {
invalidFields.add(
InvalidField.builder()
.fieldName("limit")
.messages(List.of("Page limit cannot be negative."))
.build()
);
} else if(params.getLimit() > 100) {
invalidFields.add(
InvalidField.builder()
.fieldName("limit")
.messages(List.of("Page limit is too large."))
.build()
);
}
}
private void validateSortParameters(QueryParams params, List<InvalidField> invalidFields) {
if (!(params.getOrder().equals("asc") || params.getOrder().equals("desc"))) {
invalidFields.add(
InvalidField.builder()
.fieldName("order")
.messages(List.of("Order parameter does not meet the requirements to make the query."))
.build()
);
}
if(params.getSortBy().equalsIgnoreCase("password")) {
invalidFields.add(
InvalidField.builder()
.fieldName("sortBy")
.messages(List.of("Sort By field not valid."))
.build()
);
} else {
try {
User.class.getDeclaredField(params.getSortBy().toLowerCase());
} catch (NoSuchFieldException e) {
invalidFields.add(
InvalidField.builder()
.fieldName("sortBy")
.messages(List.of("SortBy field does not exist."))
.build()
);
}
}
}
private void validateForGet(Long id) throws InvalidUserFieldsException {
List<InvalidField> invalidFields = new ArrayList<>();
idValidator(id, invalidFields);
if(!invalidFields.isEmpty()) throw new InvalidUserFieldsException(invalidFields);
}
private void validateForCreate(User user) throws InvalidUserFieldsException {
List<InvalidField> invalidFields = new ArrayList<>();
if(user.getId() != null) {
invalidFields.add(
InvalidField.builder()
.fieldName("id")
.messages(
List.of("Id cannot be manually defined")
)
.build()
);
}
usernameValidator(user.getUsername(), invalidFields);
displaynameValidator(user.getDisplayname(), invalidFields);
emailValidator(user.getEmail(), invalidFields);
passwordValidator(user.getPassword(), invalidFields);
if(invalidFields.isEmpty()) {
usernameAvailabilityValidator(user, invalidFields);
emailAvailabilityValidator(user, invalidFields);
}
if (!invalidFields.isEmpty()) throw new InvalidUserFieldsException(invalidFields);
}
private void validateForUpdate(User user) throws InvalidUserFieldsException {
List<InvalidField> invalidFields = new ArrayList<>();
idValidator(user.getId(), invalidFields);
usernameValidator(user.getUsername(), invalidFields);
displaynameValidator(user.getDisplayname(), invalidFields);
emailValidator(user.getEmail(), invalidFields);
passwordValidator(user.getPassword(), invalidFields);
if(invalidFields.isEmpty()) {
User userInDb = repository.findById(user.getId()).orElse(null);
assert userInDb != null;
if(user.getModifiedAt().before(userInDb.getModifiedAt())){
invalidFields.add(
InvalidField.builder()
.fieldName("modifiedAt")
.messages(
List.of("Version mismatch between data provided and data stored.")
)
.build()
);
}
if(!userInDb.getUsername().equals(user.getUsername())) {
usernameAvailabilityValidator(user, invalidFields);
}
if(!userInDb.getEmail().equals(user.getEmail())) {
emailAvailabilityValidator(user, invalidFields);
}
}
if(!invalidFields.isEmpty()) throw new InvalidUserFieldsException(invalidFields);
}
private void validateForDelete(Long id) throws InvalidUserFieldsException {
List<InvalidField> invalidFields = new ArrayList<>();
idValidator(id, invalidFields);
if (!invalidFields.isEmpty()) throw new InvalidUserFieldsException(invalidFields);
}
private void idValidator(Long id, List<InvalidField> invalidFields) {
List<String> messages = new ArrayList<>();
if ( id == null || id < 1) {
messages.add("Please provide a valid id.");
} else if (!repository.existsById(id)) {
messages.add("Id provided does not belong to any user.");
} else return;
invalidFields.add(
InvalidField.builder()
.fieldName("id")
.messages(messages)
.build()
);
}
private void usernameAvailabilityValidator(User user, List<InvalidField> invalidFields) {
if(repository.existsByUsername(user.getUsername())) {
invalidFields.add(
InvalidField.builder()
.fieldName("username")
.messages(List.of("Username already taken."))
.build()
);
}
}
private void emailAvailabilityValidator(User user, List<InvalidField> invalidFields) {
if(repository.existsByEmail(user.getEmail())) {
invalidFields.add(
InvalidField.builder()
.fieldName("email")
.messages(List.of("Email already taken."))
.build()
);
}
}
private void usernameValidator(String username, List<InvalidField> invalidFields) {
List<String> messages = new ArrayList<>();
if (username == null || username.isBlank()) {
messages.add("Please add an username.");
} else {
if (!Pattern.matches("^.{8,30}$", username)) {
messages.add("Username must have at least 6 characters and less than 30.");
}
if (Pattern.matches("^.*[^a-zA-Z0-9\\s]+.*$", username)) {
messages.add("Username must not have special characters nor blank spaces");
}
}
if(!messages.isEmpty()) {
invalidFields.add(
InvalidField.builder()
.fieldName("username")
.messages( messages)
.build()
);
}
}
private void displaynameValidator(String displayname, List<InvalidField> invalidFields) {
List<String> messages = new ArrayList<>();
if (displayname == null || displayname.isBlank()) {
messages.add("Please add a displayname.");
} else if (displayname.length() > 30) {
messages.add("Displayname cannot be larger than 30 characters.");
}
if(!messages.isEmpty()) {
invalidFields.add(
InvalidField.builder()
.fieldName("displayname")
.messages(messages)
.build()
);
}
}
private void emailValidator(String email, List<InvalidField> invalidFields) {
if (
email == null ||
email.isBlank() ||
!Pattern.matches("^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$", email)
) {
invalidFields.add(
InvalidField.builder()
.fieldName("email")
.messages(List.of("Please add a valid email."))
.build()
);
}
}
private void passwordValidator(String password, List<InvalidField> invalidFields) {
List<String> messages = new ArrayList<>();
if (password == null || password.isBlank()) {
messages.add("Please add a password");
} else {
if (!Pattern.matches("^.{8,50}$", password)) {
messages.add("Password must have at least 8 characters and less than 50.");
}
if (!Pattern.matches("^.*[0-9].*[0-9].*$", password)) {
messages.add("Password must have at least two digits.");
}
if (!Pattern.matches("^.*[a-z].*$", password)) {
messages.add("Password must have at least one lowercase character.");
}
if (!Pattern.matches("^.*[A-Z].*$", password)) {
messages.add("Password must have at least one uppercase character.");
}
if (Pattern.matches("^.*\\s.*$", password)) {
messages.add("Password must not contain white spaces.");
}
if (!Pattern.matches("^.*[^a-zA-Z0-9].*$", password)) {
messages.add("Password must have at least one special character.");
}
}
if(!messages.isEmpty()) {
invalidFields.add(
InvalidField.builder()
.fieldName("password")
.messages(messages)
.build()
);
}
}
}
| 29.84715 | 99 | 0.649423 |
65b3bee77865fbee1ed9779b1ad53c74d507d0d2 | 379 | package life.qbic.portal.portlet.model;
public class RoleAt {
String affiliation;
String role;
public String getAffiliation() {
return affiliation;
}
public String getRole() {
return role;
}
public RoleAt(String affiliation, String role) {
super();
this.affiliation = affiliation;
this.role = role;
}
} | 18.047619 | 52 | 0.609499 |
3a5cad6b9a96a7b9c12728e7c2a620500720f40e | 807 | package com.jyoryo.entityjdbc.builder;
import com.jyoryo.entityjdbc.support.Condition;
/**
* 基于模板和条件数据,动态构建sql
* @author jyoryo
*
*/
public interface SqlBuilder {
/**
* 通过id获取模板内容,将模板与数据解析返回解析后的sql内容
* @param sqlOrId SQL语句或对应SQL模板中的id。
* @param condition 条件
* @return
*/
String sql(String sqlOrId, Condition condition);
/**
* 设置标识sql ID的前缀符号
* @param idPrefix
*/
void setIdPrefix(char idPrefix);
/**
* 设置文件模板路径,支持classpath
* @param sqlFilePath
*/
void setSqlFilePath(String sqlFilePath);
/**
* 设置模板文件扩展名
* <li>不设置,则默认为<code>sqlt</code></li>
* @param extension
*/
void setSqlFileExtension(String extension);
/**
* 模板文件路径下文件变动是否自动重新加载
* @param autoReload
*/
void setAutoReload(boolean autoReload);
}
| 17.933333 | 50 | 0.648079 |
4a1ca8450cc9f84b3b4ac684f7950c7dc05ba726 | 2,475 | package com.space.cornerstone.system.domain.entity;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.space.cornerstone.framework.core.constant.Constant;
import com.space.cornerstone.framework.core.domain.entity.LogicDeleteEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
/**
* 用户表
*/
@Data
@Accessors(chain = true)
public class SysUser extends LogicDeleteEntity {
private static final long serialVersionUID = 6929137513399914731L;
/**
* 用户ID
*/
private Long id;
/**
* 部门ID
*/
private Long deptId;
/**
* 用户账号
*/
private String userName;
/**
* 登录来源 默认0 -本地
*/
private Integer source;
/**
* 用户昵称
*/
private String nickName;
/**
* 用户类型(ADMIN系统用户)
*/
private String type;
/**
* 用户邮箱
*/
private String email;
/**
* 手机号码
*/
private String phone;
/**
* 用户性别(0男 1女 2未知)
*/
private Integer sex;
/**
* 头像地址
*/
private String image;
/**
* 密码
*/
@JsonIgnore
@JsonProperty
private String password;
/**
* 最后登录IP
*/
private String loginIp;
/**
* 最后登录时间
*/
private LocalDateTime loginDate;
/**
* 是否锁住密码 true-是
*/
private Boolean lockFlag;
/**
* 备注
*/
private String remark;
/**
* 角色列表
*/
@TableField(exist = false)
private List<SysRole> roles;
@JsonIgnore
public SysUser cloneUpdate() {
SysUser sysUser = new SysUser()
.setUserName(getUserName())
.setId(getId())
.setEmail(getEmail())
.setPhone(getPhone())
.setDeptId(getDeptId())
.setRoles(getRoles())
.setNickName(getNickName())
.setRemark(getRemark())
.setImage(getImage())
.setSex(getSex())
.setType(getType());
sysUser.setActive(getActive());
return sysUser;
}
public boolean isAdmin() {
if (StrUtil.isEmpty(type)) {
return false;
}
return Objects.equals(Constant.USER_TYPE_ADMIN, type);
}
}
| 18.065693 | 76 | 0.563636 |
e415b20a0be6e938517dd7bb488ecc97aef9916b | 3,394 | package other;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.graphics.Color;
public class AppBgcolor {
private static int a = 1;
private static int red = 0;
private static int green = 0;
private static int blue = 0;
//getter
public static int getColor(String field)
{
if(field == "a"){
return a;
}
else if(field == "red"){
return red;
}
else if(field == "green"){
return green;
}
else if(field == "blue"){
return blue;
}
else{
return 0;
}
}
//setter
public static void setColor(String field, int value)
{
if(field == "a"){
AppBgcolor.a = value;
}
else if(field == "red"){
AppBgcolor.red = value;
}
else if(field == "green"){
AppBgcolor.green = value;
}
else if(field == "blue"){
AppBgcolor.blue = value;
}
}
public static void setActBgcolor(RelativeLayout root, TextView root1, TextView root2){
root.setBackgroundColor(Color.argb(a, red, green, blue));
root1.setTextColor(Color.argb(255, 0, 0, 0));
root2.setTextColor(Color.argb(255, 0, 0, 0));
if ((a == 255) && (red == 0) && (green == 0) && (blue == 0) ){
root1.setTextColor(Color.argb(255, 255, 255, 255));
root2.setTextColor(Color.argb(255, 255, 255, 255));
}
}
public static void setActBgcolor(RelativeLayout root, TextView root1){
root.setBackgroundColor(Color.argb(a, red, green, blue));
root1.setTextColor(Color.argb(255, 0, 0, 0));
if ((a == 255) && (red == 0) && (green == 0) && (blue == 0) ){
root1.setTextColor(Color.argb(255, 255, 255, 255));
}
}
public static void setActBgcolor(RelativeLayout root){
root.setBackgroundColor(Color.argb(a, red, green, blue));
}
public static void setActBgcolor(LinearLayout root){
root.setBackgroundColor(Color.argb(a, red, green, blue));
}
public static void setActBgcolor(CustomDrawableView root){
root.setBackgroundColor(Color.argb(a, red, green, blue));
}
public static void setActBgcolor(FrameLayout root){
root.setBackgroundColor(Color.argb(a, red, green, blue));
}
public static void setActBgcolor(
TableLayout root,
TextView root1, TextView root2, TextView root3, TextView root4,
TextView root5, TextView root6, TextView root7, TextView root8
){
root.setBackgroundColor(Color.argb(a, red, green, blue));
root1.setTextColor(Color.argb(255, 0, 0, 0));
root2.setTextColor(Color.argb(255, 0, 0, 0));
root3.setTextColor(Color.argb(255, 0, 0, 0));
root4.setTextColor(Color.argb(255, 0, 0, 0));
root5.setTextColor(Color.argb(255, 0, 0, 0));
root6.setTextColor(Color.argb(255, 0, 0, 0));
root7.setTextColor(Color.argb(255, 0, 0, 0));
root8.setTextColor(Color.argb(255, 0, 0, 0));
if ((a == 255) && (red == 0) && (green == 0) && (blue == 0) ){
root1.setTextColor(Color.argb(255, 255, 255, 255));
root2.setTextColor(Color.argb(255, 255, 255, 255));
root3.setTextColor(Color.argb(255, 255, 255, 255));
root4.setTextColor(Color.argb(255, 255, 255, 255));
root5.setTextColor(Color.argb(255, 255, 255, 255));
root6.setTextColor(Color.argb(255, 255, 255, 255));
root7.setTextColor(Color.argb(255, 255, 255, 255));
root8.setTextColor(Color.argb(255, 255, 255, 255));
}
}
}
| 29.258621 | 87 | 0.652917 |
924e672ec5c5041bf27a6a3f8dae9fed945f7167 | 1,039 | package de.garkolym.cp.commands.impl;
import de.garkolym.cp.Start;
import de.garkolym.cp.commands.Category;
import de.garkolym.cp.commands.CommandBase;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class Command_KICK extends CommandBase {
public Command_KICK() {
super("kick", "<Spieler> <Grund>" + " §d| " + ChatColor.GRAY + "Rauswerfen", Category.OTHER);
}
public void execute(String[] args, Player p) {
Bukkit.broadcastMessage(args[1]);
if (args.length == 2) {
try {
Bukkit.getScheduler().runTask(Start.INSTANCE, new Command_KICK2(this, args));
} catch (Exception var5) {
Bukkit.broadcastMessage(var5.getMessage());
}
} else {
try {
Bukkit.getScheduler().runTask(Start.INSTANCE, new Command_KICK3(this, args));
} catch (Exception var4) {
Bukkit.broadcastMessage(var4.getMessage());
}
}
}
}
| 30.558824 | 101 | 0.606352 |
60ed82ac5a92576e07ca84d9b4887da194854b23 | 7,594 | package beans.crud;
import com.kumuluz.ee.rest.beans.QueryParameters;
import com.kumuluz.ee.rest.utils.JPAUtils;
import entities.curriculum.Curriculum;
import utils.SearchAllCriteriaFilter;
import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import java.util.List;
import java.util.logging.Logger;
@ApplicationScoped
public class CurriculumBean {
private final Logger log = Logger.getLogger(this.getClass().getName());
@PersistenceContext(unitName = "sis-jpa")
private EntityManager em;
@Transactional
public List<Curriculum> getEntireCurriculum(QueryParameters query) {
return JPAUtils.queryEntities(em, Curriculum.class, query);
}
@Transactional
public List<Curriculum> getEntireCurriculum(QueryParameters query, String searchQuery) {
if(searchQuery == null) return getEntireCurriculum(query);
return JPAUtils.queryEntities(em, Curriculum.class, query, new SearchAllCriteriaFilter<>(searchQuery));
}
@Transactional
public Curriculum getCurriculumByIdCurriculum(int idCurriculum) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getByIdCurriculum", Curriculum.class);
q.setParameter("id_curriculum", idCurriculum);
// using getResultList instead of getSingleResult because the latter requires exception catching...
List<Curriculum> c = q.getResultList();
// id is unique -> max 1 result
return c.size() > 0 ? c.get(0): null;
}
@Transactional
public List<Curriculum> getCurriculumByStudyProgramId(String studyProgramId) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getByStudyProgramId", Curriculum.class);
q.setParameter("id", studyProgramId);
return q.getResultList();
}
@Transactional
public Curriculum getCourseMetadata(int idCourse, int yearOfProgram, String idStudyProgram, int idStudyYear) {
TypedQuery<Curriculum> q = em.createQuery("SELECT cur FROM curriculum cur WHERE " +
"cur.idCourse.id = :id_course AND cur.yearOfProgram = :year_of_program AND " +
"cur.idStudyProgram.id = :id_study_program AND cur.studyYear.id = :id_study_year", Curriculum.class);
q.setParameter("id_course", idCourse);
q.setParameter("year_of_program", yearOfProgram);
q.setParameter("id_study_program", idStudyProgram);
q.setParameter("id_study_year", idStudyYear);
List<Curriculum> results = q.getResultList();
if(results != null && !results.isEmpty())
return results.get(0);
return null;
}
@Transactional
public List<Curriculum> getCurriculumByStudyProgramName(String studyProgramName) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getByStudyProgramName", Curriculum.class);
q.setParameter("name", studyProgramName);
return q.getResultList();
}
@Transactional
public List<Curriculum> getCurriculumByStudyProgramDegreeName(String studyProgramDegreeName) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getByStudyProgramDegreeName", Curriculum.class);
q.setParameter("name", studyProgramDegreeName);
return q.getResultList();
}
@Transactional
public List<Curriculum> getFirstYearCourses(String studyYear, String idStudyProgram) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getFirstYear", Curriculum.class);
q.setParameter("name_study_year", studyYear);
q.setParameter("id_study_program", idStudyProgram);
return q.getResultList();
}
@Transactional
public List<Curriculum> getByStudyProgramStudyYearYearOfProgram(int idStudyYear, String idStudyProgram, int yearOfProgram) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getByStudyProgramStudyYearYearOfProgram", Curriculum.class);
q.setParameter("id_study_year", idStudyYear);
q.setParameter("id_study_program", idStudyProgram);
q.setParameter("year_of_program", yearOfProgram);
return q.getResultList();
}
/*
NOTE: 4 almost same methods created for getting courses, could be merged into 1 method, but they're not because
encoding for type of course is determined ad-hoc and would probably need to be looked up everytime.
*/
@Transactional
public List<Curriculum> getModuleCourses(String studyYear, String idStudyProgram, int yearOfProgram) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getAllModuleCourses", Curriculum.class);
q.setParameter("name_study_year", studyYear);
q.setParameter("id_study_program", idStudyProgram);
q.setParameter("year_of_program", yearOfProgram);
return q.getResultList();
}
@Transactional
public List<Curriculum> getCurriculumByPOC(int idPOC, String studyYear, String studyProgram, int yearOfProgram) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getCurriculumByPOC", Curriculum.class);
q.setParameter("id_poc", idPOC);
q.setParameter("name_study_year", studyYear);
q.setParameter("id_study_program", studyProgram);
q.setParameter("year_of_program", yearOfProgram);
return q.getResultList();
}
@Transactional
public List<Curriculum> getMandatoryCourses(String studyYear, String idStudyProgram, int yearOfProgram) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getMandatoryCourses", Curriculum.class);
q.setParameter("name_study_year", studyYear);
q.setParameter("id_study_program", idStudyProgram);
q.setParameter("year_of_program", yearOfProgram);
return q.getResultList();
}
@Transactional
public List<Curriculum> getSpecialistElectiveCourses(String studyYear, String idStudyProgram, int yearOfProgram) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getSpecialistElectiveCourses", Curriculum.class);
q.setParameter("name_study_year", studyYear);
q.setParameter("id_study_program", idStudyProgram);
q.setParameter("year_of_program", yearOfProgram);
return q.getResultList();
}
@Transactional
public List<Curriculum> getGeneralElectiveCourses(String studyYear, String idStudyProgram, int yearOfProgram) {
TypedQuery<Curriculum> q = em.createNamedQuery("Curriculum.getGeneralElectiveCourses", Curriculum.class);
q.setParameter("name_study_year", studyYear);
q.setParameter("id_study_program", idStudyProgram);
q.setParameter("year_of_program", yearOfProgram);
return q.getResultList();
}
@Transactional
public boolean existsCurriculum(int id) {
return em.find(Curriculum.class, id) != null;
}
@Transactional
public Curriculum insertCurriculum(Curriculum c) {
em.persist(c);
em.flush();
return c;
}
@Transactional
public void deleteCurriculum(int id) {
Curriculum c = em.find(Curriculum.class, id);
if(c != null) {
c.setDeleted(!c.getDeleted());
em.merge(c);
} else {
throw new NoResultException("Course by ID doesn't exist");
}
}
@Transactional
public Curriculum updateCurriculum(Curriculum c) {
em.merge(c);
em.flush();
return c;
}
}
| 38.744898 | 128 | 0.710561 |
12dc4b6638256e64c3e118e8de68030293c005d8 | 501 | package com.petsvalley.service;
import com.petsvalley.entity.Macth;
import com.petsvalley.util.PageModel;
import java.util.Date;
public interface MatchService {
PageModel<Macth> getMatchByPage( PageModel<Macth> page, Integer userId );
Integer getCount( Integer userId );
Integer deleteById( Integer msgid );
Integer getCountByDate( Integer userId, Date to, Date from1 );
PageModel<Macth> getMatchByPageDate( PageModel<Macth> page, Integer userId, Date to, Date from1 );
}
| 23.857143 | 102 | 0.752495 |
7937464646044b381800944af0dae196b16a7fd7 | 6,774 | package tests.dataaccesslayer;
import junit.framework.TestCase;
import dataaccesslayer.Database;
import domainobjects.Expense;
import domainobjects.IDSet;
import domainobjects.Label;
import domainobjects.Money;
import domainobjects.PayTo;
import domainobjects.PaymentMethod;
import domainobjects.SimpleDate;
public class DatabaseTests extends TestCase
{
protected void setUp() throws Exception
{
database = new Database("Tests");
database.open("Tests");
}
protected void tearDown() throws Exception
{
database.close();
}
public void test_Add_and_get_an_empty_expense()
{
int[] setData = new int[0];
IDSet set = IDSet.createFromArray(setData);
Expense expectedExpense = new Expense(SimpleDate.Now(), new Money(), PaymentMethod.CASH, "", 0, set);
addAndGetExpense(expectedExpense);
}
public void test_Add_and_get_an_expense()
{
int[] setData = new int[]{1};
IDSet set = IDSet.createFromArray(setData);
Expense expectedExpense = new Expense(SimpleDate.Now(), new Money(10, 0), PaymentMethod.CASH, "", 1, set);
addAndGetExpense(expectedExpense);
}
private void addAndGetExpense(Expense expectedExpense) {
int newId;
newId = database.getExpenseTable().add(expectedExpense);
Expense actualExpense = (Expense)database.getExpenseTable().getById(newId);
assertEquals(actualExpense.getDate().getDay(), expectedExpense.getDate().getDay());
assertEquals(actualExpense.getDate().getMonth(), expectedExpense.getDate().getMonth());
assertEquals(actualExpense.getDate().getYear(), expectedExpense.getDate().getYear());
assertEquals(actualExpense.getAmount().getTotalCents(), expectedExpense.getAmount().getTotalCents());
assertEquals(actualExpense.getPaymentMethod(), expectedExpense.getPaymentMethod());
assertEquals(actualExpense.getDescription(), expectedExpense.getDescription());
assertEquals(actualExpense.getPayTo(), expectedExpense.getPayTo());
assertEquals(actualExpense.getLabels().getSize(), expectedExpense.getLabels().getSize());
}
public void test_Update_expense()
{
int newId = 0;
boolean updated;
int[] setData = new int[]{2};
IDSet set = IDSet.createFromArray(setData);
Expense addedExpense = new Expense(SimpleDate.Now(), new Money(0, 50), PaymentMethod.DEBIT, "", 2, set);
newId = database.getExpenseTable().add(addedExpense);
//Update the expense by creating a new similar expense
Expense expectedExpense = new Expense(SimpleDate.Now(), new Money(0, 55), PaymentMethod.DEBIT, "", 2, set);
updated = database.getExpenseTable().update(newId, expectedExpense);
Expense actualExpense = (Expense)database.getExpenseTable().getById(newId);
assertTrue(updated);
assertEquals(actualExpense.getDate().getDay(), expectedExpense.getDate().getDay());
assertEquals(actualExpense.getDate().getMonth(), expectedExpense.getDate().getMonth());
assertEquals(actualExpense.getDate().getYear(), expectedExpense.getDate().getYear());
assertEquals(actualExpense.getAmount().getTotalCents(), expectedExpense.getAmount().getTotalCents());
assertEquals(actualExpense.getPaymentMethod(), expectedExpense.getPaymentMethod());
assertEquals(actualExpense.getDescription(), expectedExpense.getDescription());
assertEquals(actualExpense.getPayTo(), expectedExpense.getPayTo());
assertEquals(actualExpense.getLabels().getSize(), expectedExpense.getLabels().getSize());
}
public void test_Getting_all_expense_Ids_should_return_the_previously_added_id()
{
int expectedId = 0;
int[] setData = new int[]{1};
IDSet expenseIds;
IDSet set = IDSet.createFromArray(setData);
Expense expense = new Expense(SimpleDate.Now(), new Money(5, 0), PaymentMethod.DEBIT, "", 1, set);
expectedId = database.getExpenseTable().add(expense);
expenseIds = IDSet.createFromArray(database.getExpenseTable().getAllIds());
assertTrue(expenseIds.contains(expectedId));
}
public void test_Add_and_delete_an_expense_successfully()
{
int newId = 0;
boolean deleted;
int[] setData = new int[]{1};
IDSet expenseIds;
IDSet set = IDSet.createFromArray(setData);
Expense addedExpense = new Expense(SimpleDate.Now(), new Money(1, 0), PaymentMethod.DEBIT, "", 2, set);
newId = database.getExpenseTable().add(addedExpense);
deleted = database.getExpenseTable().delete(newId);
expenseIds = IDSet.createFromArray(database.getExpenseTable().getAllIds());
assertTrue(deleted);
assertFalse(expenseIds.contains(newId));
}
public void test_Add_and_get_a_label()
{
int newId = 0;
Label expectedLabel = new Label("Craziness");
newId = database.getLabelTable().add(expectedLabel);
Label actualLabel = (Label)database.getLabelTable().getById(newId);
assertEquals(actualLabel.getName(), expectedLabel.getName());
}
public void test_Update_label()
{
int newId = 0;
boolean updated;
Label addedLabel = new Label("House");
newId = database.getLabelTable().add(addedLabel);
//Update the label by creating a new similar label
Label expectedLabel = new Label("Kyles House");
updated = database.getLabelTable().update(newId, expectedLabel);
Label actualLabel = (Label)database.getLabelTable().getById(newId);
assertTrue(updated);
assertEquals(actualLabel.getName(), expectedLabel.getName());
}
public void test_Getting_all_label_Ids_should_return_the_previously_added_id()
{
int expectedId = 0;
IDSet labelIds;
Label label = new Label("Sports");
expectedId = database.getLabelTable().add(label);
labelIds = IDSet.createFromArray(database.getLabelTable().getAllIds());
assertTrue(labelIds.contains(expectedId));
}
public void test_Add_and_get_a_payTo()
{
PayTo expectedPayTo = new PayTo("U of M");
int newId = database.getPayToTable().add(expectedPayTo);
PayTo actualPayTo = (PayTo)database.getPayToTable().getById(newId);
assertEquals(actualPayTo.getName(), expectedPayTo.getName());
}
public void test_Update_payTo()
{
int newId = 0;
boolean updated;
PayTo addedPayTo = new PayTo("McDonalds");
newId = database.getPayToTable().add(addedPayTo);
//Update the payTo by creating a new similar payTo
PayTo expectedPayTo = new PayTo("McDonalds");
updated = database.getPayToTable().update(newId, expectedPayTo);
PayTo actualPayTo = (PayTo)database.getPayToTable().getById(newId);
assertTrue(updated);
assertEquals(actualPayTo.getName(), expectedPayTo.getName());
}
public void test_Getting_all_payTo_Ids_should_return_the_previously_added_id()
{
int expectedId = 0;
IDSet payToIds;
PayTo payTo = new PayTo("Tim Hortons");
expectedId = database.getPayToTable().add(payTo);
payToIds = IDSet.createFromArray(database.getPayToTable().getAllIds());
assertTrue(payToIds.contains(expectedId));
}
private Database database;
} | 34.561224 | 109 | 0.749926 |
70b5f196816d76c179e9b3b668c0260157532f53 | 1,170 | import java.util.Locale;
import java.util.Scanner;
public class Solution {
static boolean isAnagram(String a, String b) {
// Complete the function
a = a.toUpperCase();
b = b.toUpperCase();
boolean anagram = false;
StringBuilder b1 = new StringBuilder(b);
if(a.length() == b.length()) {
for (int i = 0; i < a.length(); i++){
for (int j = 0; j < b1.length(); j++){
if(a.charAt(i) == b1.charAt(j)){
b1.deleteCharAt(j);
if (i==a.length()-1 && b1.length()==0){
anagram = true;
break;
}
break;
}
}
}
}
return anagram;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}
| 29.25 | 67 | 0.417094 |
ee6a5bbb39dac9ec27da010dcf72765b1befb4d7 | 2,111 | /**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.jceplugin.language.codeStyle;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CustomCodeStyleSettings;
import org.jetbrains.annotations.NotNull;
public class JceCodeStyleSettings extends CustomCodeStyleSettings {
public static final int DO_NOT_ALIGN = PropertyAlignment.DO_NOT_ALIGN.getId();
public static final int ALIGN = PropertyAlignment.ALIGN.getId();
protected JceCodeStyleSettings(CodeStyleSettings container) {
super("JceCodeStyleSettings", container);
}
/**
* Contains value of {@link PropertyAlignment#getId()}
*
* @see #DO_NOT_ALIGN
* @see #ALIGN
*/
public int FIELD_ALIGNMENT = PropertyAlignment.ALIGN.getId();
/**
* Contains value of {@link PropertyAlignment#getId()}
*
* @see #DO_NOT_ALIGN
* @see #ALIGN
*/
public int ENUM_ALIGNMENT = PropertyAlignment.ALIGN.getId();
public enum PropertyAlignment {
DO_NOT_ALIGN(0, "Do not align"),
ALIGN(1, "Align");
private final String myKey;
private final int myId;
PropertyAlignment(int id, @NotNull String key) {
myKey = key;
myId = id;
}
@NotNull
public String getDescription() {
return myKey;
}
public int getId() {
return myId;
}
}
}
| 31.044118 | 92 | 0.681194 |
ef9aaf3a0980b7747c7d270dda4384d739287ad7 | 1,858 | package choonster.testmod3.client.init;
import choonster.testmod3.TestMod3;
import choonster.testmod3.init.ModBlocks;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.world.level.block.Block;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
/**
* Sets the render layers for this mod's {@link Block}s.
*
* @author Choonster
*/
@Mod.EventBusSubscriber(modid = TestMod3.MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public class ModRenderLayerSetup {
@SubscribeEvent
public static void setRenderLayers(final FMLClientSetupEvent event) {
event.enqueueWork(() -> {
ItemBlockRenderTypes.setRenderLayer(ModBlocks.FLUID_TANK.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.FLUID_TANK_RESTRICTED.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.FLUID_PIPE.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.MIRROR_PLANE.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.OAK_SAPLING.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.SPRUCE_SAPLING.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.BIRCH_SAPLING.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.JUNGLE_SAPLING.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.ACACIA_SAPLING.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.DARK_OAK_SAPLING.get(), RenderType.cutout());
ItemBlockRenderTypes.setRenderLayer(ModBlocks.WATER_GRASS.get(), RenderType.cutout());
});
}
}
| 50.216216 | 106 | 0.808396 |
2c239ec2bb82cb63647cfcd1cd73274333cd0fd9 | 9,384 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.v2.hs.server;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.hadoop.HadoopIllegalArgumentException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.v2.hs.JobHistory;
import org.apache.hadoop.mapreduce.v2.hs.client.HSAdmin;
import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig;
import org.apache.hadoop.security.GroupMappingServiceProvider;
import org.apache.hadoop.security.Groups;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import org.apache.hadoop.security.authorize.AuthorizationException;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogDeletionService;
public class TestHSAdminServer {
private HSAdminServer hsAdminServer = null;
private HSAdmin hsAdminClient = null;
JobConf conf = null;
private static long groupRefreshTimeoutSec = 1;
JobHistory jobHistoryService = null;
AggregatedLogDeletionService alds = null;
public static class MockUnixGroupsMapping implements
GroupMappingServiceProvider {
private int i = 0;
@Override
public List<String> getGroups(String user) throws IOException {
System.out.println("Getting groups in MockUnixGroupsMapping");
String g1 = user + (10 * i + 1);
String g2 = user + (10 * i + 2);
List<String> l = new ArrayList<String>(2);
l.add(g1);
l.add(g2);
i++;
return l;
}
@Override
public void cacheGroupsRefresh() throws IOException {
System.out.println("Refreshing groups in MockUnixGroupsMapping");
}
@Override
public void cacheGroupsAdd(List<String> groups) throws IOException {
}
}
@Before
public void init() throws HadoopIllegalArgumentException, IOException {
conf = new JobConf();
conf.set(JHAdminConfig.JHS_ADMIN_ADDRESS, "0.0.0.0:0");
conf.setClass("hadoop.security.group.mapping", MockUnixGroupsMapping.class,
GroupMappingServiceProvider.class);
conf.setLong("hadoop.security.groups.cache.secs", groupRefreshTimeoutSec);
Groups.getUserToGroupsMappingService(conf);
jobHistoryService = mock(JobHistory.class);
alds = mock(AggregatedLogDeletionService.class);
hsAdminServer = new HSAdminServer(alds, jobHistoryService) {
@Override
protected Configuration createConf() {
return conf;
}
};
hsAdminServer.init(conf);
hsAdminServer.start();
conf.setSocketAddr(JHAdminConfig.JHS_ADMIN_ADDRESS,
hsAdminServer.clientRpcServer.getListenerAddress());
hsAdminClient = new HSAdmin(conf);
}
@Test
public void testGetGroups() throws Exception {
// Get the current user
String user = UserGroupInformation.getCurrentUser().getUserName();
String[] args = new String[2];
args[0] = "-getGroups";
args[1] = user;
// Run the getGroups command
int exitCode = hsAdminClient.run(args);
assertEquals("Exit code should be 0 but was: " + exitCode, 0, exitCode);
}
@Test
public void testRefreshUserToGroupsMappings() throws Exception {
String[] args = new String[] { "-refreshUserToGroupsMappings" };
Groups groups = Groups.getUserToGroupsMappingService(conf);
String user = UserGroupInformation.getCurrentUser().getUserName();
System.out.println("first attempt:");
List<String> g1 = groups.getGroups(user);
String[] str_groups = new String[g1.size()];
g1.toArray(str_groups);
System.out.println(Arrays.toString(str_groups));
// Now groups of this user has changed but getGroups returns from the
// cache,so we would see same groups as before
System.out.println("second attempt, should be same:");
List<String> g2 = groups.getGroups(user);
g2.toArray(str_groups);
System.out.println(Arrays.toString(str_groups));
for (int i = 0; i < g2.size(); i++) {
assertEquals("Should be same group ", g1.get(i), g2.get(i));
}
// run the command,which clears the cache
hsAdminClient.run(args);
System.out
.println("third attempt(after refresh command), should be different:");
// Now get groups should return new groups
List<String> g3 = groups.getGroups(user);
g3.toArray(str_groups);
System.out.println(Arrays.toString(str_groups));
for (int i = 0; i < g3.size(); i++) {
assertFalse(
"Should be different group: " + g1.get(i) + " and " + g3.get(i), g1
.get(i).equals(g3.get(i)));
}
}
@Test
public void testRefreshSuperUserGroups() throws Exception {
UserGroupInformation ugi = mock(UserGroupInformation.class);
UserGroupInformation superUser = mock(UserGroupInformation.class);
when(ugi.getRealUser()).thenReturn(superUser);
when(superUser.getShortUserName()).thenReturn("superuser");
when(superUser.getUserName()).thenReturn("superuser");
when(ugi.getGroupNames()).thenReturn(new String[] { "group3" });
when(ugi.getUserName()).thenReturn("regularUser");
// Set super user groups not to include groups of regularUser
conf.set("hadoop.proxyuser.superuser.groups", "group1,group2");
conf.set("hadoop.proxyuser.superuser.hosts", "127.0.0.1");
String[] args = new String[1];
args[0] = "-refreshSuperUserGroupsConfiguration";
hsAdminClient.run(args);
Throwable th = null;
try {
ProxyUsers.authorize(ugi, "127.0.0.1");
} catch (Exception e) {
th = e;
}
// Exception should be thrown
assertTrue(th instanceof AuthorizationException);
// Now add regularUser group to superuser group but not execute
// refreshSuperUserGroupMapping
conf.set("hadoop.proxyuser.superuser.groups", "group1,group2,group3");
// Again,lets run ProxyUsers.authorize and see if regularUser can be
// impersonated
// resetting th
th = null;
try {
ProxyUsers.authorize(ugi, "127.0.0.1");
} catch (Exception e) {
th = e;
}
// Exception should be thrown again since we didn't refresh the configs
assertTrue(th instanceof AuthorizationException);
// Lets refresh the config by running refreshSuperUserGroupsConfiguration
hsAdminClient.run(args);
th = null;
try {
ProxyUsers.authorize(ugi, "127.0.0.1");
} catch (Exception e) {
th = e;
}
// No exception thrown since regularUser can be impersonated.
assertNull("Unexpected exception thrown: " + th, th);
}
@Test
public void testRefreshAdminAcls() throws Exception {
// Setting current user to admin acl
conf.set(JHAdminConfig.JHS_ADMIN_ACL, UserGroupInformation.getCurrentUser()
.getUserName());
String[] args = new String[1];
args[0] = "-refreshAdminAcls";
hsAdminClient.run(args);
// Now I should be able to run any hsadmin command without any exception
// being thrown
args[0] = "-refreshSuperUserGroupsConfiguration";
hsAdminClient.run(args);
// Lets remove current user from admin acl
conf.set(JHAdminConfig.JHS_ADMIN_ACL, "notCurrentUser");
args[0] = "-refreshAdminAcls";
hsAdminClient.run(args);
// Now I should get an exception if i run any hsadmin command
Throwable th = null;
args[0] = "-refreshSuperUserGroupsConfiguration";
try {
hsAdminClient.run(args);
} catch (Exception e) {
th = e;
}
assertTrue(th instanceof RemoteException);
}
@Test
public void testRefreshLoadedJobCache() throws Exception {
String[] args = new String[1];
args[0] = "-refreshLoadedJobCache";
hsAdminClient.run(args);
verify(jobHistoryService).refreshLoadedJobCache();
}
@Test
public void testRefreshLogRetentionSettings() throws Exception {
String[] args = new String[1];
args[0] = "-refreshLogRetentionSettings";
hsAdminClient.run(args);
verify(alds).refreshLogRetentionSettings();
}
@Test
public void testRefreshJobRetentionSettings() throws Exception {
String[] args = new String[1];
args[0] = "-refreshJobRetentionSettings";
hsAdminClient.run(args);
verify(jobHistoryService).refreshJobRetentionSettings();
}
@After
public void cleanUp() {
if (hsAdminServer != null)
hsAdminServer.stop();
}
}
| 34 | 79 | 0.706628 |
866aa9391864196ccd604687c67f8831f30d6196 | 1,064 | public class Bus extends Transport
{
private double time;
private final double maxTime;
private int count; // Count of how many differents Passengers has travelled inside the bus during a certain period
public Bus(int maxSeating, int maxStanding, int maxTime)
{
super(maxSeating, maxStanding);
if(maxTime < 0)
maxTime = 0;
this.maxTime = maxTime;
}
private void handle_count()
{
if(time > maxTime)
{
time -= (maxTime*((int)time/(int)maxTime));
count = nbSeating + nbStanding;
}
else
++count;
}
// Buses can accept overcrowded standing places but you can't exceed the number of seated places
public boolean pickPassenger(Passenger passenger, Position position)
{
if(position == Position.SEATING && !remainSeatingPlaces())
return false;
if(position == Position.SEATING)
++nbSeating;
if(position == Position.STANDING)
++nbStanding;
handle_count(); // We can only check the time when we pick up a new passenger
passengers.add(passenger);
return true;
}
}
| 28 | 119 | 0.679511 |
4f0e4c828598b094ccc86bce0bdd39b611fe0b77 | 7,461 | import java.awt.*;
import java.util.ArrayList;
/**
* this class is for the controlling of the informations of the Army and the Reinforcements
*/
public class Gamer {
public Color color;
public ArrayList<Territory> myTerritory = new ArrayList<Territory>();
public int reinforcements = 0;
public int reinforcementsPlacedThisTurn = 0; //// FIXME: 31/12/15
String playerName;
private boolean isHuman = false;
/**
* base information for a non player charakter
* if the player is human so it will be set in the constructor to true and blue;
*/
public Gamer(Color color, boolean isHuman, String playerName) {
this.isHuman = isHuman;
this.color = color;
this.playerName = playerName;
}
//getOwner returns which gamer controls a given territory. Iterative check.
public static Gamer getOwner(Territory currentlySelected, Gamer computerPlayer1, Gamer humanPlayer1) {
for (Territory t : computerPlayer1.myTerritory) {
if (t.equals(currentlySelected)) {
return computerPlayer1;
}
}
for (Territory t : humanPlayer1.myTerritory) {
if (t.equals(currentlySelected)) {
return humanPlayer1;
}
}
return new Gamer(Color.BLACK, false, "dummy");
}
/* public void captureForComputerPlayerAfterStartTerritoryIsSet() {
if (this.myTerritory.size() > 0) {
while (true) {
int randTerritory = 0 + (int) (Math.random() * this.myTerritory.size());
int randNeighbours = 0 + (int) (Math.random() * this.myTerritory.get(randTerritory).getNeighbours().size());
if (!this.myTerritory.contains(this.myTerritory.get(randTerritory).getNeighbours().get(randNeighbours)) &&
this.myTerritory.get(randTerritory).getNeighbours().get(randNeighbours).getArmyCount() == 0) {
this.createNewArmy(this.myTerritory.get(randTerritory).getNeighbours().get(randNeighbours));
return;
}
}
}
}*/
public void captureTerritory(Territory toCapture) {
myTerritory.add(toCapture);
toCapture.addArmy(1);
System.out.println("succesfully captured: " + toCapture.getName());
}
public void captureTerritory(Territory toCapture, boolean isATakeOver) {
if (isATakeOver) {
myTerritory.add(toCapture);
toCapture.army = 0;
System.out.println("succesfully captured: " + toCapture.getName());
} else {
captureTerritory(toCapture);
}
}
public boolean init(Territory area) {
if (this.myTerritory.size() == 0) {
this.createNewArmy(area);
return true;
} else // check if the selected area is a neightbour of the baseTerretory
{
if (!this.myTerritory.contains(area)) // the selected is not allowed to be in the Territory list
{
for (int i = 0; i < this.myTerritory.size(); i++) {
if (this.myTerritory.get(i).checkNeighbour(area)) {
this.createNewArmy(area);
return true;
}
}
}
}
return false;
}
/**
* by a fight there a three states with the randoms if army 1 == army 2 there happens nothing
* army 1 > army 2 there army 1 won the game
* army 1 < army 2 there army 2 won the game
* the looser by not equal will lose one army
*
* @param otherArmy the random number of the attacker
* @return 0 if its equal
* 1 if the otherArmy got a better value
* 2 if this army got a better value
*/
private int fight(int otherArmy) {
int thisArmy = 1 + (int) (Math.random() * 6);
if (thisArmy > otherArmy)
return 2;
else if (thisArmy == otherArmy)
return 0;
else
return 1;
}
public void removeTerritory(Territory t) {
this.myTerritory.remove(t);
}
public void createNewArmy(Territory t) {
if (this.myTerritory.contains(t)) {
t.addArmy(1);
}
}
public void calculateReinforcements() {
if (this.playerName == "Human Player 1") {
this.reinforcements = 11;
}
if (this.playerName == "CPU Player 1") {
this.reinforcements = 2000;
}
}
public void captureTerritory(Territory toCapture, boolean isATakeOver, int numberOfTransfer) {
if (isATakeOver) {
myTerritory.add(toCapture);
toCapture.army = numberOfTransfer;
System.out.println("succesfully captured: " + toCapture.getName());
} else {
captureTerritory(toCapture);
}
}
/* public void createNewReinforcements() {
this.reinforcements++;
}
public void moveArmy(Territory from, Territory to, ArrayList<Gamer> otherPlayer) {
int army = from.getArmyCount();
army--; // because one army must be at the Territory
if (army > 3) // max 3 armys can move per move
army = 3;
if (this.myTerritory.contains(to)) // move on the own ground -- no fight
{
from.removeArmy(army);
to.addArmy(army);
} else // this is an enemy ground -- fight
{
for (int i = 0; i < otherPlayer.size(); i++) {
if (!otherPlayer.get(i).equals(this)) {
if (otherPlayer.get(i).myTerritory.contains(from)) {
int erg = -1;
for (int j = 0; j < army; j++) {
erg = otherPlayer.get(i).fight((1 + (int) (Math.random() * 6)));
if (erg == 0) // no one wone
{
army--;
j--;
} else if (erg == 1) // this player won
{
to.removeArmy(1);
if (to.getArmyCount() == 0) // no enemy Armys left on the Territory - capture
{
otherPlayer.get(i).removeTerritory(to); // remove Territory from the otherPlayer
this.myTerritory.add(to); // add Territory to this Player
from.removeArmy(army);
to.addArmy(army); // set Correct count of Army
return;
}
} else if (erg == 2) // otherPlayer won
{
army--;
j--;
}
}
return;
}
}
}
}
}
public boolean setReinforcementToArmy(Territory t) {
if (this.reinforcements > 0) {
this.reinforcements--;
createNewArmy(t);
return true;
}
return false;
}
public int getAnzPossibleReinforcementsAvialable() {
return this.reinforcements;
}*/
}
| 33.16 | 124 | 0.514006 |
2ce6dd4983d836535ba230f296e755875921714a | 1,015 | package com.pigeoff.rss.cardstackview;
import android.view.View;
import com.pigeoff.rss.cardstackview.Direction;
public interface CardStackListener {
void onCardDragging(com.pigeoff.rss.cardstackview.Direction direction, float ratio);
void onCardSwiped(com.pigeoff.rss.cardstackview.Direction direction);
void onCardRewound();
void onCardCanceled();
void onCardAppeared(View view, int position);
void onCardDisappeared(View view, int position);
CardStackListener DEFAULT = new CardStackListener() {
@Override
public void onCardDragging(com.pigeoff.rss.cardstackview.Direction direction, float ratio) {}
@Override
public void onCardSwiped(Direction direction) {}
@Override
public void onCardRewound() {}
@Override
public void onCardCanceled() {}
@Override
public void onCardAppeared(View view, int position) {}
@Override
public void onCardDisappeared(View view, int position) {}
};
}
| 33.833333 | 101 | 0.706404 |
493a7b7889347c862a83fe9a1eb262c8696647a5 | 300 | package Controller;
public class Tabela {
String [] colunas = {"NOME", "EST/PROF", "CURSO", "TURNO"};
public String[] getColunas() {
return colunas;
}
public void setColunas(String[] colunas) {
this.colunas = colunas;
}
public Tabela() {
}
}
| 15.789474 | 63 | 0.553333 |
1b3dd45d3c06489e125b6ec4509ff10f12fb0406 | 588 | import java.io.*;
class bracket
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,j;String s1="";
char ch,ch2;
System.out.print("enter string");
String s=br.readLine();
for(i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch=='(')
{
for(j=s.length()-1;j>i;j--)
{
ch2=s.charAt(j);
if(ch2!=')')
{
s1=s1+ch2;
}
else break;
}
System.out.println(s1);
s1="";
}
}
}
} | 19.6 | 76 | 0.494898 |
17a7fdc48d35d86ae8ffa031d37142cfc876ea17 | 2,800 | package com.salesmanager.core.business.generic.service;
import java.io.Serializable;
import java.util.List;
import javax.persistence.metamodel.SingularAttribute;
import com.salesmanager.core.business.generic.dao.SalesManagerEntityDao;
import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.generic.model.SalesManagerEntity;
import com.salesmanager.core.business.generic.util.GenericEntityUtils;
/**
* @param <T> entity type
*/
public abstract class SalesManagerEntityServiceImpl<K extends Serializable & Comparable<K>, E extends SalesManagerEntity<K, ?>>
implements SalesManagerEntityService<K, E> {
/**
* Classe de l'entité, déterminé à partir des paramètres generics.
*/
private Class<E> objectClass;
private SalesManagerEntityDao<K, E> genericDao;
@SuppressWarnings("unchecked")
public SalesManagerEntityServiceImpl(SalesManagerEntityDao<K, E> genericDao) {
this.genericDao = genericDao;
this.objectClass = (Class<E>) GenericEntityUtils.getGenericEntityClassFromComponentDefinition(getClass());
}
protected final Class<E> getObjectClass() {
return objectClass;
}
public E getEntity(Class<? extends E> clazz, K id) {
return genericDao.getEntity(clazz, id);
}
public E getById(K id) {
return genericDao.getById(id);
}
/**
* @param fieldName condition field
* @param fieldValue field value
* @return entity
*/
protected <V> E getByField(SingularAttribute<? super E, V> fieldName, V fieldValue) {
return genericDao.getByField(fieldName, fieldValue);
}
public void save(E entity) throws ServiceException {
genericDao.save(entity);
}
public void create(E entity) throws ServiceException {
createEntity(entity);
}
protected void createEntity(E entity) throws ServiceException {
save(entity);
}
public final void update(E entity) throws ServiceException {
updateEntity(entity);
}
protected void updateEntity(E entity) throws ServiceException {
genericDao.update(entity);
}
public void delete(E entity) throws ServiceException {
genericDao.delete(entity);
}
public void flush() {
genericDao.flush();
}
public void clear() {
genericDao.clear();
}
public E refresh(E entity) {
return genericDao.refresh(entity);
}
public List<E> list() {
return genericDao.list();
}
/**
* Renvoie la liste des entités dont le champ donné en paramètre a la bonne valeur.
*
* @param fieldName le champ sur lequel appliquer la condition
* @param fieldValue valeur du champ
* @return liste d'entités
*/
protected <V> List<E> listByField(SingularAttribute<? super E, V> fieldName, V fieldValue) {
return genericDao.listByField(fieldName, fieldValue);
}
public Long count() {
return genericDao.count();
}
} | 23.140496 | 127 | 0.74 |
a98ef497677a05a8fba3f0c954e3bf3024d1d2cc | 1,545 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* Copyright (C) 2006-2010 Adele Team/LIG/Grenoble University, France
*/
package fr.imag.adele.cadse.core.ui;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import fr.imag.adele.cadse.core.*;
import fr.imag.adele.cadse.core.attribute.IAttributeType;
import fr.imag.adele.cadse.core.ui.view.FilterContext;
import fr.imag.adele.cadse.objectadapter.ObjectAdapter;
public class PageParticipator extends ObjectAdapter<PageParticipator> {
@Override
public Class<PageParticipator> getClassAdapt() {
return PageParticipator.class;
}
public void filterPage(Item item, FilterContext context, List<IPage> list,
Set<IAttributeType<?>> ro,
HashSet<IAttributeType<?>> hiddenAttributeInComputedPages) {
}
}
| 33.586957 | 75 | 0.765696 |
281e23100f6720cc07073eb9875a2baba6572780 | 5,164 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.06.26 at 10:48:45 AM CEST
//
package org.openforis.collect.mondrian;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Defines a named set which can be used in queries in the same way as a set
* defined using a WITH SET clause. A named set can be defined against a particular cube,
* or can be global to a schema. If it is defined against a cube, it is only available to queries which use that cube.
* A named set defined against a cube is not inherited by a virtual cubes defined against that cube.
* (But you can define a named set against a virtual cube). A named set defined against a schema
* is available in all cubes and virtual cubes in that schema.
* However, it is only valid if the cube contains dimensions with the names required to make the formula valid.
*
*
* <p>Java class for NamedSet complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="NamedSet">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Annotations" type="{}Annotations" minOccurs="0"/>
* <element name="Formula" type="{http://www.w3.org/2001/XMLSchema}anyType" minOccurs="0"/>
* </sequence>
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="caption" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="description" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NamedSet", propOrder = {
"annotations",
"formula"
})
public class NamedSet {
@XmlElement(name = "Annotations")
protected Annotations annotations;
@XmlElement(name = "Formula")
protected Object formula;
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "caption")
protected String caption;
@XmlAttribute(name = "description")
protected String description;
/**
* Gets the value of the annotations property.
*
* @return
* possible object is
* {@link Annotations }
*
*/
public Annotations getAnnotations() {
return annotations;
}
/**
* Sets the value of the annotations property.
*
* @param value
* allowed object is
* {@link Annotations }
*
*/
public void setAnnotations(Annotations value) {
this.annotations = value;
}
/**
* Gets the value of the formula property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getFormula() {
return formula;
}
/**
* Sets the value of the formula property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setFormula(Object value) {
this.formula = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the caption property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCaption() {
return caption;
}
/**
* Sets the value of the caption property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCaption(String value) {
this.caption = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
}
| 27.178947 | 134 | 0.583656 |
d6f7882dbdd132278da62b2a77a2355e3e0797b3 | 339 | package net.wolfesoftware.jax.ast;
public class BreakVoid extends BranchStatement
{
@Override
protected void decompile(String indentation, StringBuilder out)
{
out.append("break");
}
public static final int TYPE = 0x10e60378;
public int getElementType()
{
return TYPE;
}
}
| 19.941176 | 68 | 0.634218 |
456c3ddf40c69a3356b2aca33de8ec754500e61f | 521 | package Singleton;
/**
* 饿汉式. 这种方法非常简单,因为单例的实例被声明成 static 和 final
* 变量了,在第一次加载类到内存中时就会初始化,所以创建实例本身是线程安全的。
* 缺点是它不是一种懒加载模式(lazy initialization),单例会在加载类后一开始就被初始化,即使客户端没有调用
* getInstance()方法。饿汉式的创建方式在一些场景中将无法使用:譬如 Singleton 实例的创建是依赖参数或者配置文件的,在
* getInstance() 之前必须调用某个方法设置参数给它,那样这种单例写法就无法使用了。
*
* @author 30868
*
*/
public class Singleton1 {
// 类加载时就初始化
private static final Singleton1 instance = new Singleton1();
private Singleton1() {
}
public static Singleton1 getInstance() {
return instance;
}
}
| 21.708333 | 71 | 0.758157 |
bd084744e9c13a1cbd0fdde0b58e6ef0b83ce3b3 | 1,834 | /*
* Copyright 2000-2015 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 org.jetbrains.idea.devkit.testAssistant;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.ui.FilePathSplittingPolicy;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.File;
import java.util.Collections;
class GotoTestDataAction extends AnAction implements Comparable {
private final String myFilePath;
private final Project myProject;
public GotoTestDataAction(String filePath, Project project, Icon icon) {
super("Go to " + FilePathSplittingPolicy.SPLIT_BY_SEPARATOR.getPresentableName(new File(filePath), 50), null, icon);
myFilePath = filePath;
myProject = project;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
RelativePoint point = JBPopupFactory.getInstance().guessBestPopupLocation(e.getDataContext());
TestDataNavigationHandler.navigate(point, Collections.singletonList(myFilePath), myProject);
}
@Override
public int compareTo(Object o) {
return o instanceof GotoTestDataAction ? 0 : 1;
}
}
| 35.960784 | 120 | 0.7759 |
cc384a81104b0e2d11600801bb3ab8167430e357 | 8,638 | package vista;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import java.awt.SystemColor;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.FlowLayout;
import java.awt.CardLayout;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Font;
public class Pago extends JFrame{
public static enum enumAcciones{
BtnPagar, BtnDevolver, BtnSiguiente
}
private JTextField txtTotal;
private JTextField txtRestante;
private JTextField txtCantidadIngresada;
private JButton btnPagar;
private JTextArea txtPanelRestante;
private JButton btnDevolver;
private JButton btnPunto;
private JButton btnSiguiente;
public JButton getBtnSiguiente() {
return btnSiguiente;
}
public void setBtnSiguiente(JButton btnSiguiente) {
this.btnSiguiente = btnSiguiente;
}
public JButton getBtnDevolver() {
return btnDevolver;
}
public void setBtnDevolver(JButton btnDevolver) {
this.btnDevolver = btnDevolver;
}
public JTextArea getTxtPanelRestante() {
return txtPanelRestante;
}
public void setTxtPanelRestante(JTextArea txtPanelRestante) {
this.txtPanelRestante = txtPanelRestante;
}
public JTextField getTxtTotal() {
return txtTotal;
}
public void setTxtTotal(JTextField txtTotal) {
this.txtTotal = txtTotal;
}
public JTextField getTxtRestante() {
return txtRestante;
}
public void setTxtRestante(JTextField txtRestante) {
this.txtRestante = txtRestante;
}
public JTextField getTxtCantidadIngresada() {
return txtCantidadIngresada;
}
public void setTxtCantidadIngresada(JTextField txtCantidadIngresada) {
this.txtCantidadIngresada = txtCantidadIngresada;
}
public JButton getBtnPagar() {
return btnPagar;
}
public void setBtnPagar(JButton btnPagar) {
this.btnPagar = btnPagar;
}
/**
* Launch the application.
*/
/**
* Create the application.
*/
public Pago() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setBounds(100, 100, 450, 421);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(20, 115, 154, 146);
getContentPane().add(panel);
JButton btn3 = new JButton("3");
btn3.setBackground(Color.WHITE);
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "3") ;
}
});
JButton btn4 = new JButton("4");
btn4.setBackground(Color.WHITE);
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "4") ;
}
});
JButton btn9 = new JButton("9");
btn9.setBackground(Color.WHITE);
btn9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "9") ;
}
});
JButton btn5 = new JButton("5");
btn5.setBackground(Color.WHITE);
btn5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "5") ;
}
});
JButton btn8 = new JButton("8");
btn8.setBackground(Color.WHITE);
btn8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "8") ;
}
});
JButton btn7 = new JButton("7");
btn7.setBackground(Color.WHITE);
btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "7") ;
}
});
JButton btn6 = new JButton("6");
btn6.setBackground(Color.WHITE);
btn6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "6") ;
}
});
JButton btn1 = new JButton("1");
btn1.setBackground(Color.WHITE);
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "1") ;
}
});
JButton btn2 = new JButton("2");
btn2.setBackground(Color.WHITE);
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "2") ;
}
});
JButton btn0 = new JButton("0");
btn0.setBackground(Color.WHITE);
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + "0") ;
}
});
JButton btnBorrar = new JButton("...");
btnBorrar.setBackground(Color.WHITE);
btnBorrar.setLayout(new GridLayout(0,1,1,10));
btnBorrar.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String cadena = txtCantidadIngresada.getText();
txtCantidadIngresada.setText(cadena.substring(0,cadena.length()-1));
if((cadena.substring(cadena.length()-1)).equals(".")){
btnPunto.setEnabled(true);
}
if(txtCantidadIngresada.getText().equals("0")) {
txtCantidadIngresada.setText("");
}
if(txtCantidadIngresada.getText().contentEquals("")) {
btnBorrar.setEnabled(false);
}
}
});
btnPunto = new JButton(".");
btnPunto.setForeground(Color.BLACK);
btnPunto.setBackground(Color.WHITE);
btnPunto.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtCantidadIngresada.setText( txtCantidadIngresada.getText() + ".") ;
btnPunto.setEnabled(false);
}
});
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
panel.add(btn9);
panel.add(btn8);
panel.add(btn7);
panel.add(btn6);
panel.add(btn5);
panel.add(btn4);
panel.add(btn3);
panel.add(btn2);
panel.add(btn1);
panel.add(btnBorrar);
panel.add(btn0);
panel.add(btnPunto);
JLabel label = new JLabel("Pago:");
label.setBounds(20, 84, 79, 20);
getContentPane().add(label);
btnSiguiente = new JButton("Siguiente");
btnSiguiente.setBounds(307, 333, 104, 38);
getContentPane().add(btnSiguiente);
JButton btnCancelar = new JButton("Cancelar");
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnCancelar.setBounds(20, 333, 112, 38);
getContentPane().add(btnCancelar);
//este jtext contiene el precio a pagar
txtTotal = new JTextField();
txtTotal.setColumns(10);
txtTotal.setBounds(315, 23, 96, 20);
getContentPane().add(txtTotal);
JLabel label_1 = new JLabel("Total a Pagar:");
label_1.setBounds(315, 11, 96, 14);
getContentPane().add(label_1);
btnPagar = new JButton("Pagar");
btnPagar.setBounds(20, 275, 96, 38);
getContentPane().add(btnPagar);
txtRestante = new JTextField();
txtRestante.setColumns(10);
txtRestante.setBounds(196, 23, 96, 20);
getContentPane().add(txtRestante);
JLabel lblTotalAPagar = new JLabel("falta:");
lblTotalAPagar.setBounds(196, 11, 79, 14);
getContentPane().add(lblTotalAPagar);
txtCantidadIngresada = new JTextField();
txtCantidadIngresada.setBounds(50, 84, 96, 20);
getContentPane().add(txtCantidadIngresada);
txtCantidadIngresada.setColumns(10);
txtPanelRestante = new JTextArea();
txtPanelRestante.setBounds(210, 69, 183, 192);
getContentPane().add(txtPanelRestante);
btnDevolver = new JButton("Devolver");
btnDevolver.setBounds(126, 275, 97, 38);
getContentPane().add(btnDevolver);
JLabel label_2 = new JLabel("");
label_2.setBounds(50, 26, 48, 14);
getContentPane().add(label_2);
JLabel lblNewLabel = new JLabel("PAGO");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 25));
lblNewLabel.setBounds(20, 11, 126, 53);
getContentPane().add(lblNewLabel);
}
}
| 24.893372 | 73 | 0.707108 |
3d87bd632696f75acd93a375a1d036b8aa3cb992 | 3,072 | package com.dream.coolweather.util;
import android.content.Context;
import com.dream.coolweather.R;
import com.dream.coolweather.model.Area;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by SuSong on 2015/3/2 0002.
*/
public class AreaXmlParse {
public static List<Area> parseCityId(Context context) {
List<Area> areas = new ArrayList<Area>();
int depth = 0;
int depth0count = 0;
int depth1count = 0;
int depth2count = 0;
try {
XmlPullParser parser = context.getResources().getXml(R.xml.area);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if ("area".equals(nodeName)) {
String id = parser.getAttributeValue(0);
String name = parser.getAttributeValue(1);
String en = parser.getAttributeValue(2);
Area area = new Area(id, name, en);
if (depth == 0) {
areas.add(area);
} else if (depth == 1) {
areas.get(depth0count).getAreas().add(area);
} else if (depth == 2) {
areas.get(depth0count).getAreas().get(depth1count).getAreas().add(area);
}
depth++;
} else if ("city".equals(nodeName)) {
String id = parser.getAttributeValue(0);
String name = parser.getAttributeValue(1);
String en = parser.getAttributeValue(2);
Area area = new Area(id, name, en);
areas.get(depth0count).getAreas().get(depth1count).getAreas().get(depth2count).getAreas().add(area);
}
break;
case XmlPullParser.END_TAG:
if ("area".equals(nodeName)) {
if (depth == 3) {
depth2count++;
} else if (depth == 2) {
depth1count++;
depth2count = 0;
} else if (depth == 1) {
depth0count++;
depth1count = 0;
}
depth--;
}
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
return areas;
}
}
| 39.896104 | 128 | 0.442057 |
fd5c909d4b9eea8b53f4bfb7c0b45ed82b5aa0a2 | 1,942 | /*
Copyright (c) 2010-2011 Per Gantelius
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
package kowalski.editor.actions;
import kowalski.tools.data.ProjectDataException;
import kowalski.tools.data.ProjectDataUtils;
import kowalski.tools.data.xml.KowalskiProject;
import kowalski.tools.data.xml.Sound;
import kowalski.tools.data.xml.SoundGroup;
/**
*
*/
public class RemoveSoundAction extends AbstractProjectDataAction
{
private Sound soundToRemove;
private SoundGroup parentGroup;
private int oldIndex;
public RemoveSoundAction(KowalskiProject p, Sound sound)
{
super(p, "Remove Sound");
soundToRemove = sound;
parentGroup = (SoundGroup)ProjectDataUtils.getParentGroup(p, sound);
oldIndex = parentGroup.getSounds().indexOf(soundToRemove);
}
@Override
public void perform(KowalskiProject project) throws ProjectDataException
{
ProjectDataUtils.removeSound(project, parentGroup, soundToRemove);
}
@Override
public void undo(KowalskiProject project) throws ProjectDataException
{
parentGroup.getSounds().add(oldIndex, soundToRemove);
}
}
| 30.825397 | 77 | 0.754377 |
1ae2651ab9e78f2615f26353d5bd96582b8a859a | 3,501 | package com.buuz135.industrial.utils.explosion;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.Vector3f;
/**
* Class copied and adapted from Draconic Evolution https://github.com/brandon3055/BrandonsCore/blob/master/src/main/java/com/brandon3055/brandonscore/lib/ShortPos.java
*/
public class ShortPos {
private BlockPos relativeTo;
public ShortPos(BlockPos relativeTo) {
this.relativeTo = relativeTo;
}
/**
* This is the main method for converting a relative position to an integer.<br>
* Max allowed x/z difference between the two positions is 2048. Anything greater than this will result in a broken output but will not throw an error.<br><br>
*
* <pre>
* Byte Format:
* Y 8 bits X 12 bits Z 12 bits
* [11111111] [11111111 1111] [1111 11111111]
* </pre>
*
* @param position The position.
* @param relativeTo The the position to calculate the relative pos from. You will need this pos to convert the output from this method back to an actual block pos.
* @return the relative deference between the inputs as an integer.
*/
public static int getIntPos(BlockPos position, BlockPos relativeTo) {
if (position.getY() > 255) {
position = new BlockPos(position.getX(), 255, position.getY());
} else if (position.getY() < 0) {
position = new BlockPos(position.getX(), 0, position.getY());
}
int xp = (position.getX() - relativeTo.getX()) + 2048;
int yp = position.getY();
int zp = (position.getZ() - relativeTo.getZ()) + 2048;
return (yp << 24) | (xp << 12) | zp;
}
public static int getIntPos(Vector3f position, BlockPos relativeTo) {
if (position.getY() > 255) {
position.setY(255);
} else if (position.getY() < 0) {
position.setY(0);
}
int xp = ((int) position.getX() - relativeTo.getX()) + 2048;
int yp = (int) position.getY();
int zp = ((int) position.getZ() - relativeTo.getZ()) + 2048;
return (yp << 24) | (xp << 12) | zp;
}
/**
* This is the main method for converting from a relative integer position back to an actual block position.
*
* @param intPos The integer position calculated by getIntPos
* @param relativeTo the position to calculate the output pos relative to. This should be the same pos that was used when calculating the intPos to get back the original absolute pos.
* @return The absolute block position.
*/
public static BlockPos getBlockPos(int intPos, BlockPos relativeTo) {
int yp = (intPos >> 24 & 0xFF);
int xp = (intPos >> 12 & 0xFFF) - 2048;
int zp = (intPos & 0xFFF) - 2048;
int finalX = relativeTo.getX() + xp;
if (finalX < 0) finalX -= 1;
int finalZ = relativeTo.getZ() + zp;
if (finalZ < 0) finalZ -= 1;
return new BlockPos(finalX, yp, finalZ); //-1 so it gives a proper position
}
public BlockPos getRelativeTo() {
return relativeTo;
}
public void setRelativeTo(BlockPos relativeTo) {
this.relativeTo = relativeTo;
}
public int getIntPos(BlockPos pos) {
return getIntPos(pos, relativeTo);
}
public int getIntPos(Vector3f pos) {
return getIntPos(pos, relativeTo);
}
public BlockPos getActualPos(int intPos) {
return getBlockPos(intPos, relativeTo);
}
} | 36.46875 | 187 | 0.627535 |
9cb3d55b5ba6e7a9039ca544ee2015b1d3a87131 | 19,823 | /*
* Copyright 2010-2021 Australian Signals Directorate
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package au.gov.asd.tac.constellation.views.tableview.factory;
import au.gov.asd.tac.constellation.graph.Graph;
import au.gov.asd.tac.constellation.graph.GraphElementType;
import au.gov.asd.tac.constellation.views.tableview.TableViewTopComponent;
import au.gov.asd.tac.constellation.views.tableview.api.ActiveTableReference;
import au.gov.asd.tac.constellation.views.tableview.components.Table;
import au.gov.asd.tac.constellation.views.tableview.panes.TablePane;
import au.gov.asd.tac.constellation.views.tableview.state.TableViewState;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.SortType;
import javafx.scene.control.TableView;
import javafx.scene.control.TableView.TableViewSelectionModel;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import static org.mockito.ArgumentMatchers.any;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import org.testfx.api.FxToolkit;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
*
* @author formalhaunt
*/
public class TableViewPageFactoryNGTest {
private static final Logger LOGGER = Logger.getLogger(TableViewPageFactoryNGTest.class.getName());
private TableViewTopComponent tableViewTopComponent;
private TableView<ObservableList<String>> tableView;
private Table table;
private TablePane tablePane;
private ActiveTableReference activeTableReference;
private TableViewSelectionModel selectionModel;
private ObservableList<String> selectedItems;
private ReadOnlyObjectProperty<ObservableList<String>> selectedProperty;
private Graph graph;
private ChangeListener<ObservableList<String>> tableSelectionListener;
private ListChangeListener selectedOnlySelectionListener;
private ChangeListener<? super Comparator<? super ObservableList<String>>> tableComparatorListener;
private ChangeListener<? super TableColumn.SortType> tableSortTypeListener;
private SortedList<ObservableList<String>> sortedRowList;
private Set<ObservableList<String>> selectedOnlySelectedRows;
private ObjectProperty<Comparator<? super ObservableList<String>>> sortedRowListComparator;
private ObjectProperty<Comparator<ObservableList<String>>> tableViewComparator;
private TableViewPageFactory tableViewPageFactory;
@BeforeClass
public static void setUpClass() throws Exception {
if (!FxToolkit.isFXApplicationThreadRunning()) {
FxToolkit.registerPrimaryStage();
}
}
@AfterClass
public static void tearDownClass() throws Exception {
try {
FxToolkit.cleanupStages();
} catch (TimeoutException ex) {
LOGGER.log(Level.WARNING, "FxToolkit timed out trying to cleanup stages", ex);
}
}
@BeforeMethod
public void setUpMethod() throws Exception {
tableViewTopComponent = mock(TableViewTopComponent.class);
tableView = mock(TableView.class);
table = mock(Table.class);
tablePane = mock(TablePane.class);
activeTableReference = mock(ActiveTableReference.class);
selectionModel = mock(TableViewSelectionModel.class);
selectedItems = mock(ObservableList.class);
selectedProperty = mock(ReadOnlyObjectProperty.class);
graph = mock(Graph.class);
tableSelectionListener = mock(ChangeListener.class);
selectedOnlySelectionListener = mock(ListChangeListener.class);
tableComparatorListener = mock(ChangeListener.class);
tableSortTypeListener = mock(ChangeListener.class);
sortedRowListComparator = mock(ObjectProperty.class);
tableViewComparator = mock(ObjectProperty.class);
sortedRowList = spy(new SortedList<>(FXCollections.observableArrayList()));
selectedOnlySelectedRows = new HashSet<>();
tableViewPageFactory = spy(new TableViewPageFactory(tablePane));
doReturn(tableComparatorListener).when(tableViewPageFactory).getTableComparatorListener();
doReturn(tableSortTypeListener).when(tableViewPageFactory).getTableSortTypeListener();
when(tablePane.getTable()).thenReturn(table);
when(tablePane.getParentComponent()).thenReturn(tableViewTopComponent);
when(tablePane.getActiveTableReference()).thenReturn(activeTableReference);
when(activeTableReference.getSelectedOnlySelectedRows()).thenReturn(selectedOnlySelectedRows);
when(activeTableReference.getSortedRowList()).thenReturn(sortedRowList);
when(sortedRowList.comparatorProperty()).thenReturn(sortedRowListComparator);
when(table.getTableView()).thenReturn(tableView);
when(table.getSelectedProperty()).thenReturn(selectedProperty);
when(table.getTableSelectionListener()).thenReturn(tableSelectionListener);
when(table.getSelectedOnlySelectionListener()).thenReturn(selectedOnlySelectionListener);
when(selectionModel.getSelectedItems()).thenReturn(selectedItems);
when(tableView.comparatorProperty()).thenReturn(tableViewComparator);
when(tableView.getSelectionModel()).thenReturn(selectionModel);
when(tableViewTopComponent.getCurrentGraph()).thenReturn(graph);
when(tableViewTopComponent.getExecutorService()).thenReturn(Executors.newSingleThreadExecutor());
}
@AfterMethod
public void tearDownMethod() throws Exception {
}
@Test
public void init() {
assertNotNull(tableViewPageFactory.getTableComparatorListener());
assertNotNull(tableViewPageFactory.getTableSortTypeListener());
}
@Test
public void getCurrentSort() {
final ObservableList<TableColumn<ObservableList<String>, String>> sortOrder = mock(ObservableList.class);
final TableColumn<ObservableList<String>, String> sortCol = mock(TableColumn.class);
final ObjectProperty<SortType> sortTypeProperty = mock(ObjectProperty.class);
doReturn(sortOrder).when(tableView).getSortOrder();
when(sortOrder.isEmpty()).thenReturn(false);
when(sortOrder.get(0)).thenReturn(sortCol);
when(sortCol.getSortType()).thenReturn(TableColumn.SortType.DESCENDING);
when(sortCol.sortTypeProperty()).thenReturn(sortTypeProperty);
final Pair<TableColumn<ObservableList<String>, ?>, TableColumn.SortType> expectedSort
= ImmutablePair.of(sortCol, TableColumn.SortType.DESCENDING);
assertEquals(expectedSort, tableViewPageFactory.getCurrentSort());
verify(sortTypeProperty).removeListener(tableSortTypeListener);
}
@Test
public void getCurrentSortNoSort() {
doReturn(FXCollections.observableArrayList()).when(tableView).getSortOrder();
final Pair<TableColumn<ObservableList<String>, ?>, TableColumn.SortType> expectedSort
= ImmutablePair.of(null, null);
assertEquals(expectedSort, tableViewPageFactory.getCurrentSort());
}
@Test
public void restoreSort() {
final ObservableList<TableColumn<ObservableList<String>, String>> sortOrder = mock(ObservableList.class);
final TableColumn<ObservableList<String>, String> sortCol = mock(TableColumn.class);
final ObjectProperty<SortType> sortTypeProperty = mock(ObjectProperty.class);
doReturn(sortOrder).when(tableView).getSortOrder();
when(sortCol.getSortType()).thenReturn(TableColumn.SortType.DESCENDING);
when(sortCol.sortTypeProperty()).thenReturn(sortTypeProperty);
final Pair<TableColumn<ObservableList<String>, ?>, TableColumn.SortType> currentSort
= ImmutablePair.of(sortCol, TableColumn.SortType.DESCENDING);
tableViewPageFactory.restoreSort(currentSort);
verify(sortOrder).add(sortCol);
verify(sortCol).setSortType(SortType.DESCENDING);
verify(sortTypeProperty).addListener(tableSortTypeListener);
}
@Test
public void restoreSortCurrentSortNull() {
final ObservableList<TableColumn<ObservableList<String>, String>> sortOrder = mock(ObservableList.class);
doReturn(sortOrder).when(tableView).getSortOrder();
tableViewPageFactory.restoreSort(ImmutablePair.of(null, TableColumn.SortType.DESCENDING));
verifyNoInteractions(sortOrder);
}
@Test
public void restoreListeners() {
tableViewPageFactory.restoreListeners();
verify(sortedRowListComparator).addListener(tableComparatorListener);
verify(selectedProperty).addListener(tableSelectionListener);
verify(selectedItems).addListener(selectedOnlySelectionListener);
}
@Test
public void removeListeners() {
tableViewPageFactory.removeListeners();
verify(sortedRowListComparator).removeListener(tableComparatorListener);
verify(selectedProperty).removeListener(tableSelectionListener);
verify(selectedItems).removeListener(selectedOnlySelectionListener);
}
@Test
public void callEnsureExternalCallsMade() {
doNothing().when(tableViewPageFactory)
.restoreSelectionFromGraph(any(Graph.class), any(TableViewState.class), any(Map.class));
final ObservableList<String> row1 = FXCollections.observableArrayList(List.of("row1Column1", "row1Column2"));
final ObservableList<String> row2 = FXCollections.observableArrayList(List.of("row2Column1", "row2Column2"));
final ObservableList<String> row3 = FXCollections.observableArrayList(List.of("row3Column1", "row3Column2"));
final List<ObservableList<String>> newRowList = List.of(row1, row2, row3);
final Map<Integer, ObservableList<String>> elementIdToRowIndex = Map.of();
final int maxRowsPerPage = 2;
final int pageIndex = 0;
final TableColumn<ObservableList<String>, String> sortCol = mock(TableColumn.class);
final Pair<TableColumn<ObservableList<String>, ?>, TableColumn.SortType> currentSort
= ImmutablePair.of(sortCol, TableColumn.SortType.DESCENDING);
doReturn(currentSort).when(tableViewPageFactory).getCurrentSort();
doNothing().when(tableViewPageFactory).restoreSort(any(Pair.class));
final TableViewState tableViewState = new TableViewState();
tableViewState.setSelectedOnly(false);
when(tableViewTopComponent.getCurrentState()).thenReturn(tableViewState);
when(activeTableReference.getElementIdToRowIndex()).thenReturn(elementIdToRowIndex);
selectedOnlySelectedRows.add(row1);
selectedOnlySelectedRows.add(row2);
// This is called after the page set up so just mocking it so that it is realistic
when(tableView.getItems()).thenReturn(FXCollections.observableList(List.of(row1, row2)));
tableViewPageFactory.update(newRowList, maxRowsPerPage);
assertEquals(tableView, tableViewPageFactory.call(pageIndex));
verify(tableViewPageFactory).removeListeners();
verify(tableViewPageFactory).getCurrentSort();
verify(sortedRowListComparator).unbind();
verify(tableView).setItems(FXCollections.observableList(List.of(row1, row2)));
verify(sortedRowListComparator).bind(tableViewComparator);
verify(tableViewPageFactory).restoreSort(currentSort);
verify(tableViewPageFactory).restoreSelectionFromGraph(graph, tableViewState, elementIdToRowIndex);
// This is the first call so selectedOnlySelectedRows will be cleared
// and the selection is not updated
verify(selectionModel, times(0)).selectIndices(0, 0, 1);
verify(tableViewPageFactory).restoreListeners();
}
@Test
public void callSelectedOnlyModeMultipleCalls() {
doNothing().when(tableViewPageFactory)
.restoreSelectionFromGraph(any(Graph.class), any(TableViewState.class), any(Map.class));
final ObservableList<String> row1 = FXCollections.observableArrayList(List.of("row1Column1", "row1Column2"));
final ObservableList<String> row2 = FXCollections.observableArrayList(List.of("row2Column1", "row2Column2"));
final ObservableList<String> row3 = FXCollections.observableArrayList(List.of("row3Column1", "row3Column2"));
final int maxRowsPerPage = 2;
final int pageIndex = 0;
final ObservableList<TableColumn<ObservableList<String>, String>> sortOrder
= FXCollections.observableArrayList();
doReturn(sortOrder).when(tableView).getSortOrder();
final TableViewState tableViewState = new TableViewState();
tableViewState.setSelectedOnly(true);
when(tableViewTopComponent.getCurrentState()).thenReturn(tableViewState);
// This is called after the page set up so just mocking it so that it is realistic
when(tableView.getItems()).thenReturn(FXCollections.observableList(List.of(row1, row2)));
// =============RUN ONE=================
tableViewPageFactory.update(List.of(row1, row2, row3), maxRowsPerPage);
// Set the selected only mode selection to rows 1 and 2
selectedOnlySelectedRows.add(row1);
selectedOnlySelectedRows.add(row2);
assertEquals(tableView, tableViewPageFactory.call(pageIndex));
// In the first call this gets cleared
assertTrue(selectedOnlySelectedRows.isEmpty());
// =============RUN TWO=================
// Re-populate the selected only selected rows set as it was cleared in run 1
selectedOnlySelectedRows.add(row1);
selectedOnlySelectedRows.add(row2);
assertEquals(tableView, tableViewPageFactory.call(pageIndex));
// The second run has the same new row list so it does not get cleared
assertEquals(2, selectedOnlySelectedRows.size());
// =============RUN THREE=================
// Change the new row list
tableViewPageFactory.update(List.of(row1, row2), maxRowsPerPage);
assertEquals(tableView, tableViewPageFactory.call(pageIndex));
// The third run now has a different new row list so it is cleared again
assertTrue(selectedOnlySelectedRows.isEmpty());
// ======================================
verify(tableView, times(3)).setItems(FXCollections.observableList(List.of(row1, row2)));
assertTrue(sortOrder.isEmpty());
// This selection update only happens in the second run as it is called with
// the same new row list and that avoids it being cleared
verify(selectionModel, times(1)).selectIndices(0, 0, 1);
}
@Test
public void updateSelectionGraphNull() {
try (final MockedStatic<Platform> platformMockedStatic = Mockito.mockStatic(Platform.class)) {
tableViewPageFactory.restoreSelectionFromGraph(null, new TableViewState(), null);
platformMockedStatic.verifyNoInteractions();
}
}
@Test
public void updateSelectionStateNull() {
try (final MockedStatic<Platform> platformMockedStatic = Mockito.mockStatic(Platform.class)) {
tableViewPageFactory.restoreSelectionFromGraph(graph, null, null);
platformMockedStatic.verifyNoInteractions();
}
}
@Test(expectedExceptions = IllegalStateException.class)
public void updateSelectionNotOnFxThread() {
try (final MockedStatic<Platform> platformMockedStatic = Mockito.mockStatic(Platform.class)) {
platformMockedStatic.when(Platform::isFxApplicationThread).thenReturn(false);
tableViewPageFactory.restoreSelectionFromGraph(graph, new TableViewState(), null);
}
}
@Test
public void updateSelectionInSelectedOnlyMode() {
try (final MockedStatic<Platform> platformMockedStatic = Mockito.mockStatic(Platform.class)) {
platformMockedStatic.when(Platform::isFxApplicationThread).thenReturn(true);
final TableViewState tableViewState = new TableViewState();
tableViewState.setSelectedOnly(true);
tableViewPageFactory.restoreSelectionFromGraph(graph, tableViewState, null);
verifyNoInteractions(table);
}
}
@Test
public void updateSelectionNotInSelectedOnlyMode() throws InterruptedException, ExecutionException {
final TableViewState tableViewState = new TableViewState();
tableViewState.setSelectedOnly(false);
tableViewState.setElementType(GraphElementType.VERTEX);
doReturn(List.of(100, 102)).when(tableViewPageFactory)
.getSelectedIds(any(Graph.class), any(TableViewState.class));
final ObservableList<String> vertex1 = FXCollections.observableList(
List.of("Vertex1Attr1", "Vertex1Attr2"));
final ObservableList<String> vertex2 = FXCollections.observableList(
List.of("Vertex2Attr1", "Vertex2Attr2"));
final ObservableList<String> vertex3 = FXCollections.observableList(
List.of("Vertex3Attr1", "Vertex3Attr2"));
final Map<Integer, ObservableList<String>> elementIdToRowIndex = Map.of(
100, vertex1,
102, vertex2,
103, vertex3
);
// Order is important here. Should match on vertex 1 and 2, so indicies 0 and 2.
when(tableView.getItems()).thenReturn(
FXCollections.observableList(List.of(vertex1, vertex3, vertex2))
);
try (final MockedStatic<Platform> platformMockedStatic = Mockito.mockStatic(Platform.class)) {
platformMockedStatic.when(Platform::isFxApplicationThread).thenReturn(true);
tableViewPageFactory
.restoreSelectionFromGraph(graph, tableViewState, elementIdToRowIndex);
}
verify(tableViewPageFactory).getSelectedIds(graph, tableViewState);
verify(selectionModel).clearSelection();
verify(selectionModel).selectIndices(0, 0, 2);
}
}
| 42.538627 | 117 | 0.728195 |
b2fae1317e5c761a0e20b6c217e096d0eba5ca7e | 16,334 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sigad.sigad.business.helpers;
import com.grupo1.simulated_annealing.Locacion;
import com.grupo1.simulated_annealing.Pista;
import com.grupo1.simulated_annealing.VRPAlgorithm;
import com.grupo1.simulated_annealing.VRPCostMatrix;
import com.grupo1.simulated_annealing.VRPProblem;
import com.sigad.sigad.app.controller.LoginController;
import com.sigad.sigad.business.Constantes;
import com.sigad.sigad.business.MovimientosTienda;
import com.sigad.sigad.business.Pedido;
import com.sigad.sigad.business.PedidoEstado;
import com.sigad.sigad.business.Reparto;
import com.sigad.sigad.business.Tienda;
import com.sigad.sigad.business.TipoMovimiento;
import com.sigad.sigad.business.Usuario;
import com.sigad.sigad.business.Vehiculo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.jgrapht.Graph;
import org.jgrapht.graph.GraphWalk;
import org.jgrapht.graph.SimpleGraph;
/**
*
* @author cfoch
*/
public class AlgoritmoHelper extends BaseHelper {
public AlgoritmoHelper() {
super();
}
public AlgoritmoHelper(boolean close) {
super(close);
}
public Tienda getTiendaActual(Usuario usuario) {
Tienda tienda;
tienda = usuario.getTienda();
return tienda;
}
public void autogenerarRepartos(Tienda tienda,
String turno) throws Exception {
int i, j;
try (Session session = LoginController.serviceInit()) {
PedidoHelper helperPedido = new PedidoHelper();
List<Pedido> pedidos;
List<List<Pedido>> pedidosSublists;
List<PedidoEstado> estados;
PedidoEstado estado;
String hql;
Double totalCapacidadTipo;
Vehiculo.Tipo tipoVehiculo;
double [] proportions;
int iPedido, jPedido;
tienda = (Tienda) session.createQuery("from Tienda where id = :id")
.setParameter("id", tienda.getId())
.getSingleResult();
estados = (List<PedidoEstado>) session.createQuery(
"from PedidoEstado where nombre='Venta'").list();
if (estados.isEmpty()) {
throw new Exception("El estado 'Venta' no está registrado.");
}
estado = estados.get(0);
List<Vehiculo> vehiculos = tienda.getVehiculos();
pedidos = helperPedido.getPedidosPorTienda(tienda, estado,
turno, new Date());
if (pedidos.isEmpty()) {
throw new Exception(String.format("No hay pedidos disponibles"
+ "en estado 'Venta' asignados a la tienda (id=%d) para"
+ " el día de hoy.", tienda.getId().intValue()));
}
// FIXME
// Si no hubiera vehiculos asignados para la tienda, se rompe.
try {
tipoVehiculo = vehiculos.get(0).getTipo();
} catch (Exception ex) {
throw new Exception(String.format("No existe un vehículo o "
+ "tipo de vehículo registrado para la tienda id=%d.",
tienda.getId()));
}
generarRepartos(tienda, pedidos, tipoVehiculo, vehiculos, turno);
} catch (Exception ex) {
throw ex;
}
}
public void generarRepartos(Tienda tienda, List<Pedido> pedidos,
Vehiculo.Tipo vehiculoTipo, List<Vehiculo> vehiculos, String turno)
throws Exception {
boolean customMsg = false;
try {
GraphHopperHelper hopperHelper;
VRPProblem problem;
VRPAlgorithm algorithm;
ArrayList<GraphWalk> solution;
double [][] costMatrix;
Locacion [] locaciones;
List<Usuario> repartidores = new ArrayList<>();
Usuario repartidor;
Random rand = new Random();
int i, j;
// Resolver problema VRP
locaciones = createLocaciones(tienda, pedidos);
// try {
hopperHelper = GraphHopperHelper.getInstance();
try {
costMatrix = hopperHelper.getCostMatrix(locaciones, true);
} catch (Exception ex) {
customMsg = true;
throw new Exception("Hubo un problema al obtener la matriz "
+ "de distancias. ¿Hay conexión?");
}
problem = AlgoritmoHelper.buildVRPProblem(locaciones,
vehiculoTipo, costMatrix);
algorithm = new VRPAlgorithm(problem);
solution = algorithm.solve();
algorithm.printSolution(solution);
// Generar repartos
try {
repartidores = (List<Usuario>) session
.createQuery(
"from Usuario u where tienda_id = :tienda_id and u.perfil.nombre='Repartidor'")
.setParameter("tienda_id", tienda.getId())
.list();
} catch (Exception ex) {
customMsg = true;
throw new Exception(String.format("No existen repartidores "
+ "para la tienda con id='%d'.", tienda.getId()));
}
if (repartidores.isEmpty()) {
customMsg = true;
throw new Exception(String.format("No existen repartidores "
+ "para la tienda con id='%d'.", tienda.getId()));
}
for (i = 0; i < solution.size(); i++) {
Vehiculo vehiculo = vehiculos.get(i % vehiculos.size());
List<Pedido> subpedidos;
List<Locacion> ruta = solution.get(i).getVertexList();
subpedidos = locacionesToPedidos(ruta);
repartidor =
repartidores.get(rand.nextInt(repartidores.size()));
session.getTransaction().begin();
Reparto reparto = new Reparto();
reparto.setVehiculo(vehiculo);
reparto.setPedidos(subpedidos);
reparto.setFecha(new Date());
reparto.setRepartidor(repartidor);
reparto.setTurno(turno);
reparto.setTienda(repartidor.getTienda());
session.save(reparto);
for (j = 0; j < subpedidos.size(); j++) {
Pedido subpedido = subpedidos.get(j);
subpedido.setReparto(reparto);
try {
cambiarPedidoEstado(subpedido, "Despacho");
} catch (Exception ex) {
customMsg = true;
throw ex;
}
subpedido.setSecuenciaReparto(j);
session.save(subpedido);
}
session.getTransaction().commit();
}
} catch (VRPProblem.VRPProblemInvalidGraph |
VRPAlgorithm.VRPAlgorithmSolutionNotPossible ex) {
Logger.getLogger(AlgoritmoHelper.class.getName())
.log(Level.SEVERE, null, ex);
throw ex;
} catch (Exception ex) {
Logger.getLogger(AlgoritmoHelper.class.getName())
.log(Level.SEVERE, null, ex);
session.getTransaction().rollback();
if (!customMsg) {
throw new Exception("Hubo un problema en la base de datos.");
} else {
throw ex;
}
}
}
public boolean cambiarPedidoEstado(Pedido pedido, String estadoNombre)
throws Exception {
PedidoEstado estadoNuevo;
try {
estadoNuevo = (PedidoEstado) session
.createQuery("from PedidoEstado where nombre = :nombre")
.setParameter("nombre", estadoNombre)
.getSingleResult();
} catch (Exception ex) {
Logger.getLogger(getClass().getName())
.log(Level.SEVERE, null, ex);
throw new Exception(String.format("El estado 'Despacho' no "
+ "está registrado."));
}
return cambiarPedidoEstado(pedido, estadoNuevo);
}
public boolean cambiarPedidoEstado(Pedido pedido,
PedidoEstado estadoNuevo) throws Exception {
boolean ret = false;
PedidoEstado estadoActual = pedido.getEstado();
String estadoActualNombre = estadoActual.getNombre();
if (estadoActualNombre.equals("Venta") &&
estadoNuevo.getNombre().equals("Despacho")) {
int i;
String tipoMovimientoNombre = Constantes.TIPO_MOVIMIENTO_SALIDA_LOGICA;
List<MovimientosTienda> movimientos;
TipoMovimiento tipoMovimientoSalidaFisica = null;
// TODO
// Debería usarse preferiblemente TipoMovimientoHelper, pero por
// alguna razón cierra la sesión. Por ahora, este workaround:
try {
Query query;
query = session
.createQuery("from TipoMovimiento where nombre = :nombre")
.setParameter("nombre", Constantes.TIPO_MOVIMIENTO_SALIDA_FISICA);
if (!query.list().isEmpty()) {
tipoMovimientoSalidaFisica = (TipoMovimiento) query.list().get(0);
}
} catch (Exception ex) {
}
if (tipoMovimientoSalidaFisica == null) {
throw new Exception(String.format("No existe tipo de "
+ "movimiento '%s'",
Constantes.TIPO_MOVIMIENTO_SALIDA_FISICA));
}
try {
movimientos = (List<MovimientosTienda>) session
.createQuery("from MovimientosTienda as mov "
+ "where mov.pedido.id = :pedido_id and "
+ "mov.tipoMovimiento.nombre = :tipoMovimiento")
.setParameter("pedido_id", pedido.getId())
.setParameter("tipoMovimiento", tipoMovimientoNombre)
.list();
} catch (Exception ex) {
Logger.getLogger(getClass().getName())
.log(Level.SEVERE, null, ex);
throw new Exception(String.format("No existe movimiento de "
+ "tipo '%s' para el pedido con id %d",
tipoMovimientoNombre, pedido.getId()));
}
for (i = 0; i < movimientos.size(); i++) {
MovimientosTienda movimiento = movimientos.get(i);
MovimientosTienda movimientoNuevo = new MovimientosTienda();
movimientoNuevo.setCantidadMovimiento(
movimiento.getCantidadMovimiento());
movimientoNuevo.setFecha(movimiento.getFecha());
movimientoNuevo.setLoteInsumo(movimiento.getLoteInsumo());
movimientoNuevo.setPedido(movimiento.getPedido());
movimientoNuevo.setTienda(movimiento.getTienda());
movimientoNuevo.setTipoMovimiento(tipoMovimientoSalidaFisica);
movimientoNuevo.setTrabajador(movimiento.getTrabajador());
try {
session.save(movimientoNuevo);
} catch (Exception ex) {
Logger.getLogger(getClass().getName())
.log(Level.SEVERE, null, ex);
session.getTransaction().rollback();
throw new Exception(String.format("No se pudo crear un "
+ "movimiento de tipo '%s' para el "
+ "pedido con id %d",
Constantes.TIPO_MOVIMIENTO_SALIDA_FISICA,
pedido.getId()));
}
}
pedido.setEstado(estadoNuevo);
ret = true;
}
return ret;
}
public List<Pedido> locacionesToPedidos(
List<Locacion> locaciones) {
Query query;
List<Pedido> pedidos;
long [] idPedidosTmp;
Long [] idPedidos;
try {
idPedidosTmp = locaciones.stream()
.filter(l -> l.getServicio() != null)
.mapToLong(l -> l.getId())
.toArray();
idPedidos = ArrayUtils.toObject(idPedidosTmp);
query = session.createQuery("from Pedido p where p.id in (:ids)")
.setParameterList("ids", idPedidos);
pedidos = (List<Pedido>) query.list();
} catch (Exception ex) {
pedidos = new ArrayList<>();
}
return pedidos;
}
/**
* Obtiene pedidos a repartir. Los pedidos deben tener estado VENTA.
* @param usuario
* @return
*/
public static final List<Pedido> getPedidos(final Usuario usuario) {
ArrayList<Pedido> pedidos;
pedidos = new ArrayList<>();
return pedidos;
}
/**
* Dado una tienda y una lista de pedidos, los convierte en un formato
* entendido por el algoritmo VRP.
* @param tienda
* @param pedidos
* @return Un array de Locacion donde el primer elemento corresponde a la
* tienda.
*/
public static final Locacion [] createLocaciones(final Tienda tienda,
final List<Pedido> pedidos) {
int i;
Locacion [] locaciones = new Locacion[1 + pedidos.size()];
locaciones[0] = tienda.getLocacion();
for (i = 0; i < pedidos.size(); i++) {
locaciones[i + 1] = pedidos.get(i).getLocacion();
}
return locaciones;
}
/**
* Construye un problema de VRP dadas ciertas locaciones, un tipo de
* vehículo y una matriz de costos.
* @param locaciones
* @param vehiculoTipo
* @param costMatrix
* @return Un VRPProblem
* @throws Exception
*/
public static final VRPProblem buildVRPProblem(Locacion [] locaciones,
Vehiculo.Tipo vehiculoTipo,
double [][] costMatrix) throws VRPProblem.VRPProblemInvalidGraph {
int i, j;
Stream<Locacion> stream;
VRPCostMatrix vrpMatrix;
Graph<Locacion, Pista> grafo;
try {
vrpMatrix = new VRPCostMatrix(costMatrix, locaciones);
} catch (Exception ex) {
vrpMatrix = null;
}
grafo = new SimpleGraph<>(Pista.class);
for (i = 0; i < locaciones.length; i++) {
Locacion locacion;
locacion = locaciones[i];
locacion.setCostMatrix(vrpMatrix);
grafo.addVertex(locacion);
}
for (i = 0; i < locaciones.length; i++) {
Locacion v1;
v1 = locaciones[i];
for (j = 0; j < locaciones.length; j++) {
Locacion v2;
v2 = locaciones[j];
if (i == j) {
continue;
}
grafo.addEdge(v1, v2);
}
}
return new VRPProblem(grafo, locaciones[0], vehiculoTipo.getTipo());
}
public List<Locacion> repartoToRoute(Reparto reparto) {
int i;
ArrayList<Locacion> ruta = new ArrayList<>();
Tienda tienda = reparto.getTienda();
List<Pedido> pedidos = reparto.getPedidos();
pedidos = pedidos.stream()
.sorted((a, b) -> a.getSecuenciaReparto() - b.getSecuenciaReparto())
.collect(Collectors.toList());
ruta.add(tienda.getLocacion());
for (i = 0; i < pedidos.size(); i++) {
Pedido pedido = pedidos.get(i);
ruta.add(pedido.getLocacion());
}
ruta.add(tienda.getLocacion());
return ruta;
}
}
| 39.549637 | 111 | 0.551304 |
dda24510744abc9659e2f51b9b463d6590965be1 | 2,788 | /* -------------------------------------------------------------------
Copyright (c) 2014, Andreas Löscher <[email protected]> and
All rights reserved.
This file is distributed under the Simplified BSD License.
Details can be found in the LICENSE file.
------------------------------------------------------------------- */
package se.uu.it.parapluu.cooja_node;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JLabel;
//import org.apache.log4j.Logger;
import se.sics.cooja.ClassDescription;
import se.sics.cooja.Cooja;
import se.sics.cooja.PluginType;
import se.sics.cooja.Simulation;
import se.sics.cooja.VisPlugin;
import com.ericsson.otp.erlang.OtpAuthException;
import com.ericsson.otp.erlang.OtpConnection;
import com.ericsson.otp.erlang.OtpPeer;
import com.ericsson.otp.erlang.OtpSelf;
@SuppressWarnings("serial")
@ClassDescription("Nifty Control Plugin")
@PluginType(PluginType.SIM_CONTROL_PLUGIN)
public class SocketControlPlugin extends VisPlugin {
//private static Logger logger = Logger.getLogger(SocketControlPlugin.class);
private final static int LABEL_WIDTH = 100;
private final static int LABEL_HEIGHT = 15;
private final long MAGIC_NUMBER = 0L;
private JLabel label;
private OtpSelf self;
private String name = "cooja_control";
private String peer = "cooja_master";
private OtpPeer enode;
private OtpConnection conn;
private MessageHandler handler;
public SocketControlPlugin(Simulation sim, Cooja gui) {
super("Nifty Control Plugin", gui, false);
if (Cooja.isVisualized()) {
Box northBox = Box.createHorizontalBox();
northBox.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Box mainBox = Box.createHorizontalBox();
mainBox.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
label = new JLabel("Nifty Control Plugin: connected");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
mainBox.add(BorderLayout.CENTER, label);
getContentPane().add(BorderLayout.NORTH, northBox);
getContentPane().add(BorderLayout.CENTER, mainBox);
pack();
}
try {
connect();
this.handler = new MessageHandler(conn, self.createPid(), sim);
this.handler.start();
sim.stopSimulation();
sim.setRandomSeed(this.MAGIC_NUMBER);
} catch (IOException | OtpAuthException e) {
if (Cooja.isVisualized()) {
label.setText("Nifty Control Plugin: not connected");
}
}
}
private void connect() throws IOException, OtpAuthException {
this.self = new OtpSelf(this.name);
this.enode = new OtpPeer(this.peer);
this.conn = this.self.connect(this.enode);
}
public void closePlugin() {
if (this.conn!= null) {
this.conn.close();
}
}
}
| 28.742268 | 78 | 0.710187 |
7f5f67c0a7cb4bfd13f12ae4146f9f23ab56aa83 | 4,133 | package test.integration.api;
import org.junit.jupiter.api.Test;
import se.jbee.inject.*;
import se.jbee.lang.Qualifying;
import se.jbee.lang.Type;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
import static se.jbee.inject.Instance.defaultInstanceOf;
import static se.jbee.inject.Instance.instance;
import static se.jbee.inject.Name.named;
import static se.jbee.lang.Type.raw;
class TestMoreQualified {
private static class HigherNumberIsMoreQualified
implements Qualifying<HigherNumberIsMoreQualified> {
final int value;
HigherNumberIsMoreQualified(int value) {
this.value = value;
}
@Override
public boolean moreQualifiedThan(HigherNumberIsMoreQualified other) {
return value > other.value;
}
}
static HigherNumberIsMoreQualified hip(int value) {
return new HigherNumberIsMoreQualified(value);
}
@Test
void moreQualifiedValueIsRecognisedAsMoreQualified() {
assertTrue(hip(2).moreQualifiedThan(hip(1)));
}
@Test
void equallyQualifiedValueIsNotMoreQualified() {
assertFalse(hip(2).moreQualifiedThan(hip(2)));
}
@Test
void lessQualifiedValueIsNotMoreQualified() {
assertFalse(hip(1).moreQualifiedThan(hip(2)));
}
@Test
void mostQualifiedIsFirstInSortOrder() {
HigherNumberIsMoreQualified[] values = new HigherNumberIsMoreQualified[] {
hip(1), hip(2) };
Arrays.sort(values, Qualifying::compare);
assertEquals(2, values[0].value);
}
@Test
void sameTypeIsNotMoreQualified() {
assertNotMoreQualifiedThanItself(Type.raw(String.class));
}
@Test
void sameDefaultNameIsNotMoreQualified() {
assertNotMoreQualifiedThanItself(Name.DEFAULT);
}
/**
* This might sound a bit surprising at first. The reason is that an
* "unnamed" instance is actually a named instance having the {@link
* Name#DEFAULT} name. This is so that in case such a instance exists and
* {@link Name#ANY} is used to resolve it you get the default named
* instance. Should on the other hand a specific name be resolved it does
* not matter that the default name is more qualified as it will not match
* the specific name resolved.
*/
@Test
void unnamedIsMoreQualifiedThanNamedInstance() {
Type<Integer> type = raw(Integer.class);
Instance<Integer> named = instance(named("foo"), type);
Instance<Integer> unnamed = defaultInstanceOf(type);
assertMoreQualified(unnamed, named);
}
@Test
void unnamedIsMoreQualifiedThanNamed() {
assertTrue(Name.DEFAULT.moreQualifiedThan(named("foo")));
}
@Test
void namedIsNotMoreQualifiedThanUnnamed() {
assertFalse(named("bar").moreQualifiedThan(Name.DEFAULT));
}
@Test
void sameSpecificPackageIsNotMoreQualified() {
assertNotMoreQualifiedThanItself(Packages.packageOf(String.class));
}
@Test
void specificPackageIsMoreQualifiedThanGlobal() {
assertMoreQualified(Packages.packageOf(String.class), Packages.ALL);
}
@Test
void specificPackageIsMoreQualifiedThanThatPackageWithItsSubPackages() {
assertMoreQualified(Packages.packageOf(String.class),
Packages.packageAndSubPackagesOf(String.class));
}
@Test
void specificPackageIsMoreQualifiedThanSubPackagesUnderIt() {
assertMoreQualified(Packages.packageOf(String.class),
Packages.subPackagesOf(String.class));
}
@Test
void qualificationIsGivenByOrdinalStartingWithLowest() {
DeclarationType[] types = DeclarationType.values();
for (int i = 1; i < types.length; i++) {
assertTrue(types[i].moreQualifiedThan(types[i - 1]));
}
}
@Test
void explicitSourceIsMoreQualifiedThanPublishedSource() {
Source source = Source.source(TestMoreQualified.class);
assertMoreQualified(source.typed(DeclarationType.EXPLICIT),
source.typed(DeclarationType.PUBLISHED));
}
private static <T extends Qualifying<? super T>> void assertMoreQualified(
T morePrecise, T lessPrecise) {
assertTrue(morePrecise.moreQualifiedThan(lessPrecise));
assertFalse(lessPrecise.moreQualifiedThan(morePrecise));
}
private static <T extends Qualifying<? super T>> void assertNotMoreQualifiedThanItself(
T type) {
assertFalse(type.moreQualifiedThan(type));
assertEquals(0, Qualifying.compare(type, type));
}
}
| 27.925676 | 88 | 0.766997 |
d5d0628264596198b13d7e094b9297dea4a8547f | 462 | package com.hrm.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.Map;
/**
* @author zjw
* @package backend
* @Date 2021/7/12
* @Time 10:21
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Cart {
private Integer user_id;
private Integer product_id;
private Integer buy_count;
private Integer specification_id;
} | 17.769231 | 38 | 0.705628 |
955893c9952d75f5377ca5b7c2cc39e5ce673852 | 3,040 | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.baasdt.models;
import com.aliyun.tea.*;
public class ConfirmIpSuperviseapproveRequest extends TeaModel {
// OAuth模式下的授权token
@NameInMap("auth_token")
public String authToken;
@NameInMap("product_instance_id")
public String productInstanceId;
// 基础字段
@NameInMap("base_request")
@Validation(required = true)
public BaseRequestInfo baseRequest;
// 监修报审关联的订单id
@NameInMap("order_id")
@Validation(required = true)
public String orderId;
// 当前期望的审批阶段(用于校验)
@NameInMap("stage")
@Validation(required = true)
public Long stage;
// 是否审批通过
@NameInMap("is_approval")
@Validation(required = true)
public Boolean isApproval;
// 审批备注
@NameInMap("approval_comments")
public String approvalComments;
// 审批额外信息
@NameInMap("approval_ext_info")
public String approvalExtInfo;
public static ConfirmIpSuperviseapproveRequest build(java.util.Map<String, ?> map) throws Exception {
ConfirmIpSuperviseapproveRequest self = new ConfirmIpSuperviseapproveRequest();
return TeaModel.build(map, self);
}
public ConfirmIpSuperviseapproveRequest setAuthToken(String authToken) {
this.authToken = authToken;
return this;
}
public String getAuthToken() {
return this.authToken;
}
public ConfirmIpSuperviseapproveRequest setProductInstanceId(String productInstanceId) {
this.productInstanceId = productInstanceId;
return this;
}
public String getProductInstanceId() {
return this.productInstanceId;
}
public ConfirmIpSuperviseapproveRequest setBaseRequest(BaseRequestInfo baseRequest) {
this.baseRequest = baseRequest;
return this;
}
public BaseRequestInfo getBaseRequest() {
return this.baseRequest;
}
public ConfirmIpSuperviseapproveRequest setOrderId(String orderId) {
this.orderId = orderId;
return this;
}
public String getOrderId() {
return this.orderId;
}
public ConfirmIpSuperviseapproveRequest setStage(Long stage) {
this.stage = stage;
return this;
}
public Long getStage() {
return this.stage;
}
public ConfirmIpSuperviseapproveRequest setIsApproval(Boolean isApproval) {
this.isApproval = isApproval;
return this;
}
public Boolean getIsApproval() {
return this.isApproval;
}
public ConfirmIpSuperviseapproveRequest setApprovalComments(String approvalComments) {
this.approvalComments = approvalComments;
return this;
}
public String getApprovalComments() {
return this.approvalComments;
}
public ConfirmIpSuperviseapproveRequest setApprovalExtInfo(String approvalExtInfo) {
this.approvalExtInfo = approvalExtInfo;
return this;
}
public String getApprovalExtInfo() {
return this.approvalExtInfo;
}
}
| 27.142857 | 105 | 0.690132 |
519e8e465364e4b56e10186c443cb60fbf59348f | 1,523 | package com.winter.flashsale.mq;
import com.winter.flashsale.config.RabbitConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Slf4j
@Service
public class MyConfirmCallback implements RabbitTemplate.ConfirmCallback {
private static final String FLASHSALE_ROUTING = RabbitConfig.TOPIC_ + RabbitConfig.ORDER_KEY;
private final RabbitTemplate template;
public MyConfirmCallback(RabbitTemplate template) {
this.template = template;
}
@Override
public void confirm(CorrelationData correlationData, boolean ack, String s) {
if (correlationData == null) {
log.error("null correlation data for call back");
return;
}
String correlationId = correlationData.getId();
String order = MyDataRelation.get(correlationId);
if (!ack) {
log.info("confirm NACK for {}, starting retransmission", order);
CorrelationData retxData = new CorrelationData(UUID.randomUUID().toString());
MyDataRelation.del(correlationId);
MyDataRelation.add(retxData.getId(), order);
template.convertAndSend(RabbitConfig.ORDER_EVENT_EXCHANGE, FLASHSALE_ROUTING, order, retxData);
} else {
log.info("confirm ack for " + order);
MyDataRelation.del(correlationId);
}
}
}
| 33.108696 | 107 | 0.699934 |
f413888a7783bffe1d674cf86f182c7dd77bb488 | 1,906 | package validation.constraints.validator;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import javax.validation.ConstraintViolation;
import org.junit.Test;
import validation.constraints.CorrelationValid;
/**
* Tests CorrelationValidator
* @author hironobu-igawa
*/
public class CorrelationValidatorTest extends ValidatorTest {
/**
* Tests valid pattern.
*/
@Test
public void testValid() {
TestBean bean = new TestBean();
bean.correlation1 = "a";
bean.correlation2 = "a";
Set<ConstraintViolation<TestBean>> violations = validate(bean);
assertEquals(0, violations.size());
}
/**
* Tests invalid pattern.
*/
@Test
public void testInvalid() {
TestBean bean = new TestBean();
bean.correlation1 = "a";
bean.correlation2 = "b";
Set<ConstraintViolation<TestBean>> violations = validate(bean);
assertEquals(1, violations.size());
assertEquals("CorrelationValid constraint violation. labels: [CorrelationValid1, CorrelationValid2]", violations.iterator().next().getMessage());
}
/**
* Tests null pattern.
*/
@Test
public void test() {
TestBean bean = new TestBean();
bean.correlation1 = null;
bean.correlation2 = "b";
Set<ConstraintViolation<TestBean>> violations = validate(bean);
assertEquals(0, violations.size());
}
private static class TestBean {
public String correlation1;
public String correlation2;
@CorrelationValid(message="CORRELATIONVALID", labels={"label.correlationvalid1", "label.correlationvalid2"})
public boolean isValidMatchPassword() {
if (correlation1 == null || correlation2 == null) {
return true;
}
return correlation1.equals(correlation2);
}
}
}
| 26.472222 | 153 | 0.637985 |
75480b5dd2fee73b6efa0a62dffa069fa1f5c353 | 10,507 | /*
* 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 android.net.wifi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import android.net.wifi.WifiEnterpriseConfig.Eap;
import android.net.wifi.WifiEnterpriseConfig.Phase2;
import android.os.Parcel;
import android.security.Credentials;
import android.test.suitebuilder.annotation.SmallTest;
import org.junit.Before;
import org.junit.Test;
import java.security.cert.X509Certificate;
/**
* Unit tests for {@link android.net.wifi.WifiEnterpriseConfig}.
*/
@SmallTest
public class WifiEnterpriseConfigTest {
// Maintain a ground truth of the keystore uri prefix which is expected by wpa_supplicant.
public static final String KEYSTORE_URI = "keystore://";
public static final String CA_CERT_PREFIX = KEYSTORE_URI + Credentials.CA_CERTIFICATE;
public static final String KEYSTORES_URI = "keystores://";
private WifiEnterpriseConfig mEnterpriseConfig;
@Before
public void setUp() throws Exception {
mEnterpriseConfig = new WifiEnterpriseConfig();
}
@Test
public void testSetGetSingleCaCertificate() {
X509Certificate cert0 = FakeKeys.CA_CERT0;
mEnterpriseConfig.setCaCertificate(cert0);
assertEquals(mEnterpriseConfig.getCaCertificate(), cert0);
}
@Test
public void testSetGetMultipleCaCertificates() {
X509Certificate cert0 = FakeKeys.CA_CERT0;
X509Certificate cert1 = FakeKeys.CA_CERT1;
mEnterpriseConfig.setCaCertificates(new X509Certificate[] {cert0, cert1});
X509Certificate[] result = mEnterpriseConfig.getCaCertificates();
assertEquals(result.length, 2);
assertTrue(result[0] == cert0 && result[1] == cert1);
}
@Test
public void testSaveSingleCaCertificateAlias() {
final String alias = "single_alias 0";
mEnterpriseConfig.setCaCertificateAliases(new String[] {alias});
assertEquals(getCaCertField(), CA_CERT_PREFIX + alias);
}
@Test
public void testLoadSingleCaCertificateAlias() {
final String alias = "single_alias 1";
setCaCertField(CA_CERT_PREFIX + alias);
String[] aliases = mEnterpriseConfig.getCaCertificateAliases();
assertEquals(aliases.length, 1);
assertEquals(aliases[0], alias);
}
@Test
public void testSaveMultipleCaCertificates() {
final String alias0 = "single_alias 0";
final String alias1 = "single_alias 1";
mEnterpriseConfig.setCaCertificateAliases(new String[] {alias0, alias1});
assertEquals(getCaCertField(), String.format("%s%s %s",
KEYSTORES_URI,
WifiEnterpriseConfig.encodeCaCertificateAlias(Credentials.CA_CERTIFICATE + alias0),
WifiEnterpriseConfig.encodeCaCertificateAlias(Credentials.CA_CERTIFICATE + alias1)));
}
@Test
public void testLoadMultipleCaCertificates() {
final String alias0 = "single_alias 0";
final String alias1 = "single_alias 1";
setCaCertField(String.format("%s%s %s",
KEYSTORES_URI,
WifiEnterpriseConfig.encodeCaCertificateAlias(Credentials.CA_CERTIFICATE + alias0),
WifiEnterpriseConfig.encodeCaCertificateAlias(Credentials.CA_CERTIFICATE + alias1)));
String[] aliases = mEnterpriseConfig.getCaCertificateAliases();
assertEquals(aliases.length, 2);
assertEquals(aliases[0], alias0);
assertEquals(aliases[1], alias1);
}
private String getCaCertField() {
return mEnterpriseConfig.getFieldValue(WifiEnterpriseConfig.CA_CERT_KEY, "");
}
private void setCaCertField(String value) {
mEnterpriseConfig.setFieldValue(WifiEnterpriseConfig.CA_CERT_KEY, value);
}
// Retrieves the value for a specific key supplied to wpa_supplicant.
private class SupplicantConfigExtractor implements WifiEnterpriseConfig.SupplicantSaver {
private String mValue = null;
private String mKey;
SupplicantConfigExtractor(String key) {
mKey = key;
}
@Override
public boolean saveValue(String key, String value) {
if (key.equals(mKey)) {
mValue = value;
}
return true;
}
public String getValue() {
return mValue;
}
}
private String getSupplicantEapMethod() {
SupplicantConfigExtractor entryExtractor = new SupplicantConfigExtractor(
WifiEnterpriseConfig.EAP_KEY);
mEnterpriseConfig.saveToSupplicant(entryExtractor);
return entryExtractor.getValue();
}
private String getSupplicantPhase2Method() {
SupplicantConfigExtractor entryExtractor = new SupplicantConfigExtractor(
WifiEnterpriseConfig.PHASE2_KEY);
mEnterpriseConfig.saveToSupplicant(entryExtractor);
return entryExtractor.getValue();
}
/** Verifies the default value for EAP outer and inner methods */
@Test
public void eapInnerDefault() {
assertEquals(null, getSupplicantEapMethod());
assertEquals(null, getSupplicantPhase2Method());
}
/** Verifies that the EAP inner method is reset when we switch to TLS */
@Test
public void eapPhase2MethodForTls() {
// Initially select an EAP method that supports an phase2.
mEnterpriseConfig.setEapMethod(Eap.PEAP);
mEnterpriseConfig.setPhase2Method(Phase2.MSCHAPV2);
assertEquals("PEAP", getSupplicantEapMethod());
assertEquals("\"auth=MSCHAPV2\"", getSupplicantPhase2Method());
// Change the EAP method to another type which supports a phase2.
mEnterpriseConfig.setEapMethod(Eap.TTLS);
assertEquals("TTLS", getSupplicantEapMethod());
assertEquals("\"auth=MSCHAPV2\"", getSupplicantPhase2Method());
// Change the EAP method to TLS which does not support a phase2.
mEnterpriseConfig.setEapMethod(Eap.TLS);
assertEquals(null, getSupplicantPhase2Method());
}
/** Verfies that the EAP inner method is reset when we switch phase2 to NONE */
@Test
public void eapPhase2None() {
// Initially select an EAP method that supports an phase2.
mEnterpriseConfig.setEapMethod(Eap.PEAP);
mEnterpriseConfig.setPhase2Method(Phase2.MSCHAPV2);
assertEquals("PEAP", getSupplicantEapMethod());
assertEquals("\"auth=MSCHAPV2\"", getSupplicantPhase2Method());
// Change the phase2 method to NONE and ensure the value is cleared.
mEnterpriseConfig.setPhase2Method(Phase2.NONE);
assertEquals(null, getSupplicantPhase2Method());
}
/** Verfies that the correct "autheap" parameter is supplied for TTLS/GTC. */
@Test
public void peapGtcToTtls() {
mEnterpriseConfig.setEapMethod(Eap.PEAP);
mEnterpriseConfig.setPhase2Method(Phase2.GTC);
assertEquals("PEAP", getSupplicantEapMethod());
assertEquals("\"auth=GTC\"", getSupplicantPhase2Method());
mEnterpriseConfig.setEapMethod(Eap.TTLS);
assertEquals("TTLS", getSupplicantEapMethod());
assertEquals("\"autheap=GTC\"", getSupplicantPhase2Method());
}
/** Verfies that the correct "auth" parameter is supplied for PEAP/GTC. */
@Test
public void ttlsGtcToPeap() {
mEnterpriseConfig.setEapMethod(Eap.TTLS);
mEnterpriseConfig.setPhase2Method(Phase2.GTC);
assertEquals("TTLS", getSupplicantEapMethod());
assertEquals("\"autheap=GTC\"", getSupplicantPhase2Method());
mEnterpriseConfig.setEapMethod(Eap.PEAP);
assertEquals("PEAP", getSupplicantEapMethod());
assertEquals("\"auth=GTC\"", getSupplicantPhase2Method());
}
/** Verfies that the copy constructor preseves the inner method information. */
@Test
public void copyConstructor() {
WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
enterpriseConfig.setEapMethod(Eap.TTLS);
enterpriseConfig.setPhase2Method(Phase2.GTC);
mEnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
assertEquals("TTLS", getSupplicantEapMethod());
assertEquals("\"autheap=GTC\"", getSupplicantPhase2Method());
}
/** Verfies that parceling a WifiEnterpriseConfig preseves method information. */
@Test
public void parcelConstructor() {
WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
enterpriseConfig.setEapMethod(Eap.TTLS);
enterpriseConfig.setPhase2Method(Phase2.GTC);
Parcel parcel = Parcel.obtain();
enterpriseConfig.writeToParcel(parcel, 0);
parcel.setDataPosition(0); // Allow parcel to be read from the beginning.
mEnterpriseConfig = WifiEnterpriseConfig.CREATOR.createFromParcel(parcel);
assertEquals("TTLS", getSupplicantEapMethod());
assertEquals("\"autheap=GTC\"", getSupplicantPhase2Method());
}
/** Verifies proper operation of the getKeyId() method. */
@Test
public void getKeyId() {
assertEquals("NULL", mEnterpriseConfig.getKeyId(null));
WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
enterpriseConfig.setEapMethod(Eap.TTLS);
enterpriseConfig.setPhase2Method(Phase2.GTC);
assertEquals("TTLS_GTC", mEnterpriseConfig.getKeyId(enterpriseConfig));
mEnterpriseConfig.setEapMethod(Eap.PEAP);
mEnterpriseConfig.setPhase2Method(Phase2.MSCHAPV2);
assertEquals("PEAP_MSCHAPV2", mEnterpriseConfig.getKeyId(enterpriseConfig));
}
/** Verifies that passwords are not displayed in toString. */
@Test
public void passwordNotInToString() {
String password = "supersecret";
mEnterpriseConfig.setPassword(password);
assertFalse(mEnterpriseConfig.toString().contains(password));
}
}
| 39.5 | 101 | 0.697154 |
806867b843b71a28663e70be872a7d372340124f | 8,141 | /*
* Copyright 2010-2013 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 org.jetbrains.jet.codegen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.asm4.MethodVisitor;
import org.jetbrains.asm4.Type;
import org.jetbrains.jet.codegen.context.ClassContext;
import org.jetbrains.jet.codegen.state.GenerationState;
import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
import org.jetbrains.jet.lang.descriptors.impl.SimpleFunctionDescriptorImpl;
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
import org.jetbrains.jet.lang.resolve.name.Name;
import java.util.Collections;
import java.util.List;
import static org.jetbrains.asm4.Opcodes.*;
import static org.jetbrains.jet.codegen.AsmUtil.*;
import static org.jetbrains.jet.codegen.binding.CodegenBinding.enumEntryNeedSubclass;
public abstract class ClassBodyCodegen extends MemberCodegen {
protected final JetClassOrObject myClass;
protected final OwnerKind kind;
protected final ClassDescriptor descriptor;
protected final ClassBuilder v;
protected final ClassContext context;
private MethodVisitor clInitMethod;
private ExpressionCodegen clInitCodegen;
protected ClassBodyCodegen(
@NotNull JetClassOrObject aClass,
@NotNull ClassContext context,
@NotNull ClassBuilder v,
@NotNull GenerationState state,
@Nullable MemberCodegen parentCodegen
) {
super(state, parentCodegen);
descriptor = state.getBindingContext().get(BindingContext.CLASS, aClass);
myClass = aClass;
this.context = context;
this.kind = context.getContextKind();
this.v = v;
}
public void generate() {
generateDeclaration();
generateClassBody();
generateSyntheticParts();
generateStaticInitializer();
generateRemoveInIterator();
}
protected abstract void generateDeclaration();
protected void generateSyntheticParts() {
}
private void generateClassBody() {
FunctionCodegen functionCodegen = new FunctionCodegen(context, v, state);
PropertyCodegen propertyCodegen = new PropertyCodegen(context, v, functionCodegen, this);
if (kind != OwnerKind.TRAIT_IMPL) {
//generate nested classes first and only then generate class body. It necessary to access to nested CodegenContexts
for (JetDeclaration declaration : myClass.getDeclarations()) {
if (shouldProcessFirst(declaration)) {
generateDeclaration(propertyCodegen, declaration);
}
}
}
for (JetDeclaration declaration : myClass.getDeclarations()) {
if (!shouldProcessFirst(declaration)) {
generateDeclaration(propertyCodegen, declaration);
}
}
generatePrimaryConstructorProperties(propertyCodegen, myClass);
}
private boolean shouldProcessFirst(JetDeclaration declaration) {
return false == (declaration instanceof JetProperty || declaration instanceof JetNamedFunction);
}
protected void generateDeclaration(PropertyCodegen propertyCodegen, JetDeclaration declaration) {
if (declaration instanceof JetProperty || declaration instanceof JetNamedFunction) {
genFunctionOrProperty(context, (JetTypeParameterListOwner) declaration, v);
}
else if (declaration instanceof JetClassOrObject) {
if (declaration instanceof JetEnumEntry && !enumEntryNeedSubclass(
state.getBindingContext(), (JetEnumEntry) declaration)) {
return;
}
genClassOrObject(context, (JetClassOrObject) declaration);
}
else if (declaration instanceof JetClassObject) {
genClassOrObject(context, ((JetClassObject) declaration).getObjectDeclaration());
}
}
private void generatePrimaryConstructorProperties(PropertyCodegen propertyCodegen, JetClassOrObject origin) {
boolean isAnnotation = origin instanceof JetClass && ((JetClass) origin).isAnnotation();
for (JetParameter p : getPrimaryConstructorParameters()) {
if (p.getValOrVarNode() != null) {
PropertyDescriptor propertyDescriptor = state.getBindingContext().get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, p);
if (propertyDescriptor != null) {
if (!isAnnotation) {
propertyCodegen.generatePrimaryConstructorProperty(p, propertyDescriptor);
}
else {
Type type = state.getTypeMapper().mapType(propertyDescriptor);
v.newMethod(p, ACC_PUBLIC | ACC_ABSTRACT, p.getName(), "()" + type.getDescriptor(), null, null);
}
}
}
}
}
protected @NotNull List<JetParameter> getPrimaryConstructorParameters() {
if (myClass instanceof JetClass) {
return ((JetClass) myClass).getPrimaryConstructorParameters();
}
return Collections.emptyList();
}
private void generateStaticInitializer() {
if (clInitMethod != null) {
createOrGetClInitMethod();
if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
ExpressionCodegen codegen = createOrGetClInitCodegen();
createOrGetClInitMethod().visitInsn(RETURN);
FunctionCodegen.endVisit(codegen.v, "static initializer", myClass);
}
}
}
@Nullable
protected MethodVisitor createOrGetClInitMethod() {
if (clInitMethod == null) {
clInitMethod = v.newMethod(null, ACC_STATIC, "<clinit>", "()V", null, null);
}
return clInitMethod;
}
@Nullable
protected ExpressionCodegen createOrGetClInitCodegen() {
assert state.getClassBuilderMode() == ClassBuilderMode.FULL;
if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
if (clInitCodegen == null) {
MethodVisitor method = createOrGetClInitMethod();
method.visitCode();
SimpleFunctionDescriptorImpl clInit =
new SimpleFunctionDescriptorImpl(descriptor, Collections.<AnnotationDescriptor>emptyList(),
Name.special("<clinit>"),
CallableMemberDescriptor.Kind.SYNTHESIZED);
clInit.initialize(null, null, Collections.<TypeParameterDescriptor>emptyList(),
Collections.<ValueParameterDescriptor>emptyList(), null, null, Visibilities.PRIVATE, false);
clInitCodegen = new ExpressionCodegen(method, new FrameMap(), Type.VOID_TYPE, context.intoFunction(clInit), state);
}
}
return clInitCodegen;
}
private void generateRemoveInIterator() {
// generates stub 'remove' function for subclasses of Iterator to be compatible with java.util.Iterator
if (DescriptorUtils.isIteratorWithoutRemoveImpl(descriptor)) {
MethodVisitor mv = v.getVisitor().visitMethod(ACC_PUBLIC, "remove", "()V", null, null);
genMethodThrow(mv, "java/lang/UnsupportedOperationException", "Mutating method called on a Kotlin Iterator");
}
}
}
| 40.502488 | 135 | 0.664906 |
5b9e6819008787472ef77c94e52397dfa58a0b52 | 309 | package com.showka.web.u01;
import com.showka.system.annotation.ShiftJis;
import com.showka.web.FormBase;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public class U01G001Form extends FormBase {
@ShiftJis
private String kokyakuName;
private String bushoName;
}
| 16.263158 | 45 | 0.809061 |
a63a959a6326de2d5baded5c5d06693d75fc5afe | 1,193 | package test;
import gudusoft.gsqlparser.EDbVendor;
import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.TSourceToken;
import junit.framework.TestCase;
public class testToken extends TestCase {
public void testPosinList(){
TGSqlParser sqlparser = new TGSqlParser(EDbVendor.dbvoracle);
sqlparser.sqltext = "select f from t\n" +
"where f>1\n";
assertTrue(sqlparser.parse() == 0);
for (int i=0;i<sqlparser.sourcetokenlist.size();i++){
assertTrue(i == sqlparser.sourcetokenlist.get(i).posinlist);
}
}
public void testOffset(){
TGSqlParser sqlparser = new TGSqlParser(EDbVendor.dbvoracle);
sqlparser.sqltext = "select f from t\n" +
"where f>1\n";
assertTrue(sqlparser.parse() == 0);
for (int i=0;i<sqlparser.sourcetokenlist.size();i++){
TSourceToken st = sqlparser.sourcetokenlist.get(i);
String textFromOffset = sqlparser.sqltext.toString().substring((int)st.offset,(int)st.offset+st.toString().length());
assertTrue(st.toString().equalsIgnoreCase(textFromOffset));
}
}
} | 37.28125 | 130 | 0.633697 |
bbb2db796aeff3dd663f41369d36edb867bb057a | 1,251 | package org.javacord.api.event.channel;
import org.javacord.api.entity.channel.PrivateChannel;
import org.javacord.api.entity.channel.ServerTextChannel;
import org.javacord.api.entity.channel.ServerThreadChannel;
import org.javacord.api.entity.channel.TextChannel;
import java.util.Optional;
/**
* A text channel event.
*/
public interface TextChannelEvent extends ChannelEvent {
@Override
TextChannel getChannel();
/**
* Gets the channel of the event as a server text channel.
*
* @return The channel of the event as a server text channel.
*/
default Optional<ServerTextChannel> getServerTextChannel() {
return getChannel().asServerTextChannel();
}
/**
* Gets the channel of the event as a server thread channel.
*
* @return The channel of the event as a server thread channel.
*/
default Optional<ServerThreadChannel> getServerThreadChannel() {
return getChannel().asServerThreadChannel();
}
/**
* Gets the channel of the event as a private channel.
*
* @return The channel of the event as a private channel.
*/
default Optional<PrivateChannel> getPrivateChannel() {
return getChannel().asPrivateChannel();
}
}
| 27.195652 | 68 | 0.695444 |
ffadb2760cf27f75c8746f14747c8f18c01a1bbb | 773 | package water.compiler.parser;
import water.compiler.lexer.Token;
import water.compiler.lexer.TokenType;
/**
* Represents an error produced by the parser whilst processing tokens.
*/
public class UnexpectedTokenException extends Exception {
private final Token token;
private final String message;
public UnexpectedTokenException(Token token, String message) {
super(message);
this.token = token;
this.message = message;
}
public String getErrorMessage(String filename) {
if(token.getType() == TokenType.EOF) return "[%s:%s:%s] Unexpected EOF: %s".formatted(filename, token.getLine(), token.getColumn(), message);
return "[%s:%s:%s] Unexpected token @ '%s': %s".formatted(filename, token.getLine(), token.getColumn(), token.getValue(), message);
}
}
| 30.92 | 143 | 0.737387 |
df7f9ff028ec34ed8864e7e9ded8af64758fcaef | 2,541 | package edu.utd.minecraft.mod.polycraft.entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntitySnowball;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import edu.utd.minecraft.mod.polycraft.PolycraftMod;
import edu.utd.minecraft.mod.polycraft.item.ItemFreezeRay;
import edu.utd.minecraft.mod.polycraft.privateproperty.Enforcer;
import edu.utd.minecraft.mod.polycraft.privateproperty.PrivateProperty;
public class EntityFreezeRayProjectile extends EntitySnowball {
private final ItemFreezeRay freezeRayItem;
public EntityFreezeRayProjectile(final ItemFreezeRay freezeRayItem, World p_i1774_1_, EntityLivingBase p_i1774_2_) {
super(p_i1774_1_, p_i1774_2_);
this.freezeRayItem = freezeRayItem;
this.motionX *= (double) freezeRayItem.velocity / 10d;
this.motionY *= (double) freezeRayItem.velocity / 10d;
this.motionZ *= (double) freezeRayItem.velocity / 10d;
}
@Override
protected void onImpact(MovingObjectPosition p_70184_1_)
{
if (Enforcer.getInstance(worldObj).possiblyKillProjectile((EntityPlayer) getThrower(), this, p_70184_1_, PrivateProperty.PermissionSet.Action.UseFreezeRay))
return;
if (!worldObj.isRemote) {
if (p_70184_1_.entityHit != null)
{
if (p_70184_1_.entityHit instanceof EntityFlameThrowerProjectile) {
p_70184_1_.entityHit.setDead();
}
else {
p_70184_1_.entityHit.attackEntityFrom(DamageSource.generic, freezeRayItem.damage);
if (p_70184_1_.entityHit.isBurning()) {
p_70184_1_.entityHit.extinguish();
}
}
//FIXME eventually figure out how to "freeze" a player
}
if (p_70184_1_.entityHit == null) {
final Vec3 blockCoords = PolycraftMod.getAdjacentCoordsSideHit(p_70184_1_);
BlockPos blockPos = new BlockPos(blockCoords);
if (worldObj.getBlockState(blockPos).getBlock() == Blocks.water)
{
worldObj.setBlockState(blockPos, Blocks.ice.getDefaultState());
}
else if ((worldObj.isAirBlock(blockPos)
|| worldObj.getBlockState(blockPos).getBlock() == PolycraftMod.blockLight)
&& Blocks.snow_layer.canPlaceBlockAt(worldObj, blockPos))
{
worldObj.setBlockState(blockPos, Blocks.snow_layer.getDefaultState());
}
}
this.setDead();
}
}
} | 35.788732 | 159 | 0.744982 |
7e6d31f41313758ca9229ac9874018c25b61319c | 1,905 | package com.github.dynamicextensionsalfresco.gradle.configuration;
import com.github.dynamicextensionsalfresco.gradle.tasks.DeBundleTaskConvention;
import com.github.dynamicextensionsalfresco.gradle.tasks.InstallBundle;
import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.bundling.Jar;
import org.gradle.util.GUtil;
/**
* @author Laurent Van der Linden
*/
public class BaseConfig {
private final Project project;
private final Repository repository;
private final Versions versions;
public BaseConfig(Project project) {
this.project = project;
repository = project.getObjects().newInstance(Repository.class);
versions = project.getObjects().newInstance(Versions.class);
}
public Repository getRepository() {
return repository;
}
public Versions getVersions() {
return versions;
}
public void repository(Action<? super Repository> action) {
action.execute(repository);
}
public void versions(Action<? super Versions> action) {
action.execute(versions);
}
private static String createInstallNameFromJarName(String jarName) {
return "install"+ GUtil.toCamelCase(jarName.replaceAll("[Jj]ar$", ""))+"Bundle";
}
public void configureBundle(Jar jar) {
DeBundleTaskConvention.apply(jar);
project.getTasks().create(createInstallNameFromJarName(jar.getName()), InstallBundle.class,
installBundle -> installBundle.getFiles().from(jar));
}
public void configureBundle(TaskProvider<Jar> jarProvider) {
jarProvider.configure(DeBundleTaskConvention::apply);
project.getTasks().create(createInstallNameFromJarName(jarProvider.getName()), InstallBundle.class,
installBundle -> installBundle.getFiles().from(jarProvider));
}
}
| 32.844828 | 107 | 0.71706 |
31279a487b8c442098b92b3d5269ac16038eb42f | 3,952 | /*
* Copyright 2021 gparap
*
* 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 gparap.apps.blog;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import gparap.apps.blog.adapter.BlogPostAdapter;
import gparap.apps.blog.auth.LoginActivity;
import gparap.apps.blog.ui.post.AddBlogPostActivity;
import gparap.apps.blog.ui.settings.UserSettingsActivity;
import gparap.apps.blog.utils.FirebaseUtils;
@SuppressWarnings({"Convert2Lambda", "FieldCanBeLocal"})
@SuppressLint("NonConstantResourceId")
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private BlogPostAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//add a new blog post
FloatingActionButton fabAddPost = findViewById(R.id.fab_addPost);
fabAddPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, AddBlogPostActivity.class));
}
});
//create and configure adapter for blog posts
adapter = new BlogPostAdapter(FirebaseUtils.getInstance().createFirebaseRecyclerOptions());
adapter.setContext(MainActivity.this);
//setup recyclerView with adapter
recyclerView = findViewById(R.id.recyclerViewBlogPosts);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
@Override
protected void onDestroy() {
super.onDestroy();
FirebaseUtils.getInstance().deleteAnonymousUser();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_add_post:
startActivity(new Intent(MainActivity.this, AddBlogPostActivity.class));
break;
case R.id.menu_item_user_settings:
startActivity(new Intent(MainActivity.this, UserSettingsActivity.class));
break;
case R.id.menu_item_log_out:
signOutUserAndReturnToLoginActivity();
break;
}
return super.onOptionsItemSelected(item);
}
private void signOutUserAndReturnToLoginActivity() {
FirebaseUtils.getInstance().deleteAnonymousUser();
FirebaseUtils.getInstance().signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
} | 34.365217 | 99 | 0.705972 |
83f4565343d80cf9b4d15d2fb6b0c88dfbfe9c2b | 507 | package com.jeffmony.demo.softfilter;
import com.jeffmony.livesdk.filter.softvideofilter.BaseSoftVideoFilter;
/**
* Created by jeffmony.
*/
public class GrayFilterSoft extends BaseSoftVideoFilter {
@Override
public boolean onFrame(byte[] orignBuff, byte[] targetBuff, long presentationTimeMs, int sequenceNum) {
System.arraycopy(orignBuff,0,targetBuff,0,SIZE_Y);
for (int i = SIZE_Y; i < SIZE_TOTAL; i++) {
targetBuff[i] = 127;
}
return true;
}
}
| 28.166667 | 107 | 0.682446 |
a73f3e048e9ffa25b82241192c66fa1184c07d5d | 2,718 | package com.box.l10n.mojito.service.branch.notification.phabricator;
import com.box.l10n.mojito.service.branch.BranchUrlBuilder;
import com.box.l10n.mojito.utils.ServerConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
BranchNotificationMessageBuilderPhabricator.class,
BranchNotificationCustomMessageWithFormatPhabricatorTest.class,
BranchUrlBuilder.class,
ServerConfig.class},
properties = {
"l10n.branchNotification.phabricator.notification.message.new.format={message}",
"l10n.branchNotification.phabricator.notification.message.updated.format={message} {link}",
"l10n.branchNotification.phabricator.notification.message.new=Custom message text for new messages stating the time that screenshots need to be uploaded ",
"l10n.branchNotification.phabricator.notification.message.updated=Test custom message for update messages stating the screenshot upload deadline ",
"l10n.branchNotification.phabricator.notification.message.noMoreStrings=Test custom message for no more strings ",
"l10n.branchNotification.phabricator.notification.message.translationsReady=Test custom message for translated strings ready",
"l10n.branchNotification.phabricator.notification.message.screenshotsMissing=Test custom message for screenshots missing"})
public class BranchNotificationCustomMessageWithFormatPhabricatorTest {
@Autowired
BranchNotificationMessageBuilderPhabricator branchNotificationMessageBuilderPhabricator;
@Test
public void getCustomNewMessageWithFormat() {
String newMessage = branchNotificationMessageBuilderPhabricator.getNewMessage("branchTest", Arrays.asList("string1", "string2"));
assertEquals("Custom message text for new messages stating the time that screenshots need to be uploaded ", newMessage);
}
@Test
public void getCustomUpdatedMessageWithFormat() {
String updatedMessage = branchNotificationMessageBuilderPhabricator.getUpdatedMessage("branchTest", Arrays.asList("string1", "string2"));
assertEquals("Test custom message for update messages stating the screenshot upload deadline " +
" [→ Go to Mojito](http://localhost:8080/branches?searchText=branchTest&deleted=false&onlyMyBranches=false)"
, updatedMessage);
}
}
| 55.469388 | 171 | 0.768212 |
845acd468b97b1537e988f62b797508afe8140c2 | 108 | package edu.illinois.cs.cs125.answerable.classdesignanalysis.fixtures.names.reference;
public class Foo {}
| 27 | 86 | 0.833333 |
d0d53e6f19b8696d3c7ed7986fdd3b681d872553 | 4,289 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
package com.sun.star.comp.helper;
import com.sun.star.uno.XComponentContext;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.comp.helper.ComponentContext;
import com.sun.star.comp.helper.ComponentContextEntry;
import com.sun.star.uno.UnoRuntime;
import java.util.Hashtable;
public class ComponentContext_Test {
public static void main(String args[]) {
try {
Hashtable table = new Hashtable();
table.put( "bla1", new ComponentContextEntry( null, new Integer( 1 ) ) );
XComponentContext xInitialContext = Bootstrap.createInitialComponentContext( table );
table = new Hashtable();
table.put( "bla2", new ComponentContextEntry( new Integer( 2 ) ) );
table.put( "bla3", new Integer( 3 ) );
XComponentContext xContext = new ComponentContext( table, xInitialContext );
XMultiComponentFactory xSMgr = xContext.getServiceManager();
Object o = xSMgr.createInstanceWithContext( "com.sun.star.loader.Java", xContext );
if (o == null)
System.err.println( "### failed raising service: 1!" );
o = xSMgr.createInstanceWithContext( "com.sun.star.bridge.BridgeFactory", xContext );
if (o == null)
System.err.println( "### failed raising service: 2!" );
o = xSMgr.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", xContext );
if (o == null)
System.err.println( "### failed raising service: 3!" );
o = xSMgr.createInstanceWithContext( "com.sun.star.connection.Connector", xContext );
if (o == null)
System.err.println( "### failed raising service: 4!" );
o = xSMgr.createInstanceWithContext( "com.sun.star.connection.Acceptor", xContext );
if (o == null)
System.err.println( "### failed raising service: 5!" );
o = xSMgr.createInstanceWithContext( "com.sun.star.lang.ServiceManager", xContext );
if (o == null)
System.err.println( "### failed raising service: 6!" );
if (xContext.getValueByName( "bla1" ) == null ||
xContext.getValueByName( "bla2" ) == null ||
xContext.getValueByName( "bla3" ) == null ||
xInitialContext.getValueByName( "bla2" ) != null ||
xInitialContext.getValueByName( "bla3" ) != null)
{
System.err.println( "### bootstrap context test failed: 1!" );
}
if (((Integer)xContext.getValueByName( "bla1" )).intValue() != 1 ||
((Integer)xContext.getValueByName( "bla2" )).intValue() != 2 ||
((Integer)xContext.getValueByName( "bla3" )).intValue() != 3 ||
((Integer)xInitialContext.getValueByName( "bla1" )).intValue() != 1)
{
System.err.println( "### bootstrap context test failed: 2!" );
}
XComponent xComp = UnoRuntime.queryInterface(
XComponent.class, xInitialContext );
xComp.dispose();
}
catch(Exception exception) {
System.err.println("exception occurred:" + exception);
exception.printStackTrace();
}
}
}
| 44.677083 | 98 | 0.599207 |
caa4278730a850f87a37be5494c4cf120d989d39 | 1,757 | package com.provectus.fds.models.bcns;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.provectus.fds.models.utils.JsonUtils;
import lombok.*;
import java.io.IOException;
@Getter
@Builder
@Setter
@NoArgsConstructor
@ToString
@EqualsAndHashCode
public class Bcn implements Partitioned {
@JsonProperty("tx_id")
private String txId;
@JsonProperty("campaign_item_id")
private long campaignItemId;
private String domain;
@JsonProperty("creative_id")
private String creativeId;
@JsonProperty("creative_category")
private String creativeCategory;
@JsonProperty("app_uid")
private String appUID;
@JsonProperty("win_price")
private long winPrice;
private String type;
@JsonCreator
public Bcn(
@JsonProperty("tx_id") String txid,
@JsonProperty("campaign_item_id") long campaignItemId,
@JsonProperty("domain") String domain,
@JsonProperty("creative_id") String creativeId,
@JsonProperty("creative_category") String creativeCategory,
@JsonProperty("app_uid") String appUID,
@JsonProperty("win_price") long winPrice,
@JsonProperty("type") String type) {
this.txId = txid;
this.campaignItemId = campaignItemId;
this.domain = domain;
this.creativeId = creativeId;
this.creativeCategory = creativeCategory;
this.appUID = appUID;
this.winPrice = winPrice;
this.type = type;
}
@Override
public String getPartitionKey() {
return txId;
}
@Override
public byte[] getBytes() throws IOException {
return JsonUtils.write(this);
}
} | 25.838235 | 71 | 0.674445 |
6aee69f8c3eb2c8fd4f83977b713b07b29d87a22 | 1,978 | package com.example.bootstrapdemo.controllers;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class billing {
@Id
private String fname;
private String umail;
private String pname;
private String time;
private String addr;
private int zip;
private int cno;
private String cname;
private String edate;
private int cvv;
private String item;
private int total;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getUmail() {
return umail;
}
public void setUmail(String umail) {
this.umail = umail;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public int getCno() {
return cno;
}
public void setCno(int cno) {
this.cno = cno;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public int getCvv() {
return cvv;
}
public void setCvv(int cvv) {
this.cvv = cvv;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
@Override
public String toString() {
return "billing [fname=" + fname + ", umail=" + umail + ", pname=" + pname + ", time=" + time + ", addr=" + addr
+ ", zip=" + zip + ", cno=" + cno + ", cname=" + cname + ", edate=" + edate + ", cvv=" + cvv + ", item="
+ item + ", total=" + total + "]";
}
}
| 18.146789 | 114 | 0.640546 |
d1a7f556730b8866d4de38cae03ce14589b6ad03 | 3,673 | package br.health.workflow.core.communication;
import br.health.workflow.core.communication.config.RestTemplateConfig;
import br.health.workflow.controller.dto.EndpointDTO;
import br.health.workflow.controller.dto.MicroserviceDTO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.List;
import java.util.Set;
@Log4j2
@Component
public class SyncCommunication {
@Autowired
private RestTemplate rest;
public ResponseEntity restRequest(RestTemplateConfig attributes) {
log.info("RestTemplate attributes: {}", attributes);
HttpEntity<?> entityReq = new HttpEntity<>(attributes.getBody(), attributes.getHttpHeaders());
StringBuilder url = new StringBuilder();
if (attributes.getQueryParams() != null) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(attributes.getApiHost() + attributes.getPath()).queryParams(attributes.getQueryParams());
url.append(builder.build().toString());
} else {
url.append(attributes.getApiHost());
url.append(attributes.getPath());
}
if (attributes.getPathVariables() != null) {
Set<String> keys = attributes.getPathVariables().keySet();
for (String key: keys)
url.replace(url.indexOf(key), url.indexOf(key) + key.length(), attributes.getPathVariables().get(key));
}
ResponseEntity<?> response;
try {
if (attributes.getPageable()) {
response = rest.exchange(
url.toString(),
attributes.getHttpMethod(),
entityReq,
String.class
);
} else if (attributes.getSingleReturn()) {
response = rest.exchange(
url.toString(),
attributes.getHttpMethod(),
entityReq,
new ParameterizedTypeReference<String>() {}
);
} else {
response = rest.exchange(
url.toString(),
attributes.getHttpMethod(),
entityReq,
new ParameterizedTypeReference<List<?>>() {}
);
}
} catch (HttpClientErrorException exception) {
response = new ResponseEntity<>(exception.getResponseBodyAsString(), exception.getStatusCode());
}
log.info("Request response: {}", response);
return response;
}
public RestTemplateConfig getMicroserviceClientConfig(MicroserviceDTO microservice, String endpoint, String authorization, Object data) {
RestTemplateConfig restTemplateConfig = null;
if(microservice!=null) {
for (EndpointDTO e : microservice.getEndpoints()) {
if (e.getReference().equals(endpoint)) {
HttpMethod httpMethod = getMethodByName(e.getMethod());
if (httpMethod == null)
throw new RuntimeException("Invalid HTTP Method.");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add("Authorization", "Bearer "+ authorization);
restTemplateConfig = new RestTemplateConfig(
headers,
data,
microservice.getProtocol()+"://"+microservice.getHost(),
e.getResource(),
httpMethod,
Boolean.TRUE
);
}
}
}
return restTemplateConfig;
}
private HttpMethod getMethodByName(String name) {
switch (name.toUpperCase()) {
case "POST":
return HttpMethod.POST;
case "GET":
return HttpMethod.GET;
case "DELETE":
return HttpMethod.DELETE;
case "PUT":
return HttpMethod.PUT;
case "PATCH":
return HttpMethod.PATCH;
}
return null;
}
}
| 30.608333 | 156 | 0.719303 |
38b44fddc7eaf5819e8043c7649ada25edc5b3ff | 1,750 | package com.baeldung.properties.yamlmap.pojo;
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import com.baeldung.properties.yamlmap.factory.YamlPropertySourceFactory;
@Component
@PropertySource(value = "classpath:server.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "server")
public class ServerProperties {
private Map<String, String> application;
private Map<String, List<String>> config;
private Map<String, Credential> users;
public Map<String, String> getApplication() {
return application;
}
public void setApplication(Map<String, String> application) {
this.application = application;
}
public Map<String, List<String>> getConfig() {
return config;
}
public void setConfig(Map<String, List<String>> config) {
this.config = config;
}
public Map<String, Credential> getUsers() {
return users;
}
public void setUsers(Map<String, Credential> users) {
this.users = users;
}
public static class Credential {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
} | 26.515152 | 91 | 0.648 |
4acf2a6ae95ab2d5add6575cd8a5b118475c04bc | 3,313 | import com.google.gson.Gson;
import dto.AuthRequestDTO;
import dto.ErrorDTO;
import okhttp3.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
public class OkHttpLoginTest {
Gson gson = new Gson();
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
@Test
public void loginTestPositive() throws IOException {
AuthRequestDTO requestDTO = AuthRequestDTO.builder()
.email("[email protected]")
.password("Pinhas123$").build();
RequestBody requestBody = RequestBody.create(gson.toJson(requestDTO), JSON);
Request request = new Request.Builder()
.url("https://contacts-telran.herokuapp.com/api/login")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
String responseJson = response.body().string();
// System.out.println("responseJson: "+responseJson);
Assert.assertTrue(response.isSuccessful());
}
@Test
public void loginTestNegativeWrongEmail() throws IOException {
AuthRequestDTO requestDTO = AuthRequestDTO.builder()
.email("pinhasgmail.com")
.password("Pinhas123$").build();
RequestBody requestBody = RequestBody.create(gson.toJson(requestDTO), JSON);
Request request = new Request.Builder()
.url("https://contacts-telran.herokuapp.com/api/login")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
ErrorDTO errorDTO = gson.fromJson(response.body().string(), ErrorDTO.class);
Assert.assertEquals(errorDTO.getCode(), 400);
// Assert.assertFalse(response.isSuccessful());
}
@Test
public void loginTestNegativeWrongPassword() throws IOException {
AuthRequestDTO requestDTO = AuthRequestDTO.builder()
.email("[email protected]")
.password("pinhas123$").build();
RequestBody requestBody = RequestBody.create(gson.toJson(requestDTO), JSON);
Request request = new Request.Builder()
.url("https://contacts-telran.herokuapp.com/api/login")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
ErrorDTO errorDTO = gson.fromJson(response.body().string(), ErrorDTO.class);
Assert.assertEquals(errorDTO.getCode(), 400);
}
@Test
public void loginTestNegativeUnregisteredUser() throws IOException {
AuthRequestDTO requestDTO = AuthRequestDTO.builder()
.email("[email protected]")
.password("Papap123$").build();
RequestBody requestBody = RequestBody.create(gson.toJson(requestDTO), JSON);
Request request = new Request.Builder()
.url("https://contacts-telran.herokuapp.com/api/login")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
ErrorDTO errorDTO = gson.fromJson(response.body().string(), ErrorDTO.class);
Assert.assertEquals(errorDTO.getCode(), 401);
}
}
| 32.480392 | 90 | 0.632961 |
55a4a41e073631c1ee0ada98ac3b397c699f8266 | 717 | package website.magyar.adoration.web.service;
import website.magyar.adoration.database.tables.Person;
import website.magyar.adoration.database.tables.Social;
/**
* Google type of AuthenticatedUser.
*/
public class GoogleUser extends AuthenticatedUser {
/**
* Creates a Google User login class.
*
* @param social is the associated Social login record.
* @param person is the associated Person record (real life person) if exists
* @param sessionTimeoutInSec determines the validity of he session
*/
public GoogleUser(Social social, Person person, Integer sessionTimeoutInSec) {
super("Google", social, person, sessionTimeoutInSec);
}
}
| 31.173913 | 94 | 0.702929 |
951815a1d4583dac3dda1ec33594be23f8281668 | 416 | package ua.footballdata.repositories;
import java.util.List;
import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.springframework.data.repository.CrudRepository;
import ua.footballdata.model.entity.TeamEntity;
//@Repository
@EnableScan
public interface TeamEntityRepository extends CrudRepository<TeamEntity, Long> {
TeamEntity findByName(String name);
List<TeamEntity> findAll();
}
| 24.470588 | 80 | 0.826923 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.