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
|
---|---|---|---|---|---|
862866e527ac7241a0723947487c470858801ada | 4,889 | package com.walmartlabs.concord.server.cfg;
/*-
* *****
* Concord
* -----
* Copyright (C) 2017 - 2018 Walmart 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.
* =====
*/
import com.walmartlabs.ollie.config.Config;
import org.eclipse.sisu.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.Serializable;
import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Named
@Singleton
public class LdapConfiguration implements Serializable {
@Inject
@Config("ldap.url")
private String url;
@Inject
@Config("ldap.searchBase")
private String searchBase;
@Inject
@Config("ldap.principalSearchFilter")
private String principalSearchFilter;
@Inject
@Config("ldap.groupSearchFilter")
private String groupSearchFilter;
@Inject
@Config("ldap.groupNameProperty")
private String groupNameProperty;
@Inject
@Config("ldap.groupDisplayNameProperty")
private String groupDisplayNameProperty;
@Inject
@Config("ldap.systemUsername")
private String systemUsername;
@Inject
@Config("ldap.systemPassword")
@Nullable
private String systemPassword;
@Inject
@Config("ldap.userPrincipalNameProperty")
private String userPrincipalNameProperty;
@Inject
@Config("ldap.usernameProperty")
private String usernameProperty;
@Inject
@Config("ldap.mailProperty")
private String mailProperty;
@Inject
@Config("ldap.autoCreateUsers")
private boolean autoCreateUsers;
@Inject
@Nullable
@Config("ldap.returningAttributes")
private List<String> returningAttributes;
@Inject
@Nullable
@Config("ldap.cacheDuration")
private Duration cacheDuration;
@Inject
@Config("ldap.connectTimeout")
private Duration connectTimeout;
@Inject
@Config("ldap.readTimeout")
private Duration readTimeout;
private final Set<String> exposeAttributes;
private final Set<String> excludeAttributes;
@Inject
public LdapConfiguration(@Config("ldap.exposeAttributes") @Nullable String exposeAttributes,
@Config("ldap.excludeAttributes") @Nullable String excludeAttributes) {
this.exposeAttributes = split(exposeAttributes);
this.excludeAttributes = split(excludeAttributes);
}
public String getUrl() {
return url;
}
public String getSearchBase() {
return searchBase;
}
public String getPrincipalSearchFilter() {
return principalSearchFilter;
}
public String getGroupSearchFilter() {
return groupSearchFilter;
}
public String getGroupNameProperty() {
return groupNameProperty;
}
public String getGroupDisplayNameProperty() {
return groupDisplayNameProperty;
}
public String getSystemUsername() {
return systemUsername;
}
public String getSystemPassword() {
return systemPassword;
}
public String getUserPrincipalNameProperty() {
return userPrincipalNameProperty;
}
public String getUsernameProperty() {
return usernameProperty;
}
public String getMailProperty() {
return mailProperty;
}
public Set<String> getExposeAttributes() {
return exposeAttributes;
}
public Set<String> getExcludeAttributes() {
return excludeAttributes;
}
public List<String> getReturningAttributes() {
return returningAttributes;
}
public boolean isAutoCreateUsers() {
return autoCreateUsers;
}
public Duration getCacheDuration() {
return cacheDuration;
}
public Duration getConnectTimeout() {
return connectTimeout;
}
public Duration getReadTimeout() {
return readTimeout;
}
private static Set<String> split(String s) {
if (s == null || s.isEmpty()) {
return Collections.emptySet();
}
s = s.trim();
if (s.isEmpty()) {
return Collections.emptySet();
}
String[] as = s.split(",", -1);
Set<String> result = new HashSet<>(as.length);
Collections.addAll(result, s.split(",", -1));
return Collections.unmodifiableSet(result);
}
} | 23.618357 | 100 | 0.672326 |
1cafb455c5690016796ee107486540fe83500104 | 7,810 | package com.sensorup.iot.utility;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class STAHttpClient {
private static final Logger logger = LoggerFactory
.getLogger(STAHttpClient.class);
public static STAHttpClient STAHttpClient;
AsyncHttpClient client = null;
public static STAHttpClient getInstance(){
if(STAHttpClient == null) {
STAHttpClient = new STAHttpClient();
STAHttpClient.client = new DefaultAsyncHttpClient();
}
return STAHttpClient;
}
public Map<String,Object> doPost(String postBody, String postURL){
try {
String encoded = null;
if(PropertyReader.getInstance().getProperty("sta-username") != null &&
PropertyReader.getInstance().getProperty("sta-password") != null) {
encoded = Base64.encode((PropertyReader.getInstance().getProperty("sta-username") + ":" +
PropertyReader.getInstance().getProperty("sta-password")).getBytes());
}
byte[] postData = postBody.getBytes("UTF8");
Response response = null;
if(encoded == null) {
response = client.preparePost(postURL)
.addHeader("Content-Type", "application/json")
.setBody(postData)
.execute().get();
} else {
response = client.preparePost(postURL)
.addHeader("Content-Type", "application/json")
.setBody(postData)
.addHeader("Authorization", "Basic " + encoded)
.execute().get();
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("response-code",response.getStatusCode());
if(response.getStatusCode()==201) {
result.put("response", response.getHeader("location"));
} else {
logger.error("An error occurred for posting entity to: " +postURL+" ! The request returned with status code: "+ response.getStatusCode());
result.put("response", "");
}
return result;
} catch (Exception e) {
e.printStackTrace();
logger.error("An exception occurred for posting entity: "+e.getMessage());
return null;
}
}
public Map<String,Object> doGet(String getURL){
return doGet(getURL, false);
}
public Map<String,Object> doGet(String getURL, boolean isConfigurationServer){
try {
String url = getURL;
String encoded = null;
Response response;
if(encoded == null){
response = client.prepareGet(url).execute().get();
} else{
response = client.prepareGet(url).addHeader("Authorization", "Basic " + encoded).execute().get();
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("response-code",response.getStatusCode());
if(response.getStatusCode()==200) {
String responseBody = response.getResponseBody(StandardCharsets.UTF_8);
result.put("response",responseBody);
} else {
logger.error("An error occured when GETting '"+ url +"'! The request returned with status code: "+ response.getStatusCode());
result.put("response", "");
}
return result;
} catch (Exception e) {
e.printStackTrace();
logger.error("An exception occurred during GETting Observation from STA: "+e.getMessage());
return null;
}
}
public Map<String,Object> doPut(String putBody, String putURL){
try {
String encoded = null;
if(PropertyReader.getInstance().getProperty("sta-username") != null &&
PropertyReader.getInstance().getProperty("sta-password") != null) {
encoded = Base64.encode((PropertyReader.getInstance().getProperty("sta-username") + ":" +
PropertyReader.getInstance().getProperty("sta-password")).getBytes());
}
byte[] postData = putBody.getBytes("UTF8");
Response response = null;
if(encoded == null) {
response = client.preparePut(putURL)
.addHeader("Content-Type", "application/json")
.setBody(postData)
.execute().get();
} else {
response = client.preparePut(putURL)
.addHeader("Content-Type", "application/json")
.setBody(postData)
.addHeader("Authorization", "Basic " + encoded)
.execute().get();
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("response-code",response.getStatusCode());
if(response.getStatusCode()==200) {
result.put("response", response.getHeader("location"));
} else {
logger.error("An error occurred for putting entity to: " +putURL+" ! The request returned with status code: "+ response.getStatusCode());
result.put("response", "");
}
return result;
} catch (Exception e) {
e.printStackTrace();
logger.error("An exception occurred for putting entity: "+e.getMessage());
return null;
}
}
public Map<String,Object> doPatch(String patchBody, String patchURL){
try {
String encoded = null;
if(PropertyReader.getInstance().getProperty("sta-username") != null &&
PropertyReader.getInstance().getProperty("sta-password") != null) {
encoded = Base64.encode((PropertyReader.getInstance().getProperty("sta-username") + ":" +
PropertyReader.getInstance().getProperty("sta-password")).getBytes());
}
byte[] postData = patchBody.getBytes("UTF8");
Response response = null;
if(encoded == null) {
response = client.preparePatch(patchURL)
.addHeader("Content-Type", "application/json")
.setBody(postData)
.execute().get();
} else {
response = client.preparePatch(patchURL)
.addHeader("Content-Type", "application/json")
.setBody(postData)
.addHeader("Authorization", "Basic " + encoded)
.execute().get();
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("response-code",response.getStatusCode());
if(response.getStatusCode()==200) {
result.put("response", response.getHeader("location"));
} else {
logger.error("An error occurred for patching entity to: " +patchURL+" ! The request returned with status code: "+ response.getStatusCode());
result.put("response", "");
}
return result;
} catch (Exception e) {
e.printStackTrace();
logger.error("An exception occurred for patching entity: "+e.getMessage());
return null;
}
}
}
| 41.542553 | 156 | 0.548912 |
7cb569de9b8e774a8551505cba505be0dccc8623 | 373 | package com.zqf.spring.security.oauth2.server.service;
import com.zqf.spring.security.oauth2.server.entity.TbUser;
/**
* Created with IntelliJ IDEA.
* Author: Bill Chiu(Qifan Zhao)
* Date: Created in : 2019/11/5 13:42
* Description:
*
* @ Modified By:
*/
public interface TbUserService {
//防止sql注入 先拿到用户名 在拿密码
TbUser getByUserName(String username);
}
| 21.941176 | 59 | 0.710456 |
a8a3c562c98f0fc257f1370aa5d312da02d2cd4d | 2,048 | /*******************************************************************************
* Copyright (C) 2017-2019 Kat Fung Tjew
*
* 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.nova.sqldb;
public class SqlServerConfiguration
{
public SqlServerConfiguration(String host,int port,String database,int poolSize,long connectionKeepAliveMs,long maximumLeastRecentlyUsedCount)
{
this.host=host;
this.port=port;
this.database=database;
this.poolSize=poolSize;
this.connectionKeepAliveMs=connectionKeepAliveMs;
this.maximumLeastRecentlyUsedCount=maximumLeastRecentlyUsedCount;
}
public SqlServerConfiguration(String host,String database)
{
this(host,1433,database,10,10000,1000000);
}
public boolean connectImmediately=true;
public String host;
public String database;
public int port=1433;
public int poolSize=10;
public long connectionKeepAliveMs=10000;
public long maximumLeastRecentlyUsedCount=1000000;
}
| 42.666667 | 143 | 0.723633 |
ed071286eba22c4e21ba05667b334097e0319aed | 849 | /*
* Copyright Lars Michaelis and Stephan Zerhusen 2016.
* Distributed under the MIT License.
* (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT)
*/
package de.larmic.butterfaces.component.html.table.export.iterator;
import java.util.Iterator;
import java.util.List;
/**
* Extends an iterator and prepares header and rows for csv export.
*
* @author Lars Michaelis
*/
public interface TableExportWriterIterator<T> extends Iterator<T> {
/**
* @return the number of rows (except header).
*/
int getRowCount();
/**
* Prepares next row information. Sort order have to match header sort order.
*
* @return a list of strings of actual selected row.
*/
List<String> nextRow();
/**
* @return a sorted header list.
*/
List<String> getHeader();
}
| 24.257143 | 87 | 0.674912 |
f75ccd2a0ba8b23d13febec6d5ee730cb9e1e64f | 15,995 | /**
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.stage.origin.multikafka;
import com.google.common.base.Throwables;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.lineage.LineageEvent;
import com.streamsets.pipeline.api.lineage.LineageEventType;
import com.streamsets.pipeline.api.lineage.LineageSpecificAttribute;
import com.streamsets.pipeline.config.DataFormat;
import com.streamsets.pipeline.lib.kafka.KafkaErrors;
import com.streamsets.pipeline.sdk.PushSourceRunner;
import com.streamsets.pipeline.sdk.StageRunner;
import com.streamsets.pipeline.stage.origin.multikafka.loader.KafkaConsumerLoader;
import com.streamsets.pipeline.stage.origin.multikafka.loader.MockKafkaConsumerLoader;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
public class TestMultiKafkaSource {
@Before
public void setUp() throws IOException, InterruptedException {
MockitoAnnotations.initMocks(this);
KafkaConsumerLoader.isTest = true;
}
@After
public void tearDown() {
KafkaConsumerLoader.isTest = false;
}
private MultiKafkaBeanConfig getConfig() {
MultiKafkaBeanConfig conf = new MultiKafkaBeanConfig();
conf.consumerGroup = "sdc";
conf.maxBatchSize = 9;
conf.batchWaitTime = 5000;
conf.produceSingleRecordPerMessage = false;
conf.kafkaOptions = new HashMap<>();
conf.brokerURI = "127.0.0.1:1234";
conf.dataFormat = DataFormat.TEXT;
conf.dataFormatConfig.charset = "UTF-8";
conf.dataFormatConfig.removeCtrlChars = false;
conf.dataFormatConfig.textMaxLineLen = 4096;
return conf;
}
@Test
public void testProduceStringRecords() throws StageException, InterruptedException {
MultiKafkaBeanConfig conf = getConfig();
conf.topicList = Collections.singletonList("topic");
conf.numberOfThreads = 1;
ConsumerRecords<String, byte[]> consumerRecords = generateConsumerRecords(5, "topic", 0);
ConsumerRecords<String, byte[]> emptyRecords = generateConsumerRecords(0, "topic", 0);
KafkaConsumer mockConsumer = Mockito.mock(KafkaConsumer.class);
List<KafkaConsumer> consumerList = Collections.singletonList(mockConsumer);
Mockito.when(mockConsumer.poll(conf.batchWaitTime)).thenReturn(consumerRecords).thenReturn(emptyRecords);
MockKafkaConsumerLoader.consumers = consumerList.iterator();
MultiKafkaSource source = new MultiKafkaSource(conf);
PushSourceRunner sourceRunner = new PushSourceRunner.Builder(MultiKafkaDSource.class, source)
.addOutputLane("lane")
.build();
sourceRunner.runInit();
MultiKafkaPushSourceTestCallback callback = new MultiKafkaPushSourceTestCallback(sourceRunner, 1);
try {
sourceRunner.runProduce(new HashMap<>(), 5, callback);
int records = callback.waitForAllBatches();
source.await();
Assert.assertEquals(5, records);
Assert.assertFalse(source.isRunning());
} catch (Exception e) {
Assert.fail(e.getMessage());
throw e;
} finally {
sourceRunner.runDestroy();
}
}
@Test
public void testMultiplePartitions() throws StageException, InterruptedException {
MultiKafkaBeanConfig conf = getConfig();
conf.topicList = Collections.singletonList("topic");
conf.numberOfThreads = 1;
ConsumerRecords<String, byte[]> consumerRecords1 = generateConsumerRecords(5, "topic", 0);
ConsumerRecords<String, byte[]> consumerRecords2 = generateConsumerRecords(5, "topic", 1);
ConsumerRecords<String, byte[]> emptyRecords = generateConsumerRecords(0, "topic", 0);
KafkaConsumer mockConsumer = Mockito.mock(KafkaConsumer.class);
List<KafkaConsumer> consumerList = Collections.singletonList(mockConsumer);
Mockito
.when(mockConsumer.poll(conf.batchWaitTime))
.thenReturn(consumerRecords1)
.thenReturn(consumerRecords2)
.thenReturn(emptyRecords);
MockKafkaConsumerLoader.consumers = consumerList.iterator();
MultiKafkaSource source = new MultiKafkaSource(conf);
PushSourceRunner sourceRunner = new PushSourceRunner.Builder(MultiKafkaDSource.class, source)
.addOutputLane("lane")
.build();
sourceRunner.runInit();
MultiKafkaPushSourceTestCallback callback = new MultiKafkaPushSourceTestCallback(sourceRunner, 2);
try {
sourceRunner.runProduce(new HashMap<>(), 5, callback);
int records = callback.waitForAllBatches();
source.await();
Assert.assertEquals(10, records);
Assert.assertFalse(source.isRunning());
} catch (Exception e) {
Assert.fail(e.getMessage());
throw e;
} finally {
sourceRunner.runDestroy();
}
}
@Test
public void testMultipleTopics() throws StageException, InterruptedException, ExecutionException {
MultiKafkaBeanConfig conf = getConfig();
conf.numberOfThreads = 100;
// SDC-10162. The batch size must be
// greater than the number of records in the topic.
// This is only required for testing, because of the way we mock -
// first call returns the records, second call returns empty.
// previously, the requested batch size was ignored, and all records
// returned by poll were passed into the pipeline as a batch.
conf.maxBatchSize = 1000;
int numTopics = 20;
long totalMessages = 0;
Random rand = new Random();
List<String> topicNames = new ArrayList<>(numTopics);
List<KafkaConsumer> consumerList = new ArrayList<>(numTopics);
for(int i=0; i<numTopics; i++) {
String topic = "topic-" + i;
topicNames.add(topic);
}
for(int i=0; i<conf.numberOfThreads; i++) {
int numMessages = rand.nextInt(40)+1;
totalMessages += numMessages;
ConsumerRecords<String, byte[]> consumerRecords = generateConsumerRecords(numMessages, topicNames.get(rand.nextInt(numTopics)), 0);
ConsumerRecords<String, byte[]> emptyRecords = generateConsumerRecords(0, topicNames.get(rand.nextInt(numTopics)), 0);
KafkaConsumer mockConsumer = Mockito.mock(KafkaConsumer.class);
consumerList.add(mockConsumer);
Mockito.when(mockConsumer.poll(conf.batchWaitTime)).thenReturn(consumerRecords).thenReturn(emptyRecords);
}
conf.topicList = topicNames;
MockKafkaConsumerLoader.consumers = consumerList.iterator();
MultiKafkaSource source = new MultiKafkaSource(conf);
PushSourceRunner sourceRunner = new PushSourceRunner.Builder(MultiKafkaDSource.class, source)
.addOutputLane("lane")
.build();
sourceRunner.runInit();
MultiKafkaPushSourceTestCallback callback = new MultiKafkaPushSourceTestCallback(sourceRunner, conf.numberOfThreads);
try {
sourceRunner.runProduce(new HashMap<>(), 5, callback);
int records = callback.waitForAllBatches();
source.await();
Assert.assertEquals(totalMessages, records);
Assert.assertFalse(source.isRunning());
} finally {
sourceRunner.runDestroy();
}
}
@Test(expected = ExecutionException.class)
public void testPollFail() throws StageException, InterruptedException, ExecutionException {
MultiKafkaBeanConfig conf = getConfig();
conf.topicList = Collections.singletonList("topic");
conf.numberOfThreads = 1;
KafkaConsumer mockConsumer = Mockito.mock(KafkaConsumer.class);
List<KafkaConsumer> consumerList = Collections.singletonList(mockConsumer);
Mockito
.when(mockConsumer.poll(conf.batchWaitTime))
.thenThrow(new IllegalStateException());
MockKafkaConsumerLoader.consumers = consumerList.iterator();
MultiKafkaSource source = new MultiKafkaSource(conf);
PushSourceRunner sourceRunner = new PushSourceRunner.Builder(MultiKafkaDSource.class, source)
.addOutputLane("lane")
.build();
sourceRunner.runInit();
MultiKafkaPushSourceTestCallback callback = new MultiKafkaPushSourceTestCallback(sourceRunner, conf.numberOfThreads);
sourceRunner.runProduce(new HashMap<>(), 5, callback);
//IllegalStateException in source's threads cause a StageException
//StageException is caught by source's executor service and packaged into ExecutionException
//ExecutionException is unpacked by source and thrown as StageException
//sourceRunner sees this and throws as RuntimeException
//sourceRunner's executor service then packages as ExecutionException
try {
sourceRunner.waitOnProduce();
} catch (ExecutionException e) {
Throwable except = e.getCause().getCause();
Assert.assertEquals(StageException.class, except.getClass());
Assert.assertEquals(KafkaErrors.KAFKA_29, ((StageException) except).getErrorCode());
throw e;
} finally {
sourceRunner.runDestroy();
}
Assert.fail();
}
// If the main thread gets interrupted, then the origin (rightfully so) won't wait on all the
// other threads that might be running. Which will subsequently intefere with other tests.
// @Test(expected = InterruptedException.class)
public void testInterrupt() throws StageException, InterruptedException, ExecutionException {
MultiKafkaBeanConfig conf = getConfig();
conf.numberOfThreads = 10;
int numTopics = conf.numberOfThreads;
List<String> topicNames = new ArrayList<>(numTopics);
List<KafkaConsumer> consumerList = new ArrayList<>(numTopics);
for(int i=0; i<numTopics; i++) {
String topic = "topic-" + i;
topicNames.add(topic);
ConsumerRecords<String, byte[]> consumerRecords = generateConsumerRecords(5, topic, 0);
ConsumerRecords<String, byte[]> emptyRecords = generateConsumerRecords(0, topic, 0);
KafkaConsumer mockConsumer = Mockito.mock(KafkaConsumer.class);
consumerList.add(mockConsumer);
Mockito.when(mockConsumer.poll(conf.batchWaitTime)).thenReturn(consumerRecords).thenReturn(emptyRecords);
}
conf.topicList = topicNames;
MockKafkaConsumerLoader.consumers = consumerList.iterator();
MultiKafkaSource source = new MultiKafkaSource(conf);
PushSourceRunner sourceRunner = new PushSourceRunner.Builder(MultiKafkaDSource.class, source)
.addOutputLane("lane")
.build();
sourceRunner.runInit();
MultiKafkaPushSourceTestCallback callback = new MultiKafkaPushSourceTestCallback(sourceRunner, conf.numberOfThreads);
try {
sourceRunner.runProduce(new HashMap<>(), 5, callback);
//start the interrupt cascade
Thread.currentThread().interrupt();
sourceRunner.waitOnProduce();
} finally {
sourceRunner.runDestroy();
}
Assert.fail();
}
private ConsumerRecords<String, byte[]> generateConsumerRecords(int count, String topic, int partition) {
List<ConsumerRecord<String, byte[]>> consumerRecordsList = new ArrayList<>();
for(int i=0; i<count; i++) {
consumerRecordsList.add(new ConsumerRecord<>(topic, partition, 0, "key" + i, ("value" + i).getBytes()));
}
Map<TopicPartition, List<ConsumerRecord<String, byte[]>>> recordsMap = new HashMap<>();
if(count == 0) {
// SDC-10162 - this will make a ConsumerRecords() object which will return true when tested for isEmpty().
return new ConsumerRecords<>(recordsMap);
} else {
recordsMap.put(new TopicPartition(topic, partition), consumerRecordsList);
return new ConsumerRecords<>(recordsMap);
}
}
static class MultiKafkaPushSourceTestCallback implements PushSourceRunner.Callback {
private final PushSourceRunner pushSourceRunner;
private final AtomicInteger batchesProduced;
private final AtomicInteger recordsProcessed;
private final int numberOfBatches;
MultiKafkaPushSourceTestCallback(PushSourceRunner pushSourceRunner, int numberOfBatches) {
this.pushSourceRunner = pushSourceRunner;
this.numberOfBatches = numberOfBatches;
this.batchesProduced = new AtomicInteger(0);
this.recordsProcessed = new AtomicInteger(0);
}
synchronized int waitForAllBatches() {
try {
pushSourceRunner.waitOnProduce();
} catch (Exception e) {
throw Throwables.propagate(e);
}
return recordsProcessed.get();
}
@Override
public void processBatch(StageRunner.Output output) {
List<Record> records = output.getRecords().get("lane");
if (!records.isEmpty()) {
recordsProcessed.addAndGet(records.size());
if (batchesProduced.incrementAndGet() == numberOfBatches) {
pushSourceRunner.setStop();
}
}
}
}
@Test
public void testLineageEvent() throws StageException, InterruptedException, ExecutionException {
MultiKafkaBeanConfig conf = getConfig();
conf.numberOfThreads = 5;
int numTopics = 3;
long totalMessages = 0;
Random rand = new Random();
List<String> topicNames = new ArrayList<>(numTopics);
List<KafkaConsumer> consumerList = new ArrayList<>(numTopics);
for(int i=0; i<numTopics; i++) {
String topic = "topic-" + i;
topicNames.add(topic);
}
for(int i=0, topicIndex= 0; i<conf.numberOfThreads; i++, topicIndex++) {
if (topicIndex == numTopics) {
topicIndex = 0;
}
int numMessages = rand.nextInt(5)+1;
totalMessages += numMessages;
ConsumerRecords<String, byte[]> consumerRecords = generateConsumerRecords(numMessages, topicNames.get(topicIndex), 0);
ConsumerRecords<String, byte[]> emptyRecords = generateConsumerRecords(0, topicNames.get(rand.nextInt(numTopics)), 0);
KafkaConsumer mockConsumer = Mockito.mock(KafkaConsumer.class);
consumerList.add(mockConsumer);
Mockito.when(mockConsumer.poll(conf.batchWaitTime)).thenReturn(consumerRecords).thenReturn(emptyRecords);
}
conf.topicList = topicNames;
MockKafkaConsumerLoader.consumers = consumerList.iterator();
MultiKafkaSource source = new MultiKafkaSource(conf);
PushSourceRunner sourceRunner = new PushSourceRunner.Builder(MultiKafkaDSource.class, source)
.addOutputLane("lane")
.build();
sourceRunner.runInit();
MultiKafkaPushSourceTestCallback callback = new MultiKafkaPushSourceTestCallback(sourceRunner, conf.numberOfThreads);
try {
sourceRunner.runProduce(new HashMap<>(), 5, callback);
int records = callback.waitForAllBatches();
source.await();
Assert.assertEquals(totalMessages, records);
} catch (StageException e){
Assert.fail();
}
List<LineageEvent> events = sourceRunner.getLineageEvents();
Assert.assertEquals(numTopics, events.size());
for(int i = 0; i < numTopics; i++) {
Assert.assertEquals(LineageEventType.ENTITY_READ, events.get(i).getEventType());
Assert.assertTrue(topicNames.contains(events.get(i).getSpecificAttribute(LineageSpecificAttribute.ENTITY_NAME)));
}
sourceRunner.runDestroy();
}
}
| 38.635266 | 137 | 0.726977 |
6035585361becee0d743c84df69c1b7d63f5ce24 | 9,619 | package games.rednblack.editor.renderer.factory;
import com.artemis.EntityEdit;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.IntIntMap;
import com.badlogic.gdx.utils.viewport.Viewport;
import games.rednblack.editor.renderer.box2dLight.RayHandler;
import games.rednblack.editor.renderer.commons.IExternalItemType;
import games.rednblack.editor.renderer.components.MainItemComponent;
import games.rednblack.editor.renderer.components.TransformComponent;
import games.rednblack.editor.renderer.components.ViewPortComponent;
import games.rednblack.editor.renderer.data.*;
import games.rednblack.editor.renderer.factory.component.*;
import games.rednblack.editor.renderer.resources.IResourceRetriever;
import games.rednblack.editor.renderer.utils.ComponentRetriever;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class EntityFactory {
public static final int UNKNOWN_TYPE = -1;
public static final int COMPOSITE_TYPE = 1;
public static final int COLOR_PRIMITIVE = 2;
public static final int IMAGE_TYPE = 3;
public static final int LABEL_TYPE = 4;
public static final int SPRITE_TYPE = 5;
public static final int PARTICLE_TYPE = 6;
public static final int LIGHT_TYPE = 7;
public static final int NINE_PATCH = 8;
public static final int SPINE_TYPE = 9;
public static final int TALOS_TYPE = 10;
protected ComponentFactory compositeComponentFactory, lightComponentFactory, particleEffectComponentFactory,
simpleImageComponentFactory, spriteComponentFactory, labelComponentFactory,
ninePatchComponentFactory, colorPrimitiveFactory;
private final HashMap<Integer, ComponentFactory> externalFactories = new HashMap<>();
// TODO: Do we still need it? Like, in Artemis all enties are already identified by a Unique ID
// private final HashMap<Integer, Entitiy> entities = new HashMap<>();
private final IntIntMap entities = new IntIntMap();
public RayHandler rayHandler;
public World world;
public IResourceRetriever rm = null;
public com.artemis.World engine;
public EntityFactory(com.artemis.World engine, RayHandler rayHandler, World world, IResourceRetriever rm) {
this.engine = engine;
this.rayHandler = rayHandler;
this.world = world;
this.rm = rm;
compositeComponentFactory = new CompositeComponentFactory(engine, rayHandler, world, rm);
lightComponentFactory = new LightComponentFactory(engine, rayHandler, world, rm);
particleEffectComponentFactory = new ParticleEffectComponentFactory(engine, rayHandler, world, rm);
simpleImageComponentFactory = new SimpleImageComponentFactory(engine, rayHandler, world, rm);
spriteComponentFactory = new SpriteComponentFactory(engine, rayHandler, world, rm);
labelComponentFactory = new LabelComponentFactory(engine, rayHandler, world, rm);
ninePatchComponentFactory = new NinePatchComponentFactory(engine, rayHandler, world, rm);
colorPrimitiveFactory = new ColorPrimitiveComponentFactory(engine, rayHandler, world, rm);
}
public ComponentFactory getCompositeComponentFactory() {
return compositeComponentFactory;
}
public SpriteComponentFactory getSpriteComponentFactory() {
return (SpriteComponentFactory) spriteComponentFactory;
}
public void addExternalFactory(IExternalItemType itemType) {
externalFactories.put(itemType.getTypeId(), itemType.getComponentFactory());
}
public void initializeEntity(int root, int entity, SimpleImageVO vo) {
simpleImageComponentFactory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
public void initializeEntity(int root, int entity, Image9patchVO vo) {
ninePatchComponentFactory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
public void initializeEntity(int root, int entity, LabelVO vo) {
labelComponentFactory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
public void initializeEntity(int root, int entity, ParticleEffectVO vo) {
particleEffectComponentFactory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
public void initializeEntity(int root, int entity, TalosVO vo) {
ComponentFactory factory = externalFactories.get(TALOS_TYPE);
if (factory != null) {
factory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
}
public void initializeEntity(int root, int entity, LightVO vo) {
lightComponentFactory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
public void initializeEntity(int root, int entity, SpineVO vo) {
ComponentFactory factory = externalFactories.get(SPINE_TYPE);
if (factory != null) {
factory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
}
public void initializeEntity(int root, int entity, SpriteAnimationVO vo) {
spriteComponentFactory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
public void initializeEntity(int root, int entity, CompositeItemVO vo) {
compositeComponentFactory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
public void initializeEntity(int root, int entity, ColorPrimitiveVO vo) {
colorPrimitiveFactory.createComponents(root, entity, vo);
postProcessEntity(entity);
}
public int createRootEntity(CompositeVO compositeVo, Viewport viewport) {
CompositeItemVO vo = new CompositeItemVO();
vo.composite = compositeVo;
vo.automaticResize = false;
int entity = engine.create();
EntityEdit edit = engine.edit(entity);
compositeComponentFactory.createComponents(-1, entity, vo);
TransformComponent transform = edit.create(TransformComponent.class);
ViewPortComponent viewPortComponent = edit.create(ViewPortComponent.class);
viewPortComponent.viewPort = viewport;
viewPortComponent.viewPort.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
postProcessEntity(entity);
return entity;
}
public int postProcessEntity(int entity) {
MainItemComponent mainItemComponent = ComponentRetriever.get(entity, MainItemComponent.class);
if (mainItemComponent.uniqueId == -1) mainItemComponent.uniqueId = getFreeId();
entities.put(mainItemComponent.uniqueId, entity);
return mainItemComponent.uniqueId;
}
private int getFreeId() {
if (entities == null || entities.size == 0) return 1;
// TODO: Is it performant enough?
IntIntMap.Keys keys = entities.keys();
ArrayList<Integer> ids = new ArrayList<>();
while (keys.hasNext) ids.add(keys.next());
Collections.sort(ids);
for (int i = 1; i < ids.size(); i++) {
if (ids.get(i) - ids.get(i - 1) > 1) {
return ids.get(i - 1) + 1;
}
}
return ids.get(ids.size() - 1) + 1;
}
public int updateMap(int entity) {
MainItemComponent mainItemComponent = ComponentRetriever.get(entity, MainItemComponent.class);
entities.put(mainItemComponent.uniqueId, entity);
return mainItemComponent.uniqueId;
}
public void initAllChildren(com.artemis.World engine, int entity, CompositeVO vo) {
for (int i = 0; i < vo.sImages.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sImages.get(i));
}
for (int i = 0; i < vo.sImage9patchs.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sImage9patchs.get(i));
}
for (int i = 0; i < vo.sLabels.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sLabels.get(i));
}
for (int i = 0; i < vo.sParticleEffects.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sParticleEffects.get(i));
}
for (int i = 0; i < vo.sTalosVFX.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sTalosVFX.get(i));
}
for (int i = 0; i < vo.sLights.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sLights.get(i));
}
for (int i = 0; i < vo.sSpineAnimations.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sSpineAnimations.get(i));
}
for (int i = 0; i < vo.sSpriteAnimations.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sSpriteAnimations.get(i));
}
for (int i = 0; i < vo.sColorPrimitives.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sColorPrimitives.get(i));
}
for (int i = 0; i < vo.sComposites.size(); i++) {
int child = engine.create();
initializeEntity(entity, child, vo.sComposites.get(i));
initAllChildren(engine, child, vo.sComposites.get(i).composite);
}
}
public int getEntityByUniqueId(int id) {
return entities.get(id, -1);
}
public void clean() {
entities.clear();
}
}
| 38.170635 | 112 | 0.67533 |
892cfb0bf4c5dd1880754be3ad16a5966d34a9e5 | 6,763 | package br.com.virtz.virtzsms.repositorio;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import br.com.virtz.beans.Sms;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
public class SmsRepositorio {
private static final String SMS_TABELA = "Mensagem";
/**
*
* @param token
* @param telefone 3188512273 - só os números com ddd
* @return
*/
private Entity getSms(String token, Long telefone, Date dataCriacao) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key keySms = criarKeyParaSms(token, telefone, dataCriacao);
Query query = new Query(SMS_TABELA, keySms);
Entity sms = datastore.prepare(query).asSingleEntity();
return sms;
}
public List<Sms> recuperarTodos(String token) throws Exception{
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter filterTokenIgual = new FilterPredicate("tokenUsuario", FilterOperator.EQUAL, token);
Query query = new Query(SMS_TABELA).setFilter(filterTokenIgual).addSort("dataCriacao", Query.SortDirection.DESCENDING);
List<Entity> lista = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(9999));
List<Sms> todosSms = new ArrayList<>();
if(lista != null){
for (Entity s : lista) {
Sms sms = entityToSms(s);
todosSms.add(sms);
}
}
return todosSms;
}
public List<Sms> recuperarPorFone(String token, String fone) throws Exception{
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter filterTokenIgual = new FilterPredicate("tokenUsuario", FilterOperator.EQUAL, token);
Filter filterFoneIgual = new FilterPredicate("telefone", FilterOperator.EQUAL, fone);
Query query = new Query(SMS_TABELA).setFilter(filterFoneIgual).setFilter(filterTokenIgual).addSort("dataCriacao", Query.SortDirection.DESCENDING);
List<Entity> lista = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(9999));
List<Sms> todosSms = new ArrayList<>();
for (Entity entity : lista) {
Sms sms = entityToSms(entity);
todosSms.add(sms);
}
return todosSms;
}
public List<Sms> recuperarNaoEnviados() throws Exception{
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter filterTokenIgual = new FilterPredicate("dataEnvio", FilterOperator.EQUAL, null);
Query query = new Query(SMS_TABELA).setFilter(filterTokenIgual);
List<Entity> lista = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(9999));
List<Sms> todosSms = new ArrayList<>();
for (Entity entity : lista) {
Sms sms = entityToSms(entity);
todosSms.add(sms);
}
return todosSms;
}
public void salvar(Sms smsSalvar){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity sms = montarSmsEntityParaSalvar(smsSalvar);
datastore.put(sms);
}
public void salvar(List<Sms> smsSalvar){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
List<Entity> sms = new ArrayList<Entity>();
for(Sms s : smsSalvar){
Entity smsEntity = montarSmsEntityParaSalvar(s);
sms.add(smsEntity);
}
datastore.put(sms);
}
public void remover(Sms smsRemover){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key keySms = criarKeyParaSms(smsRemover.getTokenUsuario(), smsRemover.getTelefone(), smsRemover.getDataCriacao());
datastore.delete(keySms);
}
private Entity montarSmsEntityParaSalvar(Sms smsSalvar) {
Entity sms = getSms(smsSalvar.getTokenUsuario(), smsSalvar.getTelefone(), smsSalvar.getDataCriacao());
if(sms == null){
Key keySms = criarKeyParaSms(smsSalvar.getTokenUsuario(), smsSalvar.getTelefone(), smsSalvar.getDataCriacao());
sms = new Entity(SMS_TABELA, keySms);
}
sms.setProperty("tokenUsuario", smsSalvar.getTokenUsuario());
sms.setProperty("telefone", smsSalvar.getTelefone());
sms.setProperty("mensagem", smsSalvar.getMensagem());
sms.setProperty("okOperadora", smsSalvar.getOkOperadora());
sms.setProperty("dataCriacao", prepararDataCriacao(smsSalvar.getDataCriacao()));
sms.setProperty("dataAgendada", smsSalvar.getDataAgendada());
sms.setProperty("dataEnvio", smsSalvar.getDataEnvio());
sms.setProperty("valorCobrado", smsSalvar.getValorCobrado());
return sms;
}
private Sms entityToSms(Entity e) {
Sms sms = new Sms();
sms.setDataCriacao(e.getProperty("dataCriacao") != null ? ((Date) e.getProperty("dataCriacao")) : null);
sms.setDataAgendada(e.getProperty("dataAgendada") != null ? ((Date) e.getProperty("dataAgendada")) : null);
sms.setDataEnvio(e.getProperty("dataEnvio") != null ? ((Date) e.getProperty("dataEnvio")) : null);
sms.setTelefone(e.getProperty("telefone") != null ? Long.valueOf(e.getProperty("telefone").toString()) : null);
sms.setTokenUsuario(e.getProperty("tokenUsuario") != null ? String.valueOf(e.getProperty("tokenUsuario")) : null);
sms.setMensagem(e.getProperty("mensagem") != null ? String.valueOf(e.getProperty("mensagem")) : null);
sms.setOkOperadora(e.getProperty("okOperadora") != null ? Boolean.valueOf(e.getProperty("okOperadora").toString()) : false);
sms.setValorCobrado((e.getProperty("valorCobrado") != null ? Double.valueOf(String.valueOf(e.getProperty("valorCobrado"))) : null));
return sms;
}
private Date prepararDataCriacao(Date dataCriacao){
Calendar calendar = Calendar.getInstance();
calendar.setTime(dataCriacao);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
private Key criarKeyParaSms(String token, Long telefone, Date dataCriacao) {
dataCriacao = prepararDataCriacao(dataCriacao);
StringBuilder sb = new StringBuilder();
sb.append(token).append(telefone.toString()).append(dataCriacao.toString());
Key k = KeyFactory.createKey(SMS_TABELA, sb.toString());
return k;
}
}
| 35.783069 | 152 | 0.715954 |
c2bdbd9e2b0e6ada828c78a30b038e8337f9e529 | 1,328 | package modelo;
public class Kardex {
private int id;
private String noDocumento;
private Articulo articulo=new Articulo();
private Departamento bodega=new Departamento();
private double entrada=0;
private double salida=0.0;
private double existencia=0.0;
public double getExistencia(){
return existencia;
}
public void setExistencia(double e){
existencia=e;
}
public void incremetarExistencia(double i){
existencia+=i;
}
public void decrementarExistencia(double d){
existencia-=d;
}
private String fecha;
public String getFecha(){
return fecha;
}
public void setFecha(String f){
fecha=f;
}
public double getSalida(){
return salida;
}
public void setSalida(double s){
salida=s;
}
public double getEntrada(){
return entrada;
}
public void setEntrada(double e){
entrada=e;
}
public int getId(){
return id;
}
public void setId(int i){
id=i;
}
public String getNoDocumento(){
return noDocumento;
}
public void setNoDocumento(String n){
noDocumento=n;
}
public Articulo getArticulo(){
return articulo;
}
public void setArticulo(Articulo a){
articulo=a;
}
public void setBodega(Departamento b){
bodega=b;
}
public Departamento getBodega(){
return bodega;
}
}
| 17.246753 | 49 | 0.668675 |
5d6163fd79aad776ef4d0d7b3418abdbcbd061e6 | 1,807 | package io.taucoin.sync;
/**
* Manages sync measurements
*
* @author Mikhail Kalinin
* @since 20.08.2015
*/
public class SyncStatistics {
private static final long EMPTY_HASHES_GOT_TIMEOUT = 600 * 1000;
private long updatedAt;
private long blocksCount;
private long hashesCount;
private int emptyResponsesCount;
private long emptyHashesGotAt;
public SyncStatistics() {
reset();
}
public void reset() {
updatedAt = System.currentTimeMillis();
blocksCount = 0;
hashesCount = 0;
emptyResponsesCount = 0;
}
public void addBlocks(long cnt) {
blocksCount += cnt;
fixCommon(cnt);
}
public void addHashes(long cnt) {
hashesCount += cnt;
fixCommon(cnt);
}
private void fixCommon(long cnt) {
if (cnt == 0) {
emptyResponsesCount += 1;
}
updatedAt = System.currentTimeMillis();
}
public long getBlocksCount() {
return blocksCount;
}
public long getHashesCount() {
return hashesCount;
}
public long millisSinceLastUpdate() {
return System.currentTimeMillis() - updatedAt;
}
public int getEmptyResponsesCount() {
return emptyResponsesCount;
}
public void setEmptyHashesGot() {
emptyHashesGotAt = System.currentTimeMillis();
}
public void setHashesGot() {
emptyHashesGotAt = 0;
}
public boolean isEmptyHashesGotTimeout() {
return emptyHashesGotAt == 0
|| System.currentTimeMillis() - emptyHashesGotAt >= EMPTY_HASHES_GOT_TIMEOUT;
}
public long secondsSinceLastEmptyHashes() {
return (emptyHashesGotAt + EMPTY_HASHES_GOT_TIMEOUT
- System.currentTimeMillis()) / 1000;
}
}
| 22.5875 | 93 | 0.621472 |
05c46d68fcf36b8826c7fe511d3162c0f068e483 | 1,512 | package com.example.tarento.executer.api;
import com.android.volley.Request;
import com.example.tarento.model.BaseModel;
import com.example.tarento.model.GetNonceApiRequest;
import com.example.tarento.model.GetNonceApiResponse;
import com.example.tarento.util.Constant;
import com.example.tarento.util.Utility;
/**
* GetNonceApi
* <p>
* Request:
* {"deviceId":"fd7659d6046987bd"}
* <p>
* Response:
* {"responseStatus":true,
* "nonce":"5cefa6e7-0da0-44aa-aacb-b26c3be0c8a0"}
*
* @author Indraja Machani
*/
public class GetNonceApi extends BaseApi {
private static final String TAG = GetNonceApi.class.getSimpleName();
public GetNonceApi(GetNonceApiRequest getNonceApiRequest) {
// set partial url
setUrl(Constant.API_GET_NONCE);
// set request id
setRequestId(Constant.REQUESTID_GETNONCE_API);
//set method
setMethod(Request.Method.POST);
//set body data
setBody(Utility.toJson(getNonceApiRequest, GetNonceApiRequest.class));
}
/**
* serialize response
*
* @param responseJsonObject
* @return
* @throws Exception
*/
@Override
public BaseModel serialize(String responseJsonObject) {
BaseModel response = null;
try {
// parse the response data
response = Utility.getGson().fromJson(responseJsonObject, GetNonceApiResponse.class);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
| 25.627119 | 97 | 0.670635 |
3ec3090a83cd3962a663cce9445efbc01ca9e858 | 22,281 | package cs3500.easyanimator.view;
import cs3500.easyanimator.controller.EditorListener;
import cs3500.easyanimator.model.IAnimatorModelViewOnly;
import cs3500.easyanimator.model.shapes.IShape;
import cs3500.easyanimator.model.shapes.IShapeVisitor;
import cs3500.easyanimator.model.shapes.ShapeNameVisitor;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import javax.swing.Timer;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.SortedMap;
/**
* Implementation of an EnhancedView that delegates base operations to a VisualView.
*/
public class EditorSwingView implements IEnhancedView {
private final EditorListener listener;
private final Timer timer;
private int tick;
private double speed;
private boolean looping;
private IAnimatorModelViewOnly model;
@Override
public void setModel(IAnimatorModelViewOnly model) {
// When we get a new view we need to update several things.
this.model = model;
updateShapes();
}
// GRAPHICS
private static final Dimension EDITOR_PANEL_SIZE = new Dimension(300, 500);
private static final Color EDITOR_PANEL_BACKGROUND = Color.GRAY;
/**
* A small helper method to create the editor panel. This will return something that will stack
* components vertically in our editor.
* @return The newly created panel.
*/
private JPanel createEditorPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setMinimumSize(EDITOR_PANEL_SIZE);
panel.setMaximumSize(EDITOR_PANEL_SIZE);
panel.setBackground(EDITOR_PANEL_BACKGROUND);
return panel;
}
private static Dimension MAX_FIELD_SIZE = new Dimension(200, 25);
/**
* Create a field coupled with a label and add it to the editor panel.
* @param name The named label of the field to use.
* @param editorPanel The panel to add the field group to.
* @return
*/
private JTextField createField(String name, JPanel editorPanel) {
JPanel group = new JPanel(new BorderLayout());
JTextField field = new JTextField();
field.setPreferredSize(MAX_FIELD_SIZE);
JLabel label = new JLabel(name);
group.add(label, BorderLayout.CENTER);
group.add(field, BorderLayout.WEST);
editorPanel.add(group);
return field;
}
/**
* Create a button and link it to the given action listener with the given action command.
* Add to the given panel
* @param name The button name.
* @param listener The listener to use.
* @param command The string to use in the action command.
* @param panel The panel to add yourself to.
*/
private JButton addButton(String name, ActionListener listener, String command, JPanel panel) {
JButton button = new JButton(name);
button.setActionCommand(command);
button.addActionListener(listener);
panel.add(button);
return button;
}
/**
* A PLAYBACK_ACTION is a set of actions to do when adjusting playback.
*/
private enum PLAYBACK_ACTION { PLAY, PAUSE, RESTART, TOGGLELOOP, SPEEDUP, SPEEDDOWN,
TICKUP, TICKDOWN }
// We have the listener for those actions below.
// See the justification for this style here, https://stackoverflow.com/a/5937586.
// The time to change the delay by.
// By default, changing the tps by 5.
private static int TIMER_CHANGE = 20;
/**
* A PlaybackListener is a class to listen to playback commands.
*/
private class PlaybackListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String ac = e.getActionCommand();
// Since these enums are singleton instances we can actually do a pointer comparison.
if (ac == PLAYBACK_ACTION.PLAY.name()) {
if (model != null) {
// Without a model, if we start there will be errors.
timer.start();
}
}
// PAUSE
else if (ac == PLAYBACK_ACTION.PAUSE.name()) {
timer.stop();
}
// RESTART
else if (ac == PLAYBACK_ACTION.RESTART.name()) {
timer.stop();
tick = 0;
refresh();
}
// SPEEDUP
else if (ac == PLAYBACK_ACTION.SPEEDUP.name()) {
// Max not necessary here, but here for good practice as a reminder.
setSpeed(speed + 1);
}
// SPEEDDOWN
else if (ac == PLAYBACK_ACTION.SPEEDDOWN.name()) {
setSpeed(speed - 1);
}
//TOGGLELOOP
else if (ac == PLAYBACK_ACTION.TOGGLELOOP.name()) {
looping = !looping;
}
//TICKUP
else if (ac == PLAYBACK_ACTION.TICKUP.name()) {
if (tick == model.getMaxTick()) {
tick = 0;
} else {
tick = tick + 1;
}
mainPanel.setShapes(model.getShapesAtTick(tick));
mainPanel.repaint();
updateTickLabel();
}
//TICKDOWN
else if (ac == PLAYBACK_ACTION.TICKDOWN.name()) {
if (tick == 0) {
tick = model.getMaxTick();
} else {
tick = tick - 1;
}
mainPanel.setShapes(model.getShapesAtTick(tick));
mainPanel.repaint();
updateTickLabel();
}
else {
// We don't add events to this listener without setting the action command.
throw new IllegalStateException("This branch should have been unreachable");
}
}
}
/**
* A EDITING_ACTION is a set of actions having to do when changing shape details.
*/
private enum EDITING_ACTION { SELECT_SHAPE, SAVE_SHAPE, DELETE_SHAPE,
SELECT_KEYFRAME, SAVE_KEYFRAME, DELETE_KEYFRAME }
private static Toolkit tk = Toolkit.getDefaultToolkit();
/**
* Rings the system bell if there was a failure of an operation from the controller.
* @param success The boolean of success to use.
*/
private static void bellOnFail(boolean success) {
if (!success) {
tk.beep();
}
}
/**
* An EditingListener is an action listener for all the commands the user may enter having to
* do with editing.
*/
private class EditingListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String ac = e.getActionCommand();
// Some useful variables.
String selectedShapeString = (String) selectShape.getSelectedItem();
if (selectedShapeString == null) {
bellOnFail(false);
return;
} else {
selectedShapeString = selectedShapeString.trim();
}
// I use ██████████ to show the different actions.
// ██████████ SELECTING A SHAPE ██████████
if (ac == EDITING_ACTION.SELECT_SHAPE.name()) {
selectShape(selectedShapeString);
// ██████████ OVERRIDING / CREATING A SHAPE ██████████
} else if (ac == EDITING_ACTION.SAVE_SHAPE.name()) {
String newShapeName = shapeName.getText().trim();
String newShapeType = (String) shapeType.getSelectedItem();
// Check if they tried to name a shape New Shape.
if (newShapeName.equals(NEW_SHAPE)) {
// Naughty user.
bellOnFail(false);
return;
}
// Are they trying to rename?
if (!selectedShapeString.equals(NEW_SHAPE) && !selectedShapeString.equals(newShapeName)) {
// Override.
bellOnFail(listener.renameShape(selectedShapeString, newShapeName, newShapeType));
} else {
// Adding a new shape.
bellOnFail(listener.addShape(newShapeName, newShapeType));
}
// No matter what happened, let's update.
updateShapes();
// ██████████ DELETING A SHAPE ██████████
} else if (ac == EDITING_ACTION.DELETE_SHAPE.name()) {
bellOnFail(listener.removeShape(selectedShapeString));
updateShapes();
// ██████████ SELECTING A KEYFRAME ██████████
} else if (ac == EDITING_ACTION.SELECT_KEYFRAME.name()) {
selectKeyframe(selectedShapeString,
getTickSelected());
// ██████████ SAVING A KEYFRAME ██████████
} else if (ac == EDITING_ACTION.SAVE_KEYFRAME.name()) {
// This is very similar to save shape.
Integer tickSelected = getTickSelected();
Integer tickSet;
try {
tickSet = Integer.parseInt(keyFrameTick.getText());
} catch (NumberFormatException nfe) {
bellOnFail(false);
return;
}
if (!tickSet.equals(tickSelected) && tickSelected != null) {
// We need to move the keyframe before overriding it..
bellOnFail(listener.removeKeyframe(selectedShapeString, tickSelected));
}
// Overriding and moving.
bellOnFail(listener.setKeyframe(selectedShapeString,
tickSet,
keyFrameWidth.getText(), keyFrameHeight.getText(),
keyFrameX.getText(), keyFrameY.getText(),
keyFrameR.getText(), keyFrameG.getText(), keyFrameB.getText()));
updateKeyframeSelector(selectedShapeString);
// ██████████ DELETING A KEYFRAME ██████████
} else if (ac == EDITING_ACTION.DELETE_KEYFRAME.name()) {
bellOnFail(listener.removeKeyframe(selectedShapeString, getTickSelected()));
updateKeyframeSelector(selectedShapeString);
} else {
throw new IllegalStateException("This branch of the if statement " +
"should have been impossible to reach.");
}
}
}
/**
* Class for handling a key pressed, will pass off to the controller.
*/
private class SaveListener implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
//do nothing.
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == 's') {
listener.saveModel();
}
else if (e.getKeyChar() == 'l') {
listener.loadModel();
}
}
@Override
public void keyReleased(KeyEvent e) {
//do nothing.
}
}
private static String[] DEFAULT_SHAPES = new String[]{"rectangle", "oval"};
private static Dimension MINIMUM_WINDOW_SIZE = new Dimension(800, 600);
private static Dimension MAX_PLAYBACK_BUTTONS_SIZE = new Dimension(Integer.MAX_VALUE, 50);
/**
* Create a new editor window linking it to a listener for model and other program actions.
* @param listener A class to listener and respond to different macro user events as they happen
* in the editor.
*/
public EditorSwingView(EditorListener listener) {
super();
// Editor stuff that is not graphics.
this.listener = listener;
//this.saveListener = listener;
this.timer = new Timer(30, e -> this.refresh());
this.tick = 0;
this.looping = true;
frame = new JFrame("EasyAnimator");
// WINDOW SETTINGS
frame.setTitle("EasyAnimator");
frame.setMinimumSize(MINIMUM_WINDOW_SIZE);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ADDING COMPONENTS
frame.setLayout(new BorderLayout());
frame.addKeyListener(saveKeyListener);
ActionListener playbackListener = new PlaybackListener();
// I was forced to put this listener not as a field ...
// but a local variable by the dreaded style checker.
ActionListener editingListener = new EditingListener();
saveKeyListener = new SaveListener();
// THE EDITOR ON THE RIGHT
// Next, we want the basic layout that everything is going to sit on.
JPanel editorPanel = createEditorPanel();
// SHAPE CONTROLS, we don't yet have a model so it will be blank.
this.selectShape = new JComboBox<>();
selectShape.setActionCommand(EDITING_ACTION.SELECT_SHAPE.name());
selectShape.addActionListener(editingListener);
selectShape.addKeyListener(saveKeyListener);
editorPanel.add(selectShape);
this.shapeName = createField("Shape Name", editorPanel);
this.shapeType = new JComboBox<>(DEFAULT_SHAPES);
editorPanel.add(shapeType);
this.shapeType.addKeyListener(saveKeyListener);
// I was made to make these local variables by the style checker.
JButton saveShape = addButton("Save Shape",
editingListener, EDITING_ACTION.SAVE_SHAPE.name(),
editorPanel);
JButton deleteShape = addButton("Delete Shape",
editingListener, EDITING_ACTION.DELETE_SHAPE.name(),
editorPanel);
// KEYFRAME CONTROLS, we don't yet have the model so this too will be blank.
selectTick = new JComboBox<>();
selectTick.setActionCommand(EDITING_ACTION.SELECT_KEYFRAME.name());
selectTick.addActionListener(editingListener);
selectTick.addKeyListener(saveKeyListener);
editorPanel.add(selectTick);
editorPanel.addKeyListener(saveKeyListener);
// createField adds it to the panel for us, how generous.
this.keyFrameTick = createField("Keyframe Tick", editorPanel);
this.keyFrameX = createField("X", editorPanel);
this.keyFrameY = createField("Y", editorPanel);
this.keyFrameWidth = createField("Width", editorPanel);
this.keyFrameHeight = createField("Height", editorPanel);
this.keyFrameR = createField("Red", editorPanel);
this.keyFrameG = createField("Green", editorPanel);
this.keyFrameB = createField("Blue", editorPanel);
// Buttons at the bottom to finalize changes.
JButton saveModification = addButton("Save Keyframe (Change)",
editingListener, EDITING_ACTION.SAVE_KEYFRAME.name(),
editorPanel);
JButton deleteKeyFrame = addButton("Delete Keyframe (Change)",
editingListener, EDITING_ACTION.DELETE_KEYFRAME.name(),
editorPanel);
frame.add(editorPanel, BorderLayout.WEST);
// ONTO THE OTHER COMPONENTS
// We'll add the player at the top of this panel, then the playback buttons.
JPanel playbackPanel = new JPanel();
playbackPanel.setLayout(new BoxLayout(playbackPanel, BoxLayout.Y_AXIS));
this.mainPanel = new DrawPanel();
this.mainPanel.addKeyListener(saveKeyListener);
JScrollPane scrollPane = new JScrollPane(this.mainPanel);
playbackPanel.add(scrollPane);
// Now we add a button panel full of playback controls.
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout());
// We give the playback controls a tint.
buttonPanel.setBackground(new Color(106, 35, 38));
buttonPanel.setMaximumSize(MAX_PLAYBACK_BUTTONS_SIZE);
playbackPanel.add(buttonPanel);
// Onto buttons.
JButton startButton = addButton("Play",
playbackListener, PLAYBACK_ACTION.PLAY.name(),
buttonPanel);
JButton pauseButton = addButton("Pause",
playbackListener, PLAYBACK_ACTION.PAUSE.name(),
buttonPanel);
JButton restartButton = addButton("Restart",
playbackListener, PLAYBACK_ACTION.RESTART.name(),
buttonPanel);
JButton toggleLoop = addButton("Toggle Loop",
playbackListener, PLAYBACK_ACTION.TOGGLELOOP.name(),
buttonPanel);
JButton increaseSpeedButton = addButton("^ Speed",
playbackListener, PLAYBACK_ACTION.SPEEDUP.name(),
buttonPanel);
JButton decreaseSpeedButton = addButton("v Speed",
playbackListener, PLAYBACK_ACTION.SPEEDDOWN.name(),
buttonPanel);
JButton tickUp = addButton("^ Tick",
playbackListener, PLAYBACK_ACTION.TICKUP.name(),
buttonPanel);
JButton tickDown = addButton("v Tick",
playbackListener, PLAYBACK_ACTION.TICKDOWN.name(),
buttonPanel);
this.tickLabel = new JLabel();
buttonPanel.add(tickLabel);
this.frame.add(playbackPanel);
this.frame.addKeyListener(saveKeyListener);
}
// All the graphics fields we use.
// We interact with these in the code below.
private JFrame frame;
private JLabel tickLabel;
// SHAPE SELECTOR
private KeyListener saveKeyListener;
private JComboBox selectShape;
private JTextField shapeName;
private JComboBox<String> shapeType;
// KEYFRAME EDITING
private JComboBox selectTick;
private JTextField keyFrameTick;
private JTextField keyFrameX;
private JTextField keyFrameY;
private JTextField keyFrameWidth;
private JTextField keyFrameHeight;
private JTextField keyFrameR;
private JTextField keyFrameG;
private JTextField keyFrameB;
// PLAYBACK
private DrawPanel mainPanel;
@Override
public void makeVisible() {
this.frame.setVisible(true);
}
/**
* A custom method to use when refreshing playback.
*/
private void refresh() {
if (this.model.getMaxTick() == 0) {
// A special rule for if the model is in a particularly weird state.
this.tick = 0;
this.timer.stop();
} else if (this.looping) {
this.tick = (this.tick + 1) % model.getMaxTick();
} else {
if (this.tick == model.getMaxTick()) {
this.timer.stop();
this.tick = 0;
} else {
this.tick += 1;
}
}
this.mainPanel.setShapes(model.getShapesAtTick(this.tick));
this.mainPanel.repaint();
this.updateTickLabel();
}
/**
* Simply updates the tick label to the current tick.
*/
private void updateTickLabel() {
this.tickLabel.setText(" " + this.tick);
}
@Override
public void setSpeed(double tps) {
this.speed = Math.max(tps, 1);
this.timer.setDelay((int) Math.max(1, (1.0 / speed * 1000.0)));
}
private static String NEW_KEYFRAME = "New Keyframe";
private static String NEW_SHAPE = "New Shape";
/**
* A helper method to get the current keyframe tick selected if applicable.
* @return The current keyframe index or null if not a number.
*/
private Integer getTickSelected() {
String selectedItem = (String) this.selectTick.getSelectedItem();
if (!NEW_KEYFRAME.equals(selectedItem)) {
if (selectedItem != null) {
return Integer.parseInt(selectedItem);
} else {
return null;
}
} else {
return null;
}
}
/**
* A helper method to update the shape selector.
*/
private void updateShapes() {
this.selectShape.removeAllItems();
for (String name: model.getShapeNames()) {
this.selectShape.addItem(name);
}
this.selectShape.addItem(NEW_SHAPE);
}
private IShapeVisitor<String> getName = new ShapeNameVisitor();
/**
* A helper method to update fields below when selecting a shape of the given name.
* @param name The name of the shape to update fields with.
*/
private void selectShape(String name) {
// If the shape doesn't exist then we don't bother updating fields.
if (!model.getShapes().containsKey(name)) {
return;
}
// Shape fields.
shapeName.setText(name);
shapeType.setSelectedItem(model.getShapes().get(name).accept(getName));
// Keyframe fields.
updateKeyframeSelector(name);
if (model.getKeyframes(name).size() > 0) {
selectKeyframe(name, model.getKeyframes(name).firstKey());
}
// We don't select a keyframe if there are no keyframes.
// This will leave the keyframes fields on whatever they were previously.
// I'm okay with this.
}
/**
* A helper method to update the keyframe selector.
* @param name The name of the shape to use to lookup keyframes.
*/
private void updateKeyframeSelector(String name) {
selectTick.removeAllItems();
for (Integer tick: model.getKeyframes(name).keySet()) {
selectTick.addItem(Integer.toString(tick));
}
selectTick.addItem(NEW_KEYFRAME);
}
// We use this number as the default for everything.
private static String DEFAULT = "100";
/**
* A helper method to update fields below when selecting a keyframe of the given integer.
* If the tick is between two keyframes we get the mid point with getShapeAtTick.
* Otherwise we use the closest keyframe values.
* Or we set them to the defaults.
* @param name The name of the shape to use when selecting a keyframe.
* @param tick The tick of the keyframe we have selected.
*/
private void selectKeyframe(String name, Integer tick) {
String w = DEFAULT;
String h = DEFAULT;
String x = DEFAULT;
String y = DEFAULT;
String r = DEFAULT;
String g = DEFAULT;
String b = DEFAULT;
// If we have actually selected the New Keyframe we just want to use the playback tick.
if (tick == null) {
tick = this.tick;
}
if (name == null || !model.getShapeNames().contains(name)) {
return;
}
SortedMap<Integer, IShape> keyframes = model.getKeyframes(name);
if (keyframes.size() > 0) {
IShape state;
SortedMap<Integer, IShape> tailMap = keyframes.tailMap(tick);
SortedMap<Integer, IShape> headMap = keyframes.headMap(tick);
if (keyframes.containsKey(tick)) {
state = keyframes.get(tick);
// I have this extra from the bottom since I think getShapeAtTick may have rounding errors.
} else if (tailMap.size() > 0 && headMap.size() > 0) {
state = model.getShapeAtTick(name, tick);
} else if (tailMap.size() > 0) {
state = keyframes.get(tailMap.firstKey());
} else {
state = keyframes.get(headMap.firstKey());
}
w = Integer.toString(state.getSize().getWidth());
h = Integer.toString(state.getSize().getHeight());
x = Integer.toString(state.getPosition().getX());
y = Integer.toString(state.getPosition().getY());
r = Integer.toString(state.getColor().getRed());
g = Integer.toString(state.getColor().getGreen());
b = Integer.toString(state.getColor().getBlue());
}
// We do NOT set the selected tick. That must be done somewhere else.
this.keyFrameTick.setText(Integer.toString(tick));
this.keyFrameWidth.setText(w);
this.keyFrameHeight.setText(h);
this.keyFrameX.setText(x);
this.keyFrameY.setText(y);
this.keyFrameR.setText(r);
this.keyFrameG.setText(g);
this.keyFrameB.setText(b);
}
}
| 33.404798 | 99 | 0.663211 |
3b5c7e0f09f63ba385d9d65d67c2a8b904edf6cc | 6,212 | package com.cskaoyan.gateway.controller.promo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.config.CacheManager;
import com.cskaoyan.gateway.form.promo.CreatePromoOrderInfo;
import com.google.common.util.concurrent.RateLimiter;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.promo.PromoService;
import com.mall.promo.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.*;
/**
* @author: jia.xue
* @Email: [email protected]
* @Description
**/
@RestController
@RequestMapping("/shopping")
public class PromoController {
@Reference(check = false)
private PromoService promoService;
@Autowired
private RedissonClient redissonClient;
@Autowired
private CacheManager cacheManager;
private RateLimiter rateLimiter;
private ExecutorService executorService;
@PostConstruct
public void init(){
rateLimiter = RateLimiter.create(100);
//
// //带有定时任务的线程池
//// executorService = Executors.newScheduledThreadPool();
//
// //新建一个单线程的线程池
//// executorService = Executors.newSingleThreadExecutor();
//
// //新建一个缓存类型的线程池
//// executorService = Executors.newCachedThreadPool();
//
// //新建一个固定大小的线程池
// // LinkedBlockingQueue 无界的阻塞队列
executorService = Executors.newFixedThreadPool(100);
}
@GetMapping("/seckilllist")
@Anoymous
public ResponseData getPromoList(@RequestParam Integer sessionId) {
PromoInfoRequest promoInfoRequest = new PromoInfoRequest();
promoInfoRequest.setSessionId(sessionId);
String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
promoInfoRequest.setYyyymmdd(yyyyMMdd);
PromoInfoResponse promoInfoResponse = promoService.getPromoList(promoInfoRequest);
if (!promoInfoResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
return new ResponseUtil<>().setErrorMsg(promoInfoResponse.getMsg());
}
return new ResponseUtil<>().setData(promoInfoResponse);
}
@PostMapping("/seckill")
public ResponseData seckill(HttpServletRequest request, @RequestBody CreatePromoOrderInfo createPromoOrderInfo) throws ExecutionException, InterruptedException {
// 获取一个令牌 返回值是什么呢? 返回值可以理解为等待时间
/**
* public double acquire(int permits) {
* // 需要等待的时间
* long microsToWait = this.reserve(permits);
*
* // 让线程去等待
* this.stopwatch.sleepMicrosUninterruptibly(microsToWait);
*
* // 100/1000 = 0.1 (0.1 秒)
* return 1.0D * (double)microsToWait / (double)TimeUnit.SECONDS.toMicros(1L);
* }
*/
rateLimiter.acquire();
String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
JSONObject jsonObject = JSON.parseObject(userInfo);
String username = (String) jsonObject.get("username");
Integer uid = (Integer)jsonObject.get("uid");
CreatePromoOrderRequest createPromoOrderRequest = new CreatePromoOrderRequest();
createPromoOrderRequest.setProductId(createPromoOrderInfo.getProductId());
createPromoOrderRequest.setPsId(createPromoOrderInfo.getPsId());
createPromoOrderRequest.setUserId(uid.longValue());
createPromoOrderRequest.setUsername(username);
//增加地址信息
createPromoOrderRequest.setAddressId(createPromoOrderInfo.getAddressId());
createPromoOrderRequest.setStreetName(createPromoOrderInfo.getStreetName());
createPromoOrderRequest.setTel(createPromoOrderInfo.getTel());
/**
* 可以去Redis里面看一下有没有库存售罄的标记
*
* 如果有 表示库存已经售罄
*
* 如果没有,表示我们的库存还有剩余
*/
String key = "promo_item_stock_not_enough_" + createPromoOrderInfo.getPsId() +"_" + createPromoOrderInfo.getProductId();
String cache = cacheManager.checkCache(key);
if (! StringUtils.isBlank(cache)) {
return new ResponseUtil<>().setErrorMsg("库存已经售罄");
}
// 通过线程池去限制派发给下游的秒杀服务的流量
// 线程池的作用主要是为了去保护下游的系统
Future<CreatePromoOrderResponse> future = executorService.submit(new Callable<CreatePromoOrderResponse>() {
@Override
public CreatePromoOrderResponse call() {
CreatePromoOrderResponse promoOrderResponse = promoService.createPromoOrderInTransaction(createPromoOrderRequest);
return promoOrderResponse;
}
});
CreatePromoOrderResponse promoOrderResponse = future.get();
// CreatePromoOrderResponse promoOrderResponse = promoService.createPromoOrderInTransaction(createPromoOrderRequest);
if (!promoOrderResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
return new ResponseUtil<>().setErrorMsg(promoOrderResponse.getMsg());
}
return new ResponseUtil<>().setData(promoOrderResponse);
}
@PostMapping("/promoProductDetail")
public ResponseData getPromoProductsDetails(@RequestBody PromoProductDetailRequest request) {
PromoProductDetailResponse response = promoService.getPromoProductProduct(request);
if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode()) ) {
return new ResponseUtil<>().setErrorMsg(response.getMsg());
}
return new ResponseUtil<>().setData(response);
}
} | 36.116279 | 165 | 0.690116 |
60a4dd2dd0ec4786d67d4e389d8e77ae57e44827 | 10,232 | /*
* Copyright 2017 Matthew Tamlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.matthewtamlin.mixtape.library.mixtape_container;
import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.matthewtamlin.android_utilities.library.helpers.DimensionHelper;
import com.matthewtamlin.mixtape.library.R;
import com.matthewtamlin.mixtape.library.mixtape_body.RecyclerBodyView;
import com.matthewtamlin.mixtape.library.mixtape_header.ToolbarHeader;
import static android.support.design.widget.AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS;
import static android.support.design.widget.AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL;
import static android.support.design.widget.AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static com.matthewtamlin.mixtape.library.mixtape_container.CoordinatedMixtapeContainer.Constraint.PERSISTENT_HEADER;
import static com.matthewtamlin.mixtape.library.mixtape_container.CoordinatedMixtapeContainer.Constraint.SHOW_HEADER_AT_START;
import static com.matthewtamlin.mixtape.library.mixtape_container.CoordinatedMixtapeContainer.Constraint.SHOW_HEADER_ON_SCROLL_TO_START;
/**
* A MixtapeContainer which shows and hides the header based on body scroll events. There are four
* available coordination profiles: <ul> <li>The header is always hidden, regardless of body scroll
* events.</li> <li>The header is always shown, regardless of body scroll events.</li> <li>The
* header is hidden unless the body is scrolled to the start position.</li> <li>The header is shown
* whenever the body is scrolled towards the start, and hidden whenever the body is scrolled towards
* the end.</li> </ul>
*/
public class CoordinatedMixtapeContainer extends FrameLayout implements
MixtapeContainerView<ToolbarHeader, RecyclerBodyView> {
/**
* Performs the actual coordination.
*/
private CoordinatorLayout coordinatorLayout;
/**
* Contains the header and facilitates scrolling behaviours.
*/
private AppBarLayout headerContainer;
/**
* The header to display at the top of the view.
*/
private ToolbarHeader header;
/**
* The body to display beneath the header.
*/
private RecyclerBodyView body;
/**
* The current elevation of the body.
*/
private int bodyElevationPx = 0;
/**
* The current constraint between the header and the body.
*/
private Constraint constraint = PERSISTENT_HEADER;
/**
* Constructs a new CoordinatedMixtapeCoordinatorView.
*
* @param context
* the context this view is operating in, not null
*/
public CoordinatedMixtapeContainer(final Context context) {
super(context);
init();
}
/**
* Constructs a new CoordinatedMixtapeCoordinatorView.
*
* @param context
* the Context the view is operating in, not null
* @param attrs
* configuration attributes, null allowed
*/
public CoordinatedMixtapeContainer(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* Constructs a new CoordinatedMixtapeCoordinatorView.
*
* @param context
* the Context the view is operating in, not null
* @param attrs
* configuration attributes, null allowed
* @param defStyleAttr
* an attribute in the current theme which supplies default attributes, pass 0 to ignore
*/
public CoordinatedMixtapeContainer(final Context context,
final AttributeSet attrs,
final int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@Override
public ToolbarHeader getHeader() {
return header;
}
@Override
public void setHeader(final ToolbarHeader header) {
headerContainer.removeView(this.header);
if (header != null) {
headerContainer.addView(header);
header.setLayoutParams(new AppBarLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
}
this.header = header;
applyCurrentConstraint();
}
@Override
public RecyclerBodyView getBody() {
return body;
}
@Override
public void setBody(final RecyclerBodyView body) {
coordinatorLayout.removeView(this.body);
if (body != null) {
coordinatorLayout.addView(body);
final CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams
(MATCH_PARENT, MATCH_PARENT);
layoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
body.setLayoutParams(layoutParams);
}
this.body = body;
setBodyElevationPx(bodyElevationPx);
applyCurrentConstraint();
}
@Override
public void setHeaderElevationDp(final int elevationDp) {
setHeaderElevationPx(DimensionHelper.dpToPx(getContext(), elevationDp));
}
@Override
public void setHeaderElevationPx(final int elevationPx) {
// No need to check for null, since the header container is never be null
ViewCompat.setElevation(headerContainer, DimensionHelper.dpToPx(getContext(), elevationPx));
}
@Override
public void setBodyElevationDp(final int elevationDp) {
setBodyElevationPx(DimensionHelper.dpToPx(getContext(), elevationDp));
}
@Override
public void setBodyElevationPx(final int elevationPx) {
this.bodyElevationPx = elevationPx;
// Check must be done since the body may be null
if (body != null) {
ViewCompat.setElevation(body, DimensionHelper.dpToPx(getContext(), bodyElevationPx));
}
}
/**
* Configures this view to always hide the header regardless of body scroll events. This
* overrides any behaviour set previously.
*/
public void hideHeaderAlways() {
constraint = Constraint.HIDDEN_HEADER;
applyCurrentConstraint();
}
/**
* Configures this view to always show the header regardless of body scroll events. This
* overrides any behaviour set previously.
*/
public void showHeaderAlways() {
constraint = PERSISTENT_HEADER;
applyCurrentConstraint();
}
/**
* Configures this view to hide the header unless the body is scrolled to the start position.
* This overrides any behaviour set previously.
*/
public void showHeaderAtStartOnly() {
constraint = SHOW_HEADER_AT_START;
applyCurrentConstraint();
}
/**
* Configures this view to show the header whenever the body is scrolled towards the start, and
* hide the header whenever the body is scrolled towards the end. This overrides any behaviour
* set previously.
*/
public void showHeaderOnScrollToStartOnly() {
constraint = SHOW_HEADER_ON_SCROLL_TO_START;
applyCurrentConstraint();
}
/**
* Creates the layout and assigns the necessary views references to member variables.
*/
private void init() {
inflate(getContext(), R.layout.coordinatedheaderbodyview, this);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatedHeaderBodyView_root);
headerContainer = (AppBarLayout) findViewById(R.id.coordinatedHeaderBodyView_container);
}
/**
* Applies the current constraint to the header and the body. If the current constraint is null,
* the {@link Constraint#PERSISTENT_HEADER} constraint is used.
*/
private void applyCurrentConstraint() {
switch (constraint) {
case HIDDEN_HEADER: {
if (header != null) {
header.setVisibility(GONE);
setHeaderScrollFlags(0);
}
if (body != null) {
body.clearRegisteredTopReachedListeners();
}
break;
}
case PERSISTENT_HEADER: {
if (header != null) {
header.setVisibility(VISIBLE);
setHeaderScrollFlags(0);
}
if (body != null) {
body.clearRegisteredTopReachedListeners();
}
break;
}
case SHOW_HEADER_AT_START: {
if (header != null) {
header.setVisibility(VISIBLE);
setHeaderScrollFlags(SCROLL_FLAG_SCROLL | SCROLL_FLAG_SNAP);
}
if (body != null) {
body.addTopReachedListener(new RecyclerBodyView.TopReachedListener() {
@Override
public void onTopReached(final RecyclerBodyView recyclerBodyView) {
headerContainer.setExpanded(true);
}
});
}
break;
}
case SHOW_HEADER_ON_SCROLL_TO_START: {
if (header != null) {
header.setVisibility(VISIBLE);
setHeaderScrollFlags(SCROLL_FLAG_SCROLL | SCROLL_FLAG_ENTER_ALWAYS |
SCROLL_FLAG_SNAP);
}
if (body != null) {
body.clearRegisteredTopReachedListeners();
}
}
}
}
/**
* Applies the supplied scroll flags to the header.
*
* @param flags
* the flags to apply, 0 to clear all flags
*/
private void setHeaderScrollFlags(final int flags) {
final AppBarLayout.LayoutParams layoutParams = (AppBarLayout.LayoutParams) header
.getLayoutParams();
layoutParams.setScrollFlags(flags);
header.setLayoutParams(layoutParams);
}
/**
* The supported header-body constraints.
*/
protected enum Constraint {
/**
* The header is always hidden, regardless of body scroll events.
*/
HIDDEN_HEADER,
/**
* The header is always shown, regardless of body scroll events.
*/
PERSISTENT_HEADER,
/**
* The header is hidden unless the body is scrolled to the start position.
*/
SHOW_HEADER_AT_START,
/**
* The header is shown whenever the body is scrolled towards the start and hidden whenever
* the body is scrolled towards the end.
*/
SHOW_HEADER_ON_SCROLL_TO_START
}
} | 30.272189 | 137 | 0.722244 |
655a0f953841a4c1a961a83682a96d9835d8a91b | 9,743 | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vividus.email.factory;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.matchesRegex;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.Mockito.when;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.stream.Stream;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.lang3.function.FailablePredicate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import org.vividus.steps.ComparisonRule;
import org.vividus.steps.StringComparisonRule;
class EmailParameterFilterFactoryTests
{
@ParameterizedTest
@CsvSource({
"Test message, EQUAL_TO, Test message, true ",
"Error , EQUAL_TO, Test message, false"
})
void testSubject(String messageSubject, String rule, String subject, boolean passed) throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getSubject()).thenReturn(messageSubject);
performTest(message, EmailParameterFilterFactory.SUBJECT, rule, subject, passed);
}
@ParameterizedTest
@CsvSource({
"2020-06-14T11:47:11.521Z, GREATER_THAN, 1993-04-16T23:10:38.456Z, true",
"1970-01-01T00:00:00.000Z, GREATER_THAN, 2003-10-23T01:20:38.113Z, false"
})
void testSentDate(ZonedDateTime messageDate, String rule, String date, boolean passed) throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getSentDate()).thenReturn(asDate(messageDate));
performTest(message, EmailParameterFilterFactory.SENT_DATE, rule, date, passed);
}
@ParameterizedTest
@CsvSource({
"1993-04-16T23:10:38.456Z, LESS_THAN, 2020-06-14T11:47:11.521Z, true",
"2003-10-23T01:20:38.113Z, LESS_THAN, 1970-01-01T00:00:00.000Z, false"
})
void testReceivedDate(ZonedDateTime messageDate, String rule, String date, boolean passed) throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getReceivedDate()).thenReturn(asDate(messageDate));
performTest(message, EmailParameterFilterFactory.RECEIVED_DATE, rule, date, passed);
}
static Stream<Arguments> dataSetForFromTest()
{
return Stream.of(
arguments(
new Address[] { asAddress("Bob Bob <[email protected]>"), asAddress("John Nhoj <[email protected]>")},
StringComparisonRule.MATCHES.name(),
"(?i).*bob.*,.*John.*", true),
arguments(
new Address[] { asAddress("Pip Pip <[email protected]>")},
StringComparisonRule.MATCHES.name(),
".*,.*", false),
arguments(
new Address[] { asAddress("Bill Llib <[email protected]>"), asAddress("Yo Oy <[email protected]>")},
StringComparisonRule.MATCHES.name(),
".*", false)
);
}
@ParameterizedTest
@MethodSource("dataSetForFromTest")
void testFrom(Address[] messageAddresses, String rule, String addresses, boolean passed) throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getFrom()).thenReturn(messageAddresses);
performTest(message, EmailParameterFilterFactory.FROM, rule, addresses, passed);
}
static Stream<Arguments> dataSetForRecipientsTest()
{
return Stream.of(
arguments(
new Address[] { asAddress("Donald Dlanod <[email protected]>")},
StringComparisonRule.CONTAINS.name(),
"@tut.by", true),
arguments(
new Address[] { asAddress("Chack Kcahc <[email protected]>")},
StringComparisonRule.CONTAINS.name(),
"@yandex.ru", false)
);
}
@ParameterizedTest
@MethodSource("dataSetForRecipientsTest")
void testCcRecipients(Address[] messageAddresses, String rule, String addresses, boolean passed)
throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getRecipients(RecipientType.CC)).thenReturn(messageAddresses);
performTest(message, EmailParameterFilterFactory.CC_RECIPIENTS, rule, addresses, passed);
}
@ParameterizedTest
@MethodSource("dataSetForRecipientsTest")
void testBccRecipients(Address[] messageAddresses, String rule, String addresses, boolean passed)
throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getRecipients(RecipientType.BCC)).thenReturn(messageAddresses);
performTest(message, EmailParameterFilterFactory.BCC_RECIPIENTS, rule, addresses, passed);
}
@ParameterizedTest
@MethodSource("dataSetForRecipientsTest")
void testToRecipients(Address[] messageAddresses, String rule, String addresses, boolean passed)
throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getRecipients(RecipientType.TO)).thenReturn(messageAddresses);
performTest(message, EmailParameterFilterFactory.TO_RECIPIENTS, rule, addresses, passed);
}
static Stream<Arguments> dataSetForReplyToTest()
{
return Stream.of(
arguments(
new Address[] { asAddress("Solomon Northup <[email protected]>")},
StringComparisonRule.DOES_NOT_CONTAIN.name(),
"@dev.by", true),
arguments(
new Address[] { asAddress("Luke Skywalker <[email protected]>")},
StringComparisonRule.DOES_NOT_CONTAIN.name(),
"jedi", false)
);
}
@ParameterizedTest
@MethodSource("dataSetForReplyToTest")
void testReplyTo(Address[] messageAddresses, String rule, String addresses, boolean passed)
throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getReplyTo()).thenReturn(messageAddresses);
performTest(message, EmailParameterFilterFactory.REPLY_TO, rule, addresses, passed);
}
@ParameterizedTest
@CsvSource(value = {
"MATCHES | MATCHES filter is not applicable for SENT_DATE parameter",
"SIMILAR | Unknown rule SIMILAR, please choose among the following rules:"
+ " [DOES_NOT_CONTAIN, IS_EQUAL_TO, GREATER_THAN, LESS_THAN_OR_EQUAL_TO,"
+ " MATCHES, EQUAL_TO, LESS_THAN, GREATER_THAN_OR_EQUAL_TO, CONTAINS, NOT_EQUAL_TO]"
}, delimiter = '|')
void testErrors(String rule, String errorMessage) throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getSentDate()).thenReturn(Date.from(Instant.now()));
FailablePredicate<Message, MessagingException> filter = EmailParameterFilterFactory.SENT_DATE.createFilter(rule,
Instant.now().toString());
Exception exception = assertThrows(IllegalArgumentException.class, () -> filter.test(message));
assertEquals(errorMessage, exception.getMessage());
}
@Test
void testInvalidDateFormat() throws MessagingException
{
Message message = Mockito.mock(Message.class);
when(message.getSentDate()).thenReturn(Date.from(Instant.now()));
FailablePredicate<Message, MessagingException> filter = EmailParameterFilterFactory.SENT_DATE
.createFilter(ComparisonRule.EQUAL_TO.name(), "11:11:11");
Exception exception = assertThrows(IllegalArgumentException.class, () -> filter.test(message));
assertThat(exception.getMessage(), matchesRegex(
"Please use ISO 8601 zone date time format like '\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z'"));
}
private static Date asDate(ZonedDateTime dateTime)
{
return Date.from(dateTime.toInstant());
}
private static void performTest(Message message, EmailParameterFilterFactory filterFactory, String rule,
String input, boolean passed) throws MessagingException
{
FailablePredicate<Message, MessagingException> filter = filterFactory.createFilter(rule, input);
assertEquals(passed, filter.test(message));
}
private static Address asAddress(String addr)
{
try
{
return new InternetAddress(addr);
}
catch (AddressException e)
{
throw new IllegalStateException(e);
}
}
}
| 41.636752 | 120 | 0.677204 |
e7a98dd267fa43417e0029324e50ac6608728654 | 12,856 | /*
* (C) Copyright IBM Corp. 2016,2020
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.whc.deid.providers;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnore;
/** The type Provider type. */
public final class ProviderType implements Serializable {
/** */
private static final long serialVersionUID = -2274165028703699686L;
private static Map<String, ProviderType> registeredTypes = new HashMap<>();
/** The constant NUMERIC. */
public static final ProviderType NUMERIC =
new ProviderType("NUMERIC", "Numeric", "Masks numerical values", TypeClass.NUMERICAL);
/** The constant NAME. */
public static final ProviderType NAME =
new ProviderType("NAME", "Name", "Masks names (with gender preservation) and surnames");
/** The constant EMAIL. */
public static final ProviderType EMAIL = new ProviderType("EMAIL", "E-mail",
"Masks e-mail addresses, supports preservation of domain names");
/** The constant CREDIT_CARD. */
public static final ProviderType CREDIT_CARD = new ProviderType("CREDIT_CARD", "Credit Card",
"Masks credit cards, support vendor preservation");
/** The constant ADDRESS. */
public static final ProviderType ADDRESS = new ProviderType("ADDRESS", "Addresses",
"Masks addresses, supports free text and PO BOX formats");
/** The constant NATIONAL_ID. */
public static final ProviderType NATIONAL_ID =
new ProviderType("NATIONAL_ID", "National ID", "Masks national ID");
/** The constant IP_ADDRESS. */
public static final ProviderType IP_ADDRESS = new ProviderType("IP_ADDRESS", "IP address",
"Masks IP addresses, supports prefix preservation");
/** The constant URL. */
public static final ProviderType URL = new ProviderType("URL", "URLs",
"Masks URLs, supports preservation of domain names and usernames");
/** The constant VIN. */
public static final ProviderType VIN = new ProviderType("VIN", "Vehicle Identification Number",
"Masks VINs, support vendor preservation");
/** The constant LATITUDE_LONGITUDE. */
public static final ProviderType LATITUDE_LONGITUDE = new ProviderType("LATITUDE_LONGITUDE",
"Latitude/Longitude", "Masks latitude/longitude pairs, supports multiple coordinate formats",
TypeClass.NUMERICAL);
/** The constant COUNTRY. */
public static final ProviderType COUNTRY = new ProviderType("COUNTRY", "Country",
"Masks country names, supports masking based on closest countries");
/** The constant DATETIME. */
public static final ProviderType DATETIME = new ProviderType("DATETIME", "Date/Time",
"Masks date/time, supports multiple datetime formats or user-specified ones",
TypeClass.NUMERICAL);
/** The constant CITY. */
public static final ProviderType CITY =
new ProviderType("CITY", "City", "Masks city names, support masking based on closest cities");
/** The constant CONTINENT. */
public static final ProviderType CONTINENT =
new ProviderType("CONTINENT", "Continent", "Masks continent names");
/** The constant ICDv9. */
public static final ProviderType ICDv9 = new ProviderType("ICDV9", "ICDv9",
"Masks ICD v9 codes, supports preservation of chapter and section");
/** The constant ICDv10. */
public static final ProviderType ICDv10 = new ProviderType("ICDV10", "ICDv10",
"Masks ICD v10 codes, supports preservation of chapter and section");
/** The constant PHONE. */
public static final ProviderType PHONE = new ProviderType("PHONE", "Telephone numbers",
"Masks phone numbers, supports preservation of country codes and areas");
/** The constant HOSPITAL. */
public static final ProviderType HOSPITAL = new ProviderType("HOSPITAL",
"Hospitals and medical centers", "Masks names of hospitals and medical centers");
/** The constant RANDOM. */
public static final ProviderType RANDOM =
new ProviderType("RANDOM", "Random", "Changes characters of the value randomly");
/** The constant RELIGION. */
public static final ProviderType RELIGION =
new ProviderType("RELIGION", "Religion", "Masks religion names");
/** The constant MARITAL_STATUS. */
public static final ProviderType MARITAL_STATUS =
new ProviderType("MARITAL_STATUS", "Marital Status", "Masks marital status");
/** The constant RACE */
public static final ProviderType RACE =
new ProviderType("RACE", "Race/Ethnicity", "Masks races and ethnicities");
/** The constant MAC_ADDRESS. */
public static final ProviderType MAC_ADDRESS = new ProviderType("MAC_ADDRESS", "MAC Address",
"Masks MAC addresses, supports vendor preservation");
/** The constant MAINTAIN. */
public static final ProviderType MAINTAIN =
new ProviderType("MAINTAIN", "Maintain", "To maintain original value");
/** The constant CREDIT_CARD_TYPE. */
public static final ProviderType CREDIT_CARD_TYPE =
new ProviderType("CREDIT_CARD_TYPE", "Credit Card type", "Mask credit card vendor names");
/** The constant IBAN. */
public static final ProviderType IBAN = new ProviderType("IBAN", "IBAN", "Masks IBAN values");
/** The constant IMEI. */
public static final ProviderType IMEI =
new ProviderType("IMEI", "IMEI", "Masks IMEI values, supports vendor preservation");
/** The constant SSN_UK. */
public static final ProviderType SSN_UK =
new ProviderType("SSN_UK", "Social Security Number UK", "Masks social security numbers");
/** The constant SSN_US. */
public static final ProviderType SSN_US =
new ProviderType("SSN_US", "Social Security Number US", "Masks social security numbers");
/** The constant OCCUPATION. */
public static final ProviderType OCCUPATION =
new ProviderType("OCCUPATION", "Occupation", "Masks occupations");
/** The constant SWIFT. */
public static final ProviderType SWIFT =
new ProviderType("SWIFT", "SWIFT code", "Masks SWIFT codes, support country preservation");
/** The constant GUID. */
public static final ProviderType GUID =
new ProviderType("GUID", "GUID", "Replaces values with a GUID");
/** The constant EMPTY. */
public static final ProviderType EMPTY =
new ProviderType("EMPTY", "Empty", "Empty", TypeClass.CATEGORICAL, true);
/** The constant ATC. */
public static final ProviderType ATC = new ProviderType("ATC", "ATC codes", "Masks ATC codes");
/** The constant REPLACE. */
public static final ProviderType REPLACE = new ProviderType("REPLACE", "Replace",
"Replaces and preserves parts of the value", TypeClass.CATEGORICAL, false);
/** The constant NULL. */
public static final ProviderType NULL = new ProviderType("NULL", "Null",
"Replaces the value with an empty one", TypeClass.CATEGORICAL, false);
public static final ProviderType HASH =
new ProviderType("HASH", "Hash", "Hashes the value", TypeClass.CATEGORICAL, false);
public static final ProviderType SHIFT =
new ProviderType("SHIFT", "Shift", "Shifts the value", TypeClass.NUMERICAL, false);
public static final ProviderType PSEUDONYM =
new ProviderType("PSEUDONYM", "Pseudonym", "Replaces the value with a pseudonym");
public static final ProviderType GENERALIZE = new ProviderType("GENERALIZE", "Generalize",
"Replaces the value based on generalize ruleset");
public static final ProviderType CONDITIONAL = new ProviderType("CONDITIONAL", "Conditional",
"Replaces the value based on conditional ruleset");
/** The constant STATES_US */
public static final ProviderType STATES_US = new ProviderType("STATES_US", "US States",
"Replaces the US States value", TypeClass.CATEGORICAL, false);
public static final ProviderType GENDER =
new ProviderType("GENDER", "Genders", "Replaces the genders");
public static final ProviderType COUNTY =
new ProviderType("COUNTY", "Counties", "Replaces the county names");
public static final ProviderType FHIR =
new ProviderType("FHIR", "FHIR objects", "Masks FHIR objects");
public static final ProviderType HASHINT = new ProviderType("HASHINT", "Hash and convert to int",
"Hashes the incoming (integer) value and returns an integer (as a string)");
public static final ProviderType ZIPCODE =
new ProviderType("ZIPCODE", "ZIP codes", "Replaces the ZIP codes");
public static final ProviderType MRN =
new ProviderType("MRN", "Medical Record Number", "Medical record number");
public static final ProviderType ORGANIZATION =
new ProviderType("ORGANIZATION", "Organizations", "Masks organizations");
public static final ProviderType GENERIC = new ProviderType("GENERIC", "Generic Json Handler",
"Mask generic json, not conforming to the FHIR standard");
private final String unfriendlyName;
private final String description;
private final String friendlyName;
private final int id;
private final boolean forInternalPurposes;
private final TypeClass typeClass;
/**
* Gets id.
*
* @return the id
*/
@JsonIgnore
public int getId() {
return this.id;
}
/**
* Gets name.
*
* @return the name
*/
public String getName() {
return this.unfriendlyName;
}
/**
* Gets friendly name.
*
* @return the friendly name
*/
public String getFriendlyName() {
return this.friendlyName;
}
private boolean isForInternalPurposes() {
return forInternalPurposes;
}
/**
* Gets description.
*
* @return the description
*/
public String getDescription() {
return this.description;
}
/**
* Gets type class.
*
* @return the type class
*/
public TypeClass getTypeClass() {
return typeClass;
}
private ProviderType(String unfriendlyName, String friendlyName, String description,
TypeClass typeClass, boolean forInternalPurposes) {
this.unfriendlyName = unfriendlyName;
this.friendlyName = friendlyName;
this.description = description;
this.forInternalPurposes = forInternalPurposes;
this.typeClass = typeClass;
this.id = insertType(this);
}
private ProviderType(String name, String friendlyName, String description, TypeClass typeClass) {
this(name, friendlyName, description, typeClass, false);
}
private ProviderType(String name, String friendlyName, String description) {
this(name, friendlyName, description, TypeClass.CATEGORICAL, false);
}
private ProviderType(String name) {
this(name, name, "");
}
@Override
public boolean equals(Object o) {
return !(null == o || !(o instanceof ProviderType))
&& this.unfriendlyName.equals(((ProviderType) o).getName());
}
@Override
public String toString() {
return getName();
}
/**
* Value of provider type.
*
* @param name the name
* @return the provider type
*/
public static synchronized ProviderType valueOf(String name) {
if (!registeredTypes.containsKey(name)) {
return new ProviderType(name);
}
return registeredTypes.get(name);
}
/**
* Public values collection.
*
* @return the collection
*/
public static synchronized Collection<ProviderType> publicValues() {
Collection<ProviderType> providerTypes = new ArrayList<>();
for (ProviderType p : registeredTypes.values()) {
if (!p.isForInternalPurposes()) {
providerTypes.add(p);
}
}
return providerTypes;
}
/**
* Values provider type [ ].
*
* @return the provider type [ ]
*/
public static synchronized ProviderType[] values() {
ProviderType[] values = new ProviderType[registeredTypes.size()];
return registeredTypes.values().toArray(values);
}
/**
* Register type provider type.
*
* @param typeName the type name
* @return the provider type
*/
public static ProviderType registerType(String typeName) {
ProviderType providerType = valueOf(typeName);
if (providerType != null) {
return providerType;
}
return new ProviderType(typeName);
}
private static synchronized int insertType(ProviderType type) {
if (!registeredTypes.containsKey(type.getName())) {
registeredTypes.put(type.getName(), type);
return registeredTypes.size();
}
return registeredTypes.get(type.getName()).getId();
}
@Override
public int hashCode() {
return Objects.hash(unfriendlyName, description, friendlyName, id, forInternalPurposes,
typeClass);
}
}
| 37.923304 | 101 | 0.686061 |
c7f009cb1b975bbf0a3b2dd479dba9eafddfec29 | 2,884 | package gui;
import java.awt.Component;
import java.util.ResourceBundle;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Util {
public static String getGUIText(String key) {
ResourceBundle textBundle = ResourceBundle.getBundle("txtBundles.guiText");
return textBundle.getString(key);
}
public static String getExerciseGroupText(String key) {
ResourceBundle textBundle = ResourceBundle.getBundle("txtBundles.exerciseGroupText");
return textBundle.getString(key);
}
public static String getKeyboardLayoutText(String key) {
return ResourceBundle.getBundle("txtBundles.kbLayoutText").getString(key);
}
/**
* I18n the name of an <tt>Exercise</tt>. The name will be internationalized, if it is not
* a user defined <tt>Exercise</tt>.
* @param key The key entry in <i>exerciseName_Text.properties</i>
* @param groupId The id of the associated <tt>ExerciseGroup</tt>
* @return the name of the <tt>Exercise</tt> in the language of the current locale
*/
public static String getExerciseNameText(String key, int groupId) {
if(groupId == persistence.Constants.userDefExerciseGroup)
return key;
ResourceBundle textBundle = ResourceBundle.getBundle("txtBundles.exerciseNameText");
return textBundle.getString(key);
}
public static int getKeyCodeFromString(String key) {
return java.awt.event.KeyEvent.getExtendedKeyCodeForChar(key.charAt(0));
}
public static String milli2TimeLabel(long time) {
int seconds = (int) time/1000;
int minutes = seconds/60;
seconds = seconds%60;
return String.format("%02d:%02d", minutes, seconds);
}
public static String rateLabel(double rate) {
return String.format("%.2f %%", rate*100);
}
public static String hitsPerMinLabel(int hits, long requiredTime) {
double min = requiredTime/60000.0;
if(min < 0.02) // too short time to evaluate rate
return "0";
int rate = (int) Math.round(hits/min);
return Integer.toString(rate);
}
public static JTextArea makeLabelStyle(String text) {
JTextArea textArea = new JTextArea(text);
textArea.setEditable(false);
textArea.setCursor(null);
textArea.setOpaque(false);
textArea.setFocusable(false);
return textArea;
}
/**
* Surround a {@link java.awt.Component} with a border
* @param c the Component to be wrapped
* @param top the width of the top
* @param left the width of the left side
* @param bottom the width of the bottom
* @param right the width of the right side
* @return the wrapped Component
*/
public static JComponent wrapInEmtpyBorder(Component c,
int top, int left, int bottom, int right) {
JPanel borderedPanel = new JPanel();
borderedPanel.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
borderedPanel.add(c);
return borderedPanel;
}
}
| 31.692308 | 91 | 0.73405 |
a7507850cf7eb1da372858cf735024c7af396141 | 2,088 | package org.stagemonitor.tracing;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.stagemonitor.core.metrics.metrics2.MetricName.name;
public class RequestMonitorTest extends AbstractRequestMonitorTest {
@Test
public void testDeactivated() throws Exception {
doReturn(false).when(corePlugin).isStagemonitorActive();
final SpanContextInformation spanContext = requestMonitor.monitor(createMonitoredRequest());
assertNull(spanContext);
}
@Test
public void testRecordException() throws Exception {
final MonitoredRequest monitoredRequest = createMonitoredRequest();
doThrow(new RuntimeException("test")).when(monitoredRequest).execute();
try {
requestMonitor.monitor(monitoredRequest);
} catch (Exception e) {
}
assertEquals("java.lang.RuntimeException", tags.get("exception.class"));
assertEquals("test", tags.get("exception.message"));
assertNotNull(tags.get("exception.stack_trace"));
}
@Test
public void testInternalMetricsDeactive() throws Exception {
internalMonitoringTestHelper(false);
}
@Test
public void testInternalMetricsActive() throws Exception {
doReturn(true).when(corePlugin).isInternalMonitoringActive();
requestMonitor.monitor(createMonitoredRequest());
verify(registry).timer(name("internal_overhead_request_monitor").build());
}
private void internalMonitoringTestHelper(boolean active) throws Exception {
doReturn(active).when(corePlugin).isInternalMonitoringActive();
requestMonitor.monitor(createMonitoredRequest());
verify(registry, times(active ? 1 : 0)).timer(name("internal_overhead_request_monitor").build());
}
private MonitoredRequest createMonitoredRequest() throws Exception {
return Mockito.spy(new MonitoredMethodRequest(configuration, "test", () -> {
}));
}
}
| 33.142857 | 99 | 0.79023 |
30d519d7ce38aa8d44ba2dcc8e002d66eaa04630 | 297 | package cn.com.xuxiaowei.service;
import cn.com.xuxiaowei.entity.QrtzBlobTriggers;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author 徐晓伟
* @since 2020-09-23
*/
public interface IQrtzBlobTriggersService extends IService<QrtzBlobTriggers> {
}
| 17.470588 | 78 | 0.737374 |
ae8028342e5fd312e1e68ae70b8d88955fc95c47 | 1,414 | package de.hs.mannheim.modUro.model;
import de.hs.mannheim.modUro.reader.CellCountEntry;
import java.util.List;
/**
* @author Markus Gumbel ([email protected])
*/
public class CellCountTimeSeries extends TimeSeries {
public CellCountTimeSeries(List<String> cellTypes,
List<CellCountEntry> cellcountList) {
super("Cell count");
boolean timeSeriesSet = false;
for (String cellType : cellTypes) {
int n = cellcountList.size();
double[] xData = new double[n];
double[] yData = new double[n];
int i = 0;
for (CellCountEntry e : cellcountList) {
double x = e.time;
double y = 0;
if (e.count.containsKey(cellType)) {
y = (double) e.count.get(cellType);
}
xData[i] = x;
yData[i] = y;
i++;
}
if (!timeSeriesSet) {
setTimeSeries(xData);
timeSeriesSet = true;
}
addDataSeries(cellType, yData);
}
double[] sumData = new double[getTimePointsSize()];
int k = 0;
for (CellCountEntry e : cellcountList) {
sumData[k++] = e.count.values().stream().mapToDouble(i -> i.intValue()).sum();
}
addDataSeries("total", sumData);
}
}
| 31.422222 | 90 | 0.514144 |
88cf26325a21204733321d9c021e2d283180ef32 | 3,234 | package com.talanlabs.component.configuration;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.reflect.TypeToken;
import com.talanlabs.component.mapper.IComponentMapperTypeAdapter;
import com.talanlabs.component.mapper.IComponentMapperTypeAdapterFactory;
import com.talanlabs.component.mapper.InstanceFactory;
import com.talanlabs.typeadapters.TypeAdaptersHelper;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ComponentMapperConfigurationBuilder {
private ComponentMapperConfigurationImpl componentMapperConfiguration;
private ComponentMapperConfigurationBuilder() {
super();
this.componentMapperConfiguration = new ComponentMapperConfigurationImpl();
}
public static ComponentMapperConfigurationBuilder newBuilder() {
return new ComponentMapperConfigurationBuilder();
}
public ComponentMapperConfigurationBuilder registerInstanceFactory(Type type, InstanceFactory<?> instanceFactory) {
componentMapperConfiguration.instanceFactories.put(type, instanceFactory);
return this;
}
@SuppressWarnings("unchecked")
public ComponentMapperConfigurationBuilder registerTypeAdapter(Type srcType, Type dstType, IComponentMapperTypeAdapter<?, ?> typeAdapter) {
componentMapperConfiguration.typeAdapterFactories
.add((IComponentMapperTypeAdapterFactory) TypeAdaptersHelper.newTypeFactory(TypeToken.of(srcType), TypeToken.of(dstType), (IComponentMapperTypeAdapter) typeAdapter));
return this;
}
@SuppressWarnings("unchecked")
public ComponentMapperConfigurationBuilder registerTypeHierarchyAdapter(Class<?> srcType, Class<?> dstType, IComponentMapperTypeAdapter<?, ?> typeAdapter) {
componentMapperConfiguration.typeAdapterFactories
.add((IComponentMapperTypeAdapterFactory) TypeAdaptersHelper.newTypeHierarchyFactory(srcType, dstType, (IComponentMapperTypeAdapter) typeAdapter));
return this;
}
public ComponentMapperConfigurationBuilder registerTypeAdapterFactory(IComponentMapperTypeAdapterFactory... typeAdapterFactories) {
componentMapperConfiguration.typeAdapterFactories.addAll(Arrays.asList(typeAdapterFactories));
return this;
}
public IComponentMapperConfiguration build() {
return componentMapperConfiguration;
}
private static class ComponentMapperConfigurationImpl implements IComponentMapperConfiguration {
private final Map<Type, InstanceFactory<?>> instanceFactories = new HashMap<>();
private final List<IComponentMapperTypeAdapterFactory> typeAdapterFactories = new ArrayList<>();
public ComponentMapperConfigurationImpl() {
super();
}
@Override
public Map<Type, InstanceFactory<?>> getInstanceFactoryMap() {
return ImmutableMap.copyOf(instanceFactories);
}
@Override
public List<IComponentMapperTypeAdapterFactory> getTypeAdapterFactories() {
return ImmutableList.copyOf(typeAdapterFactories);
}
}
} | 40.936709 | 182 | 0.769017 |
ab4eb47437ba5c7fc46b7fe5275acc03b1ca5421 | 2,195 | package eu.drus.jpa.unit.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import eu.drus.jpa.unit.api.ExpectedDataSets;
import eu.drus.jpa.unit.api.InitialDataSets;
import eu.drus.jpa.unit.api.JpaUnitRule;
import eu.drus.jpa.unit.api.TransactionMode;
import eu.drus.jpa.unit.api.Transactional;
import eu.drus.jpa.unit.test.model.TestObject;
import eu.drus.jpa.unit.test.model.TestObjectRepository;
@RunWith(CdiTestRunner.class)
public class CdiEnabledJpaUnitIT {
@Rule
public JpaUnitRule rule = new JpaUnitRule(getClass());
@PersistenceContext(unitName = "my-test-unit")
private static EntityManager manager;
@Inject
private TestObjectRepository repo;
@Inject
private EntityManager em;
@Test
public void testEntityManagerIsInjectedAndIsOpen() {
assertNotNull(em);
assertTrue(em.isOpen());
assertTrue(em.getTransaction().isActive());
}
@Test
@InitialDataSets("datasets/initial-data.json")
@ExpectedDataSets("datasets/initial-data.json")
@Transactional(TransactionMode.DISABLED)
public void transactionDisabledTest() {
final TestObject entity = repo.findBy(1L);
assertNotNull(entity);
entity.setValue("Test1");
}
@Test
@InitialDataSets("datasets/initial-data.json")
@ExpectedDataSets("datasets/initial-data.json")
@Transactional(TransactionMode.ROLLBACK)
public void transactionRollbackTest() {
final TestObject entity = repo.findBy(1L);
assertNotNull(entity);
entity.setValue("Test2");
}
@Test
@InitialDataSets("datasets/initial-data.json")
@ExpectedDataSets("datasets/expected-data.json")
@Transactional(TransactionMode.COMMIT)
public void transactionCommitTest() {
final TestObject entity = repo.findBy(1L);
assertNotNull(entity);
entity.setValue("Test3");
}
}
| 27.78481 | 65 | 0.727107 |
b439579e3d9e774885adbe51a5e427ce1a41abaa | 2,596 | package cn.asxuexi.order.controller;
/**
* 微信支付
*
* @author fanjunguo
* @version 2019年8月20日 上午11:22:58
*/
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.asxuexi.order.service.WXPayService;
import cn.asxuexi.order.tool.WXPayUtil;
import cn.asxuexi.tool.JsonData;
@RestController
public class WXPayController {
@Resource
private WXPayService service;
private Logger logger=LoggerFactory.getLogger(this.getClass());
/**
* 微信统一下单接口:先调用此接口向微信下单.返回支付凭证之后,让用户确认支付
*
*
* @author fanjunguo
* @param orderId 待支付的订单号
* @param ip 终端ip地址
* @param openId 用户的微信标识
* @return 返回数据格式如下,具体的返回规则参见微信下单api:
* {
"code": 600,
"data": {
"nonce_str": "wgYmE6iEzhsxrGR3",
"appid": "wx6de372d97ccf6fb8",
"sign": "8AF00407C0FDB7FBEE26DB9E03FF7FB8",
"trade_type": "JSAPI",
"return_msg": "OK",
"result_code": "SUCCESS",
"mch_id": "1548153141",
"return_code": "SUCCESS",
"prepay_id": "wx271641583045957bea9ba5741331162400"
"timeStamp": "15012050151515"
"paySign":"2098hgqp9hg9q8wg9qhg9qwg"
},
"message": "success"
}
*/
@RequestMapping("WXPay/WXPrePay.action")
public JsonData WXPrePay(@RequestParam String orderId,@RequestParam String ip,@RequestParam String openId) {
String regex="\\d{2,3}.\\d{2,3}.\\d{2,3}.\\d{2,3}";
boolean isMatched = Pattern.matches(regex, ip);
if (isMatched) {
return service.WXPrePay(orderId,ip,openId);
} else {
return JsonData.illegalParam();
}
}
/**
* 接受微信异步通知支付结果,并应答
*
* @author fanjunguo
*/
@RequestMapping("WXPay/WXPayNotify.do")
public String notify(HttpServletRequest request) {
try {
service.notify(request);
} catch (Exception e) {
logger.error("微信支付结果回调接口异常:"+e.getMessage(),e);
}
//收到微信通知之后,给微信一个确认答复
Map<String, String> returnXml=new HashMap<String, String>(16);
returnXml.put("return_code", "SUCCESS");
returnXml.put("return_msg", "OK");
try {
return WXPayUtil.mapToXml(returnXml);
} catch (Exception e) {
logger.error("微信回调接口,controller层map转xml异常",e);
return null;
}
}
}
| 26.489796 | 110 | 0.661017 |
a07b284e738a44b17d13453727353821fbd621d7 | 4,716 | /*
* Agave
*
* This file was automatically generated for Agave Platform Client SDK by APIMATIC BETA v2.0 on 05/20/2016
*/
package org.agave.client.models;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
public class AbstractApplicationParameterValue
implements java.io.Serializable {
private static final long serialVersionUID = 5673561302663434676L;
private String defaultValue;
private boolean enquote = false;
private String enumValues;
private int order = 0;
private boolean required = false;
private String type = "string";
private String validator;
private boolean visible = true;
/** GETTER
* The default value for this parameter. The type will be determined by the value.type field.
*/
@JsonGetter("defaultValue")
public String getDefaultValue ( ) {
return this.defaultValue;
}
/** SETTER
* The default value for this parameter. The type will be determined by the value.type field.
*/
@JsonSetter("defaultValue")
public void setDefaultValue (String value) {
this.defaultValue = value;
}
/** GETTER
* Whether the argument value should be surrounded by quotation marks before injection into the wrapper template at runtime
*/
@JsonGetter("enquote")
public boolean getEnquote ( ) {
return this.enquote;
}
/** SETTER
* Whether the argument value should be surrounded by quotation marks before injection into the wrapper template at runtime
*/
@JsonSetter("enquote")
public void setEnquote (boolean value) {
this.enquote = value;
}
/** GETTER
* An array of enumerated object values.
*/
@JsonGetter("enumValues")
public String getEnumValues ( ) {
return this.enumValues;
}
/** SETTER
* An array of enumerated object values.
*/
@JsonSetter("enumValues")
public void setEnumValues (String value) {
this.enumValues = value;
}
/** GETTER
* The order in which this parameter should be printed when generating an execution command for forked execution. This will also be the order in which paramters are returned in the response json.
*/
@JsonGetter("order")
public int getOrder ( ) {
return this.order;
}
/** SETTER
* The order in which this parameter should be printed when generating an execution command for forked execution. This will also be the order in which paramters are returned in the response json.
*/
@JsonSetter("order")
public void setOrder (int value) {
this.order = value;
}
/** GETTER
* Is this parameter required? If visible is false, this must be true.
*/
@JsonGetter("required")
public boolean getRequired ( ) {
return this.required;
}
/** SETTER
* Is this parameter required? If visible is false, this must be true.
*/
@JsonSetter("required")
public void setRequired (boolean value) {
this.required = value;
}
/** GETTER
* The type of this parameter value. (Acceptable values are: "string", "number", "enumeration", "bool", "flag")
*/
@JsonGetter("type")
public String getType ( ) {
return this.type;
}
/** SETTER
* The type of this parameter value. (Acceptable values are: "string", "number", "enumeration", "bool", "flag")
*/
@JsonSetter("type")
public void setType (String value) {
this.type = value;
}
/** GETTER
* The regular expression used to validate this parameter value. For enumerations, separate values with |
*/
@JsonGetter("validator")
public String getValidator ( ) {
return this.validator;
}
/** SETTER
* The regular expression used to validate this parameter value. For enumerations, separate values with |
*/
@JsonSetter("validator")
public void setValidator (String value) {
this.validator = value;
}
/** GETTER
* Should this parameter be visible? If not, there must be a default and it will be required.
*/
@JsonGetter("visible")
public boolean getVisible ( ) {
return this.visible;
}
/** SETTER
* Should this parameter be visible? If not, there must be a default and it will be required.
*/
@JsonSetter("visible")
public void setVisible (boolean value) {
this.visible = value;
}
}
| 31.026316 | 200 | 0.622137 |
52db72ccfdfa7ff0735745eb923ae8bf27aff62f | 6,777 | package org.dbsyncer.web.config;
import org.dbsyncer.biz.ConfigService;
import org.dbsyncer.biz.vo.RestResult;
import org.dbsyncer.common.util.JsonUtil;
import org.dbsyncer.common.util.SHA1Util;
import org.dbsyncer.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author AE86
* @version 1.0.0
* @date 2019/10/23 23:57
*/
@Configuration
@EnableWebSecurity
public class WebAppConfig extends WebSecurityConfigurerAdapter implements AuthenticationProvider, HttpSessionListener {
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* 认证地址
*/
private static final String LOGIN = "/login";
/**
* 认证页面
*/
private static final String LOGIN_PAGE = "/login.html";
/**
* 每个帐号允许同时登录会话数, 默认同一个帐号只能在一个地方登录
*/
private static final int MAXIMUM_SESSIONS = 1;
@Value(value = "${dbsyncer.web.login.username}")
private String username;
@Autowired
private ConfigService configService;
/**
* 登录失败
*
* @return
*/
@Bean
public AuthenticationFailureHandler loginFailHandler() {
return (request, response, e) -> write(response, RestResult.restFail(e.getMessage(), 401));
}
/**
* 登录成功
*
* @return
*/
@Bean
public SavedRequestAwareAuthenticationSuccessHandler loginSuccessHandler() {
return new SavedRequestAwareAuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
Object principal = authentication.getPrincipal();
logger.info("USER : " + principal + " LOGIN SUCCESS ! ");
write(response, RestResult.restSuccess("登录成功!"));
}
};
}
@Bean
public LogoutSuccessHandler logoutHandler() {
return (request, response, authentication) -> {
try {
Object principal = authentication.getPrincipal();
logger.info("USER : {} LOGOUT SUCCESS ! ", principal);
write(response, RestResult.restSuccess("注销成功!"));
} catch (Exception e) {
logger.info("LOGOUT EXCEPTION , e : {}", e.getMessage());
write(response, RestResult.restFail(e.getMessage(), 403));
}
};
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//http.csrf().disable()
// .authorizeRequests()
// .anyRequest().permitAll()
// .and().logout().permitAll();
http.csrf().disable()
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/img/**", "/config/**", "/plugins/**", "/index/version.json").permitAll().anyRequest()
.authenticated()
.and()
.formLogin()
.loginProcessingUrl(LOGIN)
.loginPage(LOGIN_PAGE)
.successHandler(loginSuccessHandler())
.failureHandler(loginFailHandler())
.permitAll()
.and()
.logout()
.permitAll()
.invalidateHttpSession(true).deleteCookies("JSESSIONID").logoutSuccessHandler(logoutHandler())
.and()
.sessionManagement()
.sessionFixation()
.migrateSession()
.maximumSessions(MAXIMUM_SESSIONS);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// 获取表单用户名
String username = (String) authentication.getPrincipal();
// 获取表单用户填写的密码
String password = (String) authentication.getCredentials();
password = SHA1Util.b64_sha1(password);
if (!StringUtil.equals(username, this.username) || !StringUtil.equals(configService.getPassword(), password)) {
throw new BadCredentialsException("对不起,您输入的帐号或密码错误");
}
return new UsernamePasswordAuthenticationToken(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
@Override
public void sessionCreated(HttpSessionEvent se) {
logger.debug("创建会话:{}", se.getSession().getId());
int maxInactiveInterval = se.getSession().getMaxInactiveInterval();
logger.debug(String.valueOf(maxInactiveInterval));
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
logger.debug("销毁会话:{}", se.getSession().getId());
}
/**
* 响应
*
* @param response
* @param result
*/
private void write(HttpServletResponse response, RestResult result) {
PrintWriter out = null;
try {
response.setContentType("application/json;charset=utf-8");
response.setStatus(result.getStatus());
out = response.getWriter();
out.write(JsonUtil.objToJson(result));
out.flush();
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
if (null != out) {
out.close();
}
}
}
} | 35.668421 | 138 | 0.658699 |
95011453ad28a48dd6525910d689c58105c8e439 | 1,030 | package MTV;
import junit.framework.TestCase;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class TestMTV extends TestCase {
public static final String headerLineEnd = " degC degC days mm hours";
public void testLoadFile() throws Exception {
FileInputStream inputFile = new FileInputStream("resource/heathrowdata.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(inputFile));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
br.mark(0);
if (line.equals(headerLineEnd)) {
System.out.println("Whoo-hoo");
}
}
}
public void testSplitDataLine() {
String string = " 1948 1 8.9 3.3 --- 85.0 --- ";
String [] data = string.split("\\s{1,}");
for (String item : data) {
System.out.println(item);
}
}
}
| 23.953488 | 100 | 0.573786 |
28ac07080fa69630f448d3525906d6aa88bfa1cb | 2,380 | /*******************************************************************************
* Copyright 2021-2022 Amit Kumar Mondal
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package com.osgifx.console.util.fx;
import java.util.function.Function;
import org.osgi.util.converter.Converter;
import org.osgi.util.converter.Converters;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.util.Callback;
public final class DTOCellValueFactory<S, T> implements Callback<CellDataFeatures<S, T>, ObservableValue<T>> {
private final Class<T> clazz;
private final String property;
private final Converter converter;
private Function<S, T> nullValueReplacer;
public DTOCellValueFactory(final String property, final Class<T> clazz) {
this(property, clazz, null);
}
public DTOCellValueFactory(final String property, final Class<T> clazz, final Function<S, T> nullValueReplacer) {
this.clazz = clazz;
this.property = property;
this.converter = Converters.standardConverter();
this.nullValueReplacer = nullValueReplacer;
}
@Override
public ObservableValue<T> call(final CellDataFeatures<S, T> celldata) {
final var source = celldata.getValue();
T value = null;
try {
final var field = source.getClass().getField(property);
value = converter.convert(field.get(source)).to(clazz);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
// nothing to do as we have to check for the null value replacer
}
if (value == null && nullValueReplacer != null) {
value = nullValueReplacer.apply(source);
}
return new ReadOnlyObjectWrapper<>(value);
}
}
| 37.777778 | 114 | 0.694958 |
8fd5f3286e69af0619c295c456126b4c2d049b9e | 2,152 | //package com.taymindis.redis.srf4j.impl.lettuce;
//
//import com.redislabs.lettusearch.RediSearchClient;
//import com.redislabs.lettusearch.StatefulRediSearchConnection;
//import com.taymindis.redis.srf4j.intf.SearchFacade;
//import com.taymindis.redis.srf4j.intf.SearchSession;
//import io.lettuce.core.RedisURI;
//
//import java.time.Duration;
//import java.util.List;
//
//public class LettuSentMasterSearchFacadeImpl implements SearchFacade {
//
// private final RediSearchClient core;
// private final RedisURI redisURI;
// private static final String DEFAULT_CLUSTERED_ID = "mymaster";
//
//
//
// public LettuSentMasterSearchFacadeImpl(RedisURI redisURI) {
//// List<RedisURI> sentinels = redisURI.getSentinels();
//// if (sentinels.size() < 3) {
//// throw new IllegalStateException("Min clustered of 3 is required to achieve fail over operation");
//// }
////// Setup Sentinels master discovery
//// RedisURI sentinel = sentinels.get(0);
////
//// RedisURI.Builder builder = RedisURI.Builder
//// .sentinel(sentinel.getHost(),
//// sentinel.getPort(),
//// redisURI.getSentinelMasterId());
////
//// for (int i = 1; i < sentinels.size(); i++) {
//// sentinel = sentinels.get(i);
//// builder.withSentinel(sentinel.getHost(),sentinel.getPort());
//// }
//
//// RedisURI masterSentinelsClusteredUri = builder.build();
// this.core = RediSearchClient.create(redisURI);
// this.redisURI = redisURI;
// }
//
// @Override
// public SearchSession createSession() {
//// RedisSentinelAsyncConnection<String, String> connection = client.connectSentinelAsync();
// StatefulRediSearchConnection connection = core.<String, Object>connect();
// return new LettuSearchSessionImpl(connection);
// }
//
// @Override
// public Object getCore() {
// return core;
// }
//
//
// @Override
// public void close() {
// core.shutdown();
//// core.shutdown(Duration.ofSeconds(10L), Duration.ofSeconds(30L));
// }
//}
| 34.709677 | 113 | 0.633829 |
0ce4e8b131e08e5397826cae0c9ea1423b131eb9 | 15,765 | /*
* Copyright (c) 2016 Zhang Hai <[email protected]>
* All Rights Reserved.
*/
package me.zhanghai.android.douya.navigation.ui;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import androidx.core.view.ViewCompat;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.transitionseverywhere.ChangeTransform;
import com.transitionseverywhere.Fade;
import com.transitionseverywhere.Transition;
import com.transitionseverywhere.TransitionManager;
import com.transitionseverywhere.TransitionSet;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import me.zhanghai.android.douya.R;
import me.zhanghai.android.douya.account.util.AccountUtils;
import me.zhanghai.android.douya.network.api.info.apiv2.SimpleUser;
import me.zhanghai.android.douya.network.api.info.apiv2.User;
import me.zhanghai.android.douya.ui.CrossfadeText;
import me.zhanghai.android.douya.util.DrawableUtils;
import me.zhanghai.android.douya.util.ImageUtils;
import me.zhanghai.android.douya.util.ViewUtils;
public class NavigationHeaderLayout extends FrameLayout {
@BindView(R.id.backdrop)
ImageView mBackdropImage;
@BindView(R.id.scrim)
View mScrimView;
@BindViews({R.id.avatar, R.id.fade_out_avatar,
R.id.recent_one_avatar, R.id.fade_out_recent_one_avatar,
R.id.recent_two_avatar, R.id.fade_out_recent_two_avatar})
ImageView[] mAvatarImages;
@BindView(R.id.avatar)
ImageView mAvatarImage;
@BindView(R.id.fade_out_avatar)
ImageView mFadeOutAvatarImage;
@BindView(R.id.recent_one_avatar)
ImageView mRecentOneAvatarImage;
@BindView(R.id.fade_out_recent_one_avatar)
ImageView mFadeOutRecentOneAvatarImage;
@BindView(R.id.recent_two_avatar)
ImageView mRecentTwoAvatarImage;
@BindView(R.id.fade_out_recent_two_avatar)
ImageView mFadeOutRecentTwoAvatarImage;
@BindView(R.id.info)
LinearLayout mInfoLayout;
@BindView(R.id.name)
TextView mNameText;
@BindView(R.id.description)
TextView mDescriptionText;
@BindView(R.id.dropDown)
ImageView mDropDownImage;
private Adapter mAdapter;
private Listener mListener;
private Account mActiveAccount;
private Account mRecentOneAccount;
private Account mRecentTwoAccount;
private boolean mAccountTransitionRunning;
private boolean mShowingAccountList;
public NavigationHeaderLayout(Context context) {
super(context);
init();
}
public NavigationHeaderLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public NavigationHeaderLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public NavigationHeaderLayout(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
ViewUtils.inflateInto(R.layout.navigation_header_layout, this);
ButterKnife.bind(this);
mBackdropImage.setImageResource(R.drawable.profile_header_backdrop);
ViewCompat.setBackground(mScrimView, DrawableUtils.makeScrimDrawable());
mInfoLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showAccountList(!mShowingAccountList);
}
});
}
public void setAdapter(Adapter adapter) {
mAdapter = adapter;
}
public void setListener(Listener listener) {
mListener = listener;
}
public void bind() {
if (mAdapter == null) {
return;
}
bindActiveUser();
bindRecentUsers();
}
public void onAccountListChanged() {
boolean needReload = !mActiveAccount.equals(AccountUtils.getActiveAccount());
bind();
if (mListener != null && needReload) {
mListener.onAccountTransitionStart();
mListener.onAccountTransitionEnd();
}
}
private void bindActiveUser() {
mActiveAccount = AccountUtils.getActiveAccount();
User user = mAdapter.getUser(mActiveAccount);
if (user != null) {
bindAvatarImage(mAvatarImage, user.getLargeAvatarOrAvatar());
mNameText.setText(user.name);
if (!TextUtils.isEmpty(user.signature)) {
mDescriptionText.setText(user.signature);
} else {
//noinspection deprecation
mDescriptionText.setText(user.uid);
}
} else {
SimpleUser partialUser = mAdapter.getPartialUser(mActiveAccount);
bindAvatarImage(mAvatarImage, null);
mNameText.setText(partialUser.name);
//noinspection deprecation
mDescriptionText.setText(partialUser.uid);
}
mAvatarImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mAccountTransitionRunning) {
return;
}
if (mListener != null) {
mListener.openProfile(mActiveAccount);
}
}
});
mAvatarImage.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mAccountTransitionRunning) {
return false;
}
if (mListener != null) {
mListener.openProfile(mActiveAccount);
}
return true;
}
});
//mBackdropImage.setImageResource();
}
private void bindRecentUsers() {
mRecentOneAccount = AccountUtils.getRecentOneAccount();
bindRecentUser(mRecentOneAvatarImage, mRecentOneAccount);
mRecentTwoAccount = AccountUtils.getRecentTwoAccount();
bindRecentUser(mRecentTwoAvatarImage, mRecentTwoAccount);
}
private void bindRecentUser(ImageView avatarImage, final Account account) {
if (account == null) {
avatarImage.setVisibility(GONE);
return;
}
avatarImage.setVisibility(VISIBLE);
User user = mAdapter.getUser(account);
if (user != null) {
bindAvatarImage(avatarImage, user.getLargeAvatarOrAvatar());
} else {
bindAvatarImage(avatarImage, null);
}
avatarImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
switchToAccountWithTransitionIfNotRunning(account);
}
});
avatarImage.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mAccountTransitionRunning) {
return false;
}
if (mListener != null) {
mListener.openProfile(account);
}
return true;
}
});
}
private void bindAvatarImage(ImageView avatarImage, String avatarUrl) {
if (TextUtils.isEmpty(avatarUrl)) {
avatarImage.setImageResource(R.drawable.avatar_icon_white_inactive_64dp);
avatarImage.setTag(null);
return;
}
for (ImageView anotherAvatarImage : mAvatarImages) {
String anotherAvatarUrl = (String) anotherAvatarImage.getTag();
if (TextUtils.equals(anotherAvatarUrl , avatarUrl)) {
setAvatarImageFrom(avatarImage, anotherAvatarImage);
return;
}
}
ImageUtils.loadNavigationHeaderAvatar(avatarImage, avatarUrl);
}
private void setAvatarImageFrom(ImageView toAvatarImage, ImageView fromAvatarImage) {
if (toAvatarImage == fromAvatarImage) {
return;
}
toAvatarImage.setImageDrawable(fromAvatarImage.getDrawable());
toAvatarImage.setTag(fromAvatarImage.getTag());
}
public void switchToAccountWithTransitionIfNotRunning(Account account) {
if (mAccountTransitionRunning) {
return;
}
showAccountList(false);
if (AccountUtils.isActiveAccount(account)) {
return;
}
AccountUtils.setActiveAccount(account);
if (account.equals(mRecentOneAccount)) {
beginAvatarTransitionFromRecent(mRecentOneAvatarImage);
} else if (account.equals(mRecentTwoAccount)) {
beginAvatarTransitionFromRecent(mRecentTwoAvatarImage);
} else {
beginAvatarTransitionFromNonRecent();
}
bind();
}
private void beginAvatarTransitionFromRecent(ImageView recentAvatarImage) {
beginAvatarTransition(recentAvatarImage, mAvatarImage, null);
}
private void beginAvatarTransitionFromNonRecent() {
beginAvatarTransition(mAvatarImage, mRecentOneAvatarImage,
mRecentTwoAccount != null ? mRecentTwoAvatarImage : null);
}
private void beginAvatarTransition(ImageView moveAvatarOneImage, ImageView moveAvatarTwoImage,
ImageView moveAvatarThreeImage) {
ImageView appearAvatarImage = moveAvatarOneImage;
ImageView disappearAvatarImage = moveAvatarThreeImage != null ? moveAvatarThreeImage
: moveAvatarTwoImage;
ImageView fadeOutDisappearAvatarImage =
disappearAvatarImage == mAvatarImage ? mFadeOutAvatarImage
: disappearAvatarImage == mRecentOneAvatarImage ?
mFadeOutRecentOneAvatarImage : mFadeOutRecentTwoAvatarImage;
TransitionSet transitionSet = new TransitionSet();
int duration = ViewUtils.getLongAnimTime(getContext());
// Will be set on already added and newly added transitions.
transitionSet.setDuration(duration);
// NOTE: TransitionSet.setInterpolator() won't have any effect on platform versions.
// https://code.google.com/p/android/issues/detail?id=195495
transitionSet.setInterpolator(new FastOutSlowInInterpolator());
Fade fadeOutAvatar = new Fade(Fade.OUT);
setAvatarImageFrom(fadeOutDisappearAvatarImage, disappearAvatarImage);
fadeOutDisappearAvatarImage.setVisibility(VISIBLE);
fadeOutAvatar.addTarget(fadeOutDisappearAvatarImage);
transitionSet.addTransition(fadeOutAvatar);
// Make it finish before new avatar arrives.
fadeOutAvatar.setDuration(duration / 2);
Fade fadeInAvatar = new Fade(Fade.IN);
appearAvatarImage.setVisibility(INVISIBLE);
fadeInAvatar.addTarget(appearAvatarImage);
transitionSet.addTransition(fadeInAvatar);
ChangeTransform changeAppearAvatarTransform = new ChangeTransform();
appearAvatarImage.setScaleX(0.8f);
appearAvatarImage.setScaleY(0.8f);
changeAppearAvatarTransform.addTarget(appearAvatarImage);
transitionSet.addTransition(changeAppearAvatarTransform);
addChangeMoveToAvatarTransformToTransitionSet(moveAvatarOneImage, moveAvatarTwoImage,
transitionSet);
if (moveAvatarThreeImage != null) {
addChangeMoveToAvatarTransformToTransitionSet(moveAvatarTwoImage, moveAvatarThreeImage,
transitionSet);
}
CrossfadeText crossfadeText = new CrossfadeText();
crossfadeText.addTarget(mNameText);
crossfadeText.addTarget(mDescriptionText);
transitionSet.addTransition(crossfadeText);
transitionSet.addListener(new Transition.TransitionListenerAdapter() {
@Override
public void onTransitionEnd(Transition transition) {
mAccountTransitionRunning = false;
mInfoLayout.setEnabled(true);
if (mListener != null) {
mListener.onAccountTransitionEnd();
}
}
});
mInfoLayout.setEnabled(false);
TransitionManager.beginDelayedTransition(this, transitionSet);
mAccountTransitionRunning = true;
if (mListener != null) {
mListener.onAccountTransitionStart();
}
fadeOutDisappearAvatarImage.setVisibility(INVISIBLE);
appearAvatarImage.setVisibility(VISIBLE);
appearAvatarImage.setScaleX(1);
appearAvatarImage.setScaleY(1);
resetMoveToAvatarTransform(moveAvatarTwoImage);
if (moveAvatarThreeImage != null) {
resetMoveToAvatarTransform(moveAvatarThreeImage);
}
}
private void addChangeMoveToAvatarTransformToTransitionSet(ImageView moveFromAvatarImage,
ImageView moveToAvatarImage,
TransitionSet transitionSet) {
ChangeTransform changeMoveToAvatarTransform = new ChangeTransform();
moveToAvatarImage.setX(moveFromAvatarImage.getLeft()
+ (moveFromAvatarImage.getWidth() - moveToAvatarImage.getWidth()) / 2);
moveToAvatarImage.setY(moveFromAvatarImage.getTop()
+ (moveFromAvatarImage.getHeight() - moveToAvatarImage.getHeight()) / 2);
moveToAvatarImage.setScaleX((float) ViewUtils.getWidthExcludingPadding(moveFromAvatarImage)
/ ViewUtils.getWidthExcludingPadding(moveToAvatarImage));
moveToAvatarImage.setScaleY((float) ViewUtils.getHeightExcludingPadding(moveFromAvatarImage)
/ ViewUtils.getHeightExcludingPadding(moveToAvatarImage));
changeMoveToAvatarTransform.addTarget(moveToAvatarImage);
transitionSet.addTransition(changeMoveToAvatarTransform);
}
private void resetMoveToAvatarTransform(ImageView moveToAvatarImage) {
moveToAvatarImage.setTranslationX(0);
moveToAvatarImage.setTranslationY(0);
moveToAvatarImage.setScaleX(1);
moveToAvatarImage.setScaleY(1);
}
public boolean isShowingAccountList() {
return mShowingAccountList;
}
public void setShowingAccountList(boolean showing) {
showAccountList(showing, false);
}
private void showAccountList(boolean show, boolean animate) {
if (mShowingAccountList == show) {
return;
}
if (mListener == null) {
return;
}
float rotation = show ? 180 : 0;
if (animate) {
mDropDownImage.animate()
.rotation(rotation)
.setDuration(ViewUtils.getShortAnimTime(getContext()))
.start();
} else {
mDropDownImage.setRotation(rotation);
}
mListener.showAccountList(show);
mShowingAccountList = show;
}
private void showAccountList(boolean show) {
showAccountList(show, true);
}
public interface Adapter {
SimpleUser getPartialUser(Account account);
User getUser(Account account);
}
public interface Listener {
void openProfile(Account account);
void showAccountList(boolean show);
void onAccountTransitionStart();
void onAccountTransitionEnd();
}
}
| 35.189732 | 100 | 0.656391 |
6f6949c2926fcea1f9b40864d755a20a974098c7 | 9,815 | /*
* 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.brooklyn.launcher;
import java.io.File;
import java.util.Set;
import java.util.zip.ZipFile;
import org.apache.brooklyn.api.mgmt.ManagementContext;
import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
import org.apache.brooklyn.api.mgmt.rebind.RebindManager;
import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
import org.apache.brooklyn.core.entity.Entities;
import org.apache.brooklyn.core.internal.BrooklynProperties;
import org.apache.brooklyn.core.mgmt.ha.OsgiManager;
import org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore;
import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils;
import org.apache.brooklyn.core.mgmt.persist.PersistMode;
import org.apache.brooklyn.core.mgmt.persist.PersistenceObjectStore;
import org.apache.brooklyn.core.mgmt.rebind.PersistenceExceptionHandlerImpl;
import org.apache.brooklyn.core.mgmt.rebind.RebindManagerImpl;
import org.apache.brooklyn.core.server.BrooklynServerConfig;
import org.apache.brooklyn.core.server.BrooklynServerPaths;
import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
import org.apache.brooklyn.test.Asserts;
import org.apache.brooklyn.util.collections.MutableSet;
import org.apache.brooklyn.util.core.ResourceUtils;
import org.apache.brooklyn.util.core.file.ArchiveUtils;
import org.apache.brooklyn.util.core.osgi.BundleMaker;
import org.apache.brooklyn.util.exceptions.Exceptions;
import org.apache.brooklyn.util.javalang.JavaClassNames;
import org.apache.brooklyn.util.os.Os;
import org.apache.brooklyn.util.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.common.collect.Sets;
public class CleanOrphanedLocationsIntegrationTest extends AbstractCleanOrphanedStateTest {
private static final Logger LOG = LoggerFactory.getLogger(CleanOrphanedLocationsIntegrationTest.class);
private final String PERSISTED_STATE_PATH_WITH_ORPHANED_LOCATIONS = "/orphaned-locations-test-data/data-with-orphaned-locations";
private final String PERSISTED_STATE_PATH_WITH_MULTIPLE_LOCATIONS_OCCURRENCE = "/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests";
private final String PERSISTED_STATE_PATH_WITHOUT_ORPHANED_LOCATIONS = "/orphaned-locations-test-data/data-without-orphaned-locations";
private String persistenceDirWithOrphanedLocations;
private String persistenceDirWithoutOrphanedLocations;
private String persistenceDirWithMultipleLocationsOccurrence;
private File destinationDir;
private Set<ManagementContext> mgmts;
private ManagementContext mgmt;
private String copyResourcePathToTempPath(String resourcePath) {
BundleMaker bm = new BundleMaker(ResourceUtils.create(this));
bm.setDefaultClassForLoading(CleanOrphanedLocationsIntegrationTest.class);
File jar = bm.createJarFromClasspathDir(resourcePath);
File output = Os.newTempDir("brooklyn-test-resouce-from-"+resourcePath);
try {
ArchiveUtils.extractZip(new ZipFile(jar), output.getAbsolutePath());
return output.getAbsolutePath();
} catch (Exception e) {
throw Exceptions.propagate(e);
}
}
@BeforeMethod(alwaysRun = true)
@Override
public void setUp() throws Exception {
super.setUp();
persistenceDirWithOrphanedLocations = copyResourcePathToTempPath(PERSISTED_STATE_PATH_WITH_ORPHANED_LOCATIONS);
persistenceDirWithoutOrphanedLocations = copyResourcePathToTempPath(PERSISTED_STATE_PATH_WITHOUT_ORPHANED_LOCATIONS);
persistenceDirWithMultipleLocationsOccurrence = copyResourcePathToTempPath(PERSISTED_STATE_PATH_WITH_MULTIPLE_LOCATIONS_OCCURRENCE);
destinationDir = Os.newTempDir(getClass());
mgmts = Sets.newLinkedHashSet();
}
@AfterMethod(alwaysRun = true)
@Override
public void tearDown() throws Exception {
super.tearDown();
// contents of method copied from BrooklynMgmtUnitTestSupport
for (ManagementContext mgmt : mgmts) {
try {
if (mgmt != null) Entities.destroyAll(mgmt);
} catch (Throwable t) {
LOG.error("Caught exception in tearDown method", t);
// we should fail here, except almost always that masks a primary failure in the test itself,
// so it would be extremely unhelpful to do so. if we could check if test has not already failed,
// that would be ideal, but i'm not sure if that's possible with TestNG. ?
}
}
if (destinationDir != null) Os.deleteRecursively(destinationDir);
mgmts.clear();
}
private void initManagementContextAndPersistence(String persistenceDir) {
BrooklynProperties brooklynProperties = BrooklynProperties.Factory.builderDefault().build();
brooklynProperties.put(BrooklynServerConfig.MGMT_BASE_DIR.getName(), "");
brooklynProperties.put(BrooklynServerConfig.OSGI_CACHE_DIR, "target/" + BrooklynServerConfig.OSGI_CACHE_DIR.getDefaultValue());
mgmt = LocalManagementContextForTests.newInstance(brooklynProperties);
mgmts.add(mgmt);
persistenceDir = BrooklynServerPaths.newMainPersistencePathResolver(brooklynProperties).dir(persistenceDir).resolve();
PersistenceObjectStore objectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(mgmt, null, persistenceDir,
PersistMode.AUTO, HighAvailabilityMode.HOT_STANDBY);
BrooklynMementoPersisterToObjectStore persister = new BrooklynMementoPersisterToObjectStore(
objectStore, mgmt);
RebindManager rebindManager = mgmt.getRebindManager();
PersistenceExceptionHandler persistenceExceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
((RebindManagerImpl) rebindManager).setPeriodicPersistPeriod(Duration.ONE_SECOND);
rebindManager.setPersister(persister, persistenceExceptionHandler);
rebindManager.forcePersistNow(false, null);
}
@Test
public void testSelectionWithOrphanedLocationsInData() throws Exception {
final Set<String> orphanedLocations = MutableSet.of(
"msyp655po0",
"ppamsemxgo"
);
initManagementContextAndPersistence(persistenceDirWithOrphanedLocations);
BrooklynMementoRawData mementoRawData = mgmt.getRebindManager().retrieveMementoRawData();
assertTransformDeletes(new Deletions().locations(orphanedLocations), mementoRawData);
}
@Test
public void testSelectionWithoutOrphanedLocationsInData() throws Exception {
initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
BrooklynMementoRawData mementoRawData = mgmt.getRebindManager().retrieveMementoRawData();
assertTransformIsNoop(mementoRawData);
}
@Test
public void testCleanedCopiedPersistedState() throws Exception {
LOG.info(JavaClassNames.niceClassAndMethod()+" taking persistence from "+persistenceDirWithOrphanedLocations);
BrooklynLauncher launcher = BrooklynLauncher.newInstance()
.restServer(false)
.brooklynProperties(OsgiManager.USE_OSGI, false)
.persistMode(PersistMode.AUTO)
.persistenceDir(persistenceDirWithOrphanedLocations)
.highAvailabilityMode(HighAvailabilityMode.DISABLED);
ManagementContext mgmtForCleaning = null;
try {
launcher.cleanOrphanedState(destinationDir.getAbsolutePath(), null);
mgmtForCleaning = launcher.getManagementContext();
} finally {
launcher.terminate();
if (mgmtForCleaning != null) Entities.destroyAll(mgmtForCleaning);
}
initManagementContextAndPersistence(destinationDir.getAbsolutePath());
BrooklynMementoRawData mementoRawDataFromCleanedState = mgmt.getRebindManager().retrieveMementoRawData();
Asserts.assertTrue(mementoRawDataFromCleanedState.getEntities().size() != 0);
Asserts.assertTrue(mementoRawDataFromCleanedState.getLocations().size() != 0);
initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
BrooklynMementoRawData mementoRawData = mgmt.getRebindManager().retrieveMementoRawData();
assertRawData(mementoRawData, mementoRawDataFromCleanedState);
}
@Test
public void testMultipleLocationOccurrenceInEntity() throws Exception {
initManagementContextAndPersistence(persistenceDirWithMultipleLocationsOccurrence);
BrooklynMementoRawData mementoRawData = mgmt.getRebindManager().retrieveMementoRawData();
assertTransformIsNoop(mementoRawData);
}
}
| 48.589109 | 164 | 0.757106 |
099aa5dff582013e79e463eb1c83a2326b05a9be | 2,716 | package org.liveontologies.puli.pinpointing;
/*-
* #%L
* Proof Utility Library
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2014 - 2021 Live Ontologies 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.
* #L%
*/
import org.liveontologies.puli.AxiomPinpointingInference;
import org.liveontologies.puli.Prover;
/**
* Collection of static methods for working with
* {@link AxiomPinpointingListener}s
*
* @author Yevgeny Kazakov
*
*/
public class AxiomPinpointingListeners {
@SafeVarargs
public static <A> AxiomPinpointingListener<A> combine(
AxiomPinpointingListener<A>... listeners) {
return new AxiomPinpointingCombinedListener<>(listeners);
}
public static <A> AxiomPinpointingListener<A> adapt(
final UsefulAxiomListener<A> listener) {
return new UsefulAxiomListenerAdapter<A>(listener);
}
public static <A> AxiomPinpointingListener<A> adapt(
final JustificationListener<A> listener) {
return new JustificationListenerAdapter<A>(listener);
}
public static <A> AxiomPinpointingListener<A> adapt(
final RepairListener<A> listener) {
return new RepairListenerAdapter<A>(listener);
}
public static <Q, A> ProverAxiomPinpointingEnumerationFactory<Q, A> appendListener(
final ProverAxiomPinpointingEnumerationFactory<Q, A> factory,
final AxiomPinpointingListener<A> extraListener) {
return new ProverAxiomPinpointingEnumerationFactory<Q, A>() {
@Override
public String toString() {
return factory.toString();
}
@Override
public <I extends AxiomPinpointingInference<?, ? extends A>> AxiomPinpointingEnumerator<Q, A> create(
Prover<? super Q, ? extends I> prover,
AxiomPinpointingInterruptMonitor monitor) {
return appendListener(factory.create(prover, monitor),
extraListener);
}
};
}
public static <Q, A> AxiomPinpointingEnumerator<Q, A> appendListener(
final AxiomPinpointingEnumerator<Q, A> enumerator,
final AxiomPinpointingListener<A> extraListener) {
return new AxiomPinpointingEnumerator<Q, A>() {
@Override
public void enumerate(Q query,
AxiomPinpointingListener<A> listener) {
enumerator.enumerate(query, combine(listener, extraListener));
}
};
}
}
| 28 | 104 | 0.73785 |
52aa226cb7d5f2bcae02b8e8745cc579bde7f68f | 5,674 | package de.csbdresden.stardist;
import java.net.URL;
import java.util.List;
import org.scijava.app.StatusService;
import org.scijava.command.CommandService;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.ui.DialogPrompt.MessageType;
import org.scijava.ui.UIService;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.PointRoi;
import ij.gui.PolygonRoi;
import ij.gui.Roi;
import ij.plugin.frame.RoiManager;
import ij.process.ImageProcessor;
import net.imagej.Dataset;
import net.imagej.DatasetService;
import net.imagej.axis.Axes;
import net.imagej.axis.AxisType;
import net.imglib2.img.Img;
import net.imglib2.img.display.imagej.ImageJFunctions;
public abstract class StarDist2DBase {
@Parameter
protected LogService log;
@Parameter
protected UIService ui;
@Parameter
protected CommandService command;
@Parameter
protected DatasetService dataset;
@Parameter
protected StatusService status;
// ---------
protected boolean exportPointRois = false;
protected boolean exportBboxRois = false;
protected RoiManager roiManager = null;
protected ImagePlus labelImage = null;
protected int labelId = 0;
protected long labelCount = 0;
protected static final int MAX_LABEL_ID = 65535;
// ---------
protected URL getResource(final String name) {
return StarDist2DBase.class.getClassLoader().getResource(name);
}
protected boolean showError(String msg) {
ui.showDialog(msg, MessageType.ERROR_MESSAGE);
// log.error(msg);
return false;
}
// ---------
protected void export(String outputType, Candidates polygons, int framePosition) {
switch (outputType) {
case Opt.OUTPUT_ROI_MANAGER:
exportROIs(polygons, framePosition);
break;
case Opt.OUTPUT_LABEL_IMAGE:
exportLabelImage(polygons, framePosition);
break;
case Opt.OUTPUT_BOTH:
exportROIs(polygons, framePosition);
exportLabelImage(polygons, framePosition);
break;
case Opt.OUTPUT_POLYGONS:
exportPolygons(polygons);
break;
default:
showError(String.format("Unknown output type \"%s\"", outputType));
}
}
protected void exportROIs(Candidates polygons, int framePosition) {
if (roiManager == null) {
IJ.run("ROI Manager...", "");
roiManager = RoiManager.getInstance();
roiManager.reset(); // clear all rois
}
for (final int i : polygons.getWinner()) {
final PolygonRoi polyRoi = Utils.toPolygonRoi(polygons.getPolygon(i));
// if (framePosition > 0) polyRoi.setPosition(0, 0, framePosition);
if (framePosition > 0) polyRoi.setPosition(framePosition);
roiManager.addRoi(polyRoi);
if (exportPointRois) {
final Point2D o = polygons.getOrigin(i);
final PointRoi pointRoi = new PointRoi(o.x, o.y);
// if (framePosition > 0) pointRoi.setPosition(0, 0, framePosition);
if (framePosition > 0) pointRoi.setPosition(framePosition);
roiManager.addRoi(pointRoi);
}
if (exportBboxRois) {
final Box2D bbox = polygons.getBbox(i);
final Roi bboxRoi = new Roi(bbox.xmin, bbox.ymin, bbox.xmax - bbox.xmin, bbox.ymax - bbox.ymin);
// if (framePosition > 0) bboxRoi.setPosition(0, 0, framePosition);
if (framePosition > 0) bboxRoi.setPosition(framePosition);
roiManager.addRoi(bboxRoi);
}
}
}
protected void exportLabelImage(Candidates polygons, int framePosition) {
if (labelImage == null)
labelImage = createLabelImage();
if (framePosition > 0)
labelImage.setT(framePosition);
final ImageProcessor ip = labelImage.getProcessor();
final List<Integer> winner = polygons.getWinner();
final int numWinners = winner.size();
// winners are ordered by score -> draw from last to first to give priority to higher scores in case of overlaps
for (int i = numWinners-1; i >= 0; i--) {
final PolygonRoi polyRoi = Utils.toPolygonRoi(polygons.getPolygon(winner.get(i)));
ip.setColor(1 + ((labelId + i) % MAX_LABEL_ID));
ip.fill(polyRoi);
}
labelCount += numWinners;
labelId = (labelId + numWinners) % MAX_LABEL_ID;
}
abstract protected void exportPolygons(Candidates polygons);
abstract protected ImagePlus createLabelImage();
protected Dataset labelImageToDataset(String outputType) {
if (outputType.equals(Opt.OUTPUT_LABEL_IMAGE) || outputType.equals(Opt.OUTPUT_BOTH)) {
if (labelCount > MAX_LABEL_ID) {
log.error(String.format("Found more than %d segments -> label image does contain some repetitive IDs.\n(\"%s\" output instead does not have this problem).", MAX_LABEL_ID, Opt.OUTPUT_ROI_MANAGER));
}
// IJ.run(labelImage, "glasbey inverted", "");
final boolean isTimelapse = labelImage.getNFrames() > 1;
final Img labelImg = (Img) ImageJFunctions.wrap(labelImage);
final AxisType[] axes = isTimelapse ? new AxisType[]{Axes.X, Axes.Y, Axes.TIME} : new AxisType[]{Axes.X, Axes.Y};
return Utils.raiToDataset(dataset, Opt.LABEL_IMAGE, labelImg, axes);
} else {
return null;
}
}
}
| 36.606452 | 212 | 0.630067 |
8292171969bbf4a0fc3b7efcabac9b07a6b99436 | 2,011 | package com.leetcode.strings.easy;
// You are given a string allowed consisting of distinct characters and an array
// of strings words. A string is consistent if all characters in the string appear
// in the string allowed.
//
// Return the number of consistent strings in the array words.
//
//
// Example 1:
//
//
// Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
// Output: 2
// Explanation: Strings "aaab" and "baa" are consistent since they only contain c
// haracters 'a' and 'b'.
//
//
// Example 2:
//
//
// Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
// Output: 7
// Explanation: All strings are consistent.
//
//
// Example 3:
//
//
// Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
// Output: 4
// Explanation: Strings "cc", "acd", "ac", and "d" are consistent.
//
//
//
// Constraints:
//
//
// 1 <= words.length <= 104
// 1 <= allowed.length <= 26
// 1 <= words[i].length <= 10
// The characters in allowed are distinct.
// words[i] and allowed contain only lowercase English letters.
//
// Related Topics String
// 👍 60 👎 3
// leetcode submit region begin(Prohibit modification and deletion)
/*
O(n) Runtime: 7 ms, faster than 81.02% of Java online submissions for Count the Number of Consistent Strings.
O(1) Memory Usage: 39.4 MB, less than 98.10% of Java online submissions for Count the Number of Consistent Strings
*/
public class CountTheNumberOfConsistentStrings_1684 {
public int countConsistentStrings(String allowed, String[] words) {
boolean[] isCharAllowed = new boolean[26];
for (int i = 0; i < allowed.length(); i++) {
isCharAllowed[allowed.charAt(i) - 'a'] = true;
}
int result = 0;
for (String word : words) {
result++;
for (int i = 0; i < word.length(); i++) {
if (!isCharAllowed[word.charAt(i) - 'a']) {
result--;
break;
}
}
}
return result;
}
}
// leetcode submit region end(Prohibit modification and deletion)
| 26.813333 | 115 | 0.630532 |
62415a579360462f5f28386e863667777389d28d | 512 | package sa.site.lab.petstore.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import sa.site.lab.petstore.domain.Animal;
public interface AnimalController
{
String findById(int id,Model model);
String findAll(Model model);
String add(Model model);
String create(Animal animal);
String delete (@PathVariable int id);
String edit(@PathVariable int id, Model model);
String update(@PathVariable int id, Animal animal);
}
| 25.6 | 60 | 0.753906 |
d39ac8511dbc9f2af90ba643916956568603a905 | 3,889 | package com.ktfootball.www.dao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table GAMES.
*/
public class Games {
private Long id;
private String game_id;
private String game_enter_users_count;
private String name;
private String time_start;
private String time_end;
private String avatar;
private String introduction;
private String location;
private String ktb;
private String enter_time_start;
private String enter_time_end;
private String place;
private String country;
private String city;
public Games() {
}
public Games(Long id) {
this.id = id;
}
public Games(Long id, String game_id, String game_enter_users_count, String name, String time_start, String time_end, String avatar, String introduction, String location, String ktb, String enter_time_start, String enter_time_end, String place, String country, String city) {
this.id = id;
this.game_id = game_id;
this.game_enter_users_count = game_enter_users_count;
this.name = name;
this.time_start = time_start;
this.time_end = time_end;
this.avatar = avatar;
this.introduction = introduction;
this.location = location;
this.ktb = ktb;
this.enter_time_start = enter_time_start;
this.enter_time_end = enter_time_end;
this.place = place;
this.country = country;
this.city = city;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGame_id() {
return game_id;
}
public void setGame_id(String game_id) {
this.game_id = game_id;
}
public String getGame_enter_users_count() {
return game_enter_users_count;
}
public void setGame_enter_users_count(String game_enter_users_count) {
this.game_enter_users_count = game_enter_users_count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTime_start() {
return time_start;
}
public void setTime_start(String time_start) {
this.time_start = time_start;
}
public String getTime_end() {
return time_end;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getKtb() {
return ktb;
}
public void setKtb(String ktb) {
this.ktb = ktb;
}
public String getEnter_time_start() {
return enter_time_start;
}
public void setEnter_time_start(String enter_time_start) {
this.enter_time_start = enter_time_start;
}
public String getEnter_time_end() {
return enter_time_end;
}
public void setEnter_time_end(String enter_time_end) {
this.enter_time_end = enter_time_end;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
| 22.74269 | 279 | 0.63281 |
79d0c985558af1b39cb7b6de79f876a5dbda0f31 | 10,381 | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xssf.usermodel;
import java.awt.*;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.FontUnderline;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTDrawing;
/**
* @author Yegor Kozlov
*/
public class TestXSSFDrawing extends TestCase {
public void testRead(){
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx");
XSSFSheet sheet = wb.getSheetAt(0);
//the sheet has one relationship and it is XSSFDrawing
List<POIXMLDocumentPart> rels = sheet.getRelations();
assertEquals(1, rels.size());
assertTrue(rels.get(0) instanceof XSSFDrawing);
XSSFDrawing drawing = (XSSFDrawing)rels.get(0);
//sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing
assertSame(drawing, sheet.createDrawingPatriarch());
String drawingId = drawing.getPackageRelationship().getId();
//there should be a relation to this drawing in the worksheet
assertTrue(sheet.getCTWorksheet().isSetDrawing());
assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(6, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFPicture);
assertTrue(shapes.get(1) instanceof XSSFPicture);
assertTrue(shapes.get(2) instanceof XSSFPicture);
assertTrue(shapes.get(3) instanceof XSSFPicture);
assertTrue(shapes.get(4) instanceof XSSFSimpleShape);
assertTrue(shapes.get(5) instanceof XSSFPicture);
for(XSSFShape sh : shapes) assertNotNull(sh.getAnchor());
}
public void testNew() throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
//multiple calls of createDrawingPatriarch should return the same instance of XSSFDrawing
XSSFDrawing dr1 = sheet.createDrawingPatriarch();
XSSFDrawing dr2 = sheet.createDrawingPatriarch();
assertSame(dr1, dr2);
List<POIXMLDocumentPart> rels = sheet.getRelations();
assertEquals(1, rels.size());
assertTrue(rels.get(0) instanceof XSSFDrawing);
XSSFDrawing drawing = (XSSFDrawing)rels.get(0);
String drawingId = drawing.getPackageRelationship().getId();
//there should be a relation to this drawing in the worksheet
assertTrue(sheet.getCTWorksheet().isSetDrawing());
assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
XSSFConnector c1= drawing.createConnector(new XSSFClientAnchor(0,0,0,0,0,0,2,2));
c1.setLineWidth(2.5);
c1.setLineStyle(1);
XSSFShapeGroup c2 = drawing.createGroup(new XSSFClientAnchor(0,0,0,0,0,0,5,5));
XSSFSimpleShape c3 = drawing.createSimpleShape(new XSSFClientAnchor(0,0,0,0,2,2,3,4));
c3.setText(new XSSFRichTextString("Test String"));
c3.setFillColor(128, 128, 128);
XSSFTextBox c4 = drawing.createTextbox(new XSSFClientAnchor(0,0,0,0,4,4,5,6));
XSSFRichTextString rt = new XSSFRichTextString("Test String");
rt.applyFont(0, 5, wb.createFont());
rt.applyFont(5, 6, wb.createFont());
c4.setText(rt);
c4.setNoFill(true);
assertEquals(4, drawing.getCTDrawing().sizeOfTwoCellAnchorArray());
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(4, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFConnector);
assertTrue(shapes.get(1) instanceof XSSFShapeGroup);
assertTrue(shapes.get(2) instanceof XSSFSimpleShape);
assertTrue(shapes.get(3) instanceof XSSFSimpleShape); //
// Save and re-load it
wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
sheet = wb.getSheetAt(0);
// Check
dr1 = sheet.createDrawingPatriarch();
CTDrawing ctDrawing = dr1.getCTDrawing();
// Connector, shapes and text boxes are all two cell anchors
assertEquals(0, ctDrawing.sizeOfAbsoluteAnchorArray());
assertEquals(0, ctDrawing.sizeOfOneCellAnchorArray());
assertEquals(4, ctDrawing.sizeOfTwoCellAnchorArray());
shapes = dr1.getShapes();
assertEquals(4, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFConnector);
assertTrue(shapes.get(1) instanceof XSSFShapeGroup);
assertTrue(shapes.get(2) instanceof XSSFSimpleShape);
assertTrue(shapes.get(3) instanceof XSSFSimpleShape); //
// Ensure it got the right namespaces
String xml = ctDrawing.toString();
assertTrue(xml.contains("xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\""));
assertTrue(xml.contains("xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\""));
}
public void testMultipleDrawings(){
XSSFWorkbook wb = new XSSFWorkbook();
for (int i = 0; i < 3; i++) {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
}
OPCPackage pkg = wb.getPackage();
assertEquals(3, pkg.getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size());
}
public void testClone() throws Exception{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx");
XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFSheet sheet2 = wb.cloneSheet(0);
//the source sheet has one relationship and it is XSSFDrawing
List<POIXMLDocumentPart> rels1 = sheet1.getRelations();
assertEquals(1, rels1.size());
assertTrue(rels1.get(0) instanceof XSSFDrawing);
List<POIXMLDocumentPart> rels2 = sheet2.getRelations();
assertEquals(1, rels2.size());
assertTrue(rels2.get(0) instanceof XSSFDrawing);
XSSFDrawing drawing1 = (XSSFDrawing)rels1.get(0);
XSSFDrawing drawing2 = (XSSFDrawing)rels2.get(0);
assertNotSame(drawing1, drawing2); // drawing2 is a clone of drawing1
List<XSSFShape> shapes1 = drawing1.getShapes();
List<XSSFShape> shapes2 = drawing2.getShapes();
assertEquals(shapes1.size(), shapes2.size());
for(int i = 0; i < shapes1.size(); i++){
XSSFShape sh1 = (XSSFShape)shapes1.get(i);
XSSFShape sh2 = (XSSFShape)shapes2.get(i);
assertTrue(sh1.getClass() == sh2.getClass());
assertEquals(sh1.getShapeProperties().toString(), sh2.getShapeProperties().toString());
}
}
/**
* ensure that rich text attributes defined in a XSSFRichTextString
* are passed to XSSFSimpleShape.
*
* See Bugzilla 52219.
*/
public void testRichText(){
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFRichTextString rt = new XSSFRichTextString("Test String");
XSSFFont font = wb.createFont();
font.setColor(new XSSFColor(new Color(0, 128, 128)));
font.setItalic(true);
font.setBold(true);
font.setUnderline(FontUnderline.SINGLE);
rt.applyFont(font);
shape.setText(rt);
CTTextParagraph pr = shape.getCTShape().getTxBody().getPArray(0);
assertEquals(1, pr.sizeOfRArray());
CTTextCharacterProperties rPr = pr.getRArray(0).getRPr();
assertEquals(true, rPr.getB());
assertEquals(true, rPr.getI());
assertEquals(STTextUnderlineType.SNG, rPr.getU());
assertTrue(Arrays.equals(
new byte[]{0, (byte)128, (byte)128} ,
rPr.getSolidFill().getSrgbClr().getVal()));
}
/**
* test that anchor is not null when reading shapes from existing drawings
*/
public void testReadAnchors(){
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor1 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4);
XSSFShape shape1 = drawing.createTextbox(anchor1);
XSSFClientAnchor anchor2 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 5);
XSSFShape shape2 = drawing.createTextbox(anchor2);
int pictureIndex= wb.addPicture(new byte[]{}, XSSFWorkbook.PICTURE_TYPE_PNG);
XSSFClientAnchor anchor3 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 6);
XSSFShape shape3 = drawing.createPicture(anchor3, pictureIndex);
wb = XSSFTestDataSamples.writeOutAndReadBack(wb);
sheet = wb.getSheetAt(0);
drawing = sheet.createDrawingPatriarch();
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(shapes.get(0).getAnchor(), anchor1);
assertEquals(shapes.get(1).getAnchor(), anchor2);
assertEquals(shapes.get(2).getAnchor(), anchor3);
}
}
| 42.02834 | 118 | 0.667951 |
a0a39131030219f57d723d42863e1acead0beff4 | 16,126 | package eu.woolplatform.utils.json;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import eu.woolplatform.utils.json.JsonAtomicToken.Type;
public class JsonStreamReaderFixture {
private String newline;
private List<TestCase> testCases = new ArrayList<TestCase>();
public JsonStreamReaderFixture() {
newline = System.getProperty("line.separator");
testCases.addAll(getStringSuccess());
testCases.addAll(getStringFailure());
testCases.addAll(getNumberSuccess());
testCases.addAll(getNumberFailure());
testCases.addAll(getBooleanSuccess());
testCases.addAll(getBooleanFailure());
testCases.addAll(getNullSuccess());
testCases.addAll(getNullFailure());
testCases.addAll(getListSuccess());
testCases.addAll(getListFailure());
testCases.addAll(getObjectSuccess());
testCases.addAll(getObjectFailure());
}
public List<TestCase> getTestCases() {
return testCases;
}
public TestCase getLongStringList() {
StringBuilder json = new StringBuilder("[" + newline);
List<JsonAtomicToken> tokens = new ArrayList<JsonAtomicToken>();
tokens.add(new JsonAtomicToken(Type.START_LIST));
Random random = new Random();
int listSize = 1000;
for (int i = 0; i < listSize; i++) {
StringBuilder builder = new StringBuilder();
for (int c = 0; c < 1000; c++) {
builder.append((char)('a' + random.nextInt(26)));
}
json.append(indent(1) + "\"" + builder + "\"");
tokens.add(new JsonAtomicToken(Type.STRING, builder.toString()));
if (i < listSize - 1) {
json.append(",");
builder.append(new JsonAtomicToken(Type.LIST_ITEM_SEPARATOR));
}
json.append(newline);
}
json.append("]" + newline);
tokens.add(new JsonAtomicToken(Type.END_LIST));
return new TestCase(json.toString(), tokens);
}
private List<TestCase> getStringSuccess() {
List<TestCase> testCases = new ArrayList<TestCase>();
TestCase testCase = new TestCase("\"abcd\"", Arrays.asList(
new JsonAtomicToken(Type.STRING, "abcd")));
testCases.add(testCase);
testCase = new TestCase("\"\"", Arrays.asList(
new JsonAtomicToken(Type.STRING, "")));
testCases.add(testCase);
testCase = new TestCase("\"a\\tb c\\nd\\\"e\\\\f\"", Arrays.asList(
new JsonAtomicToken(Type.STRING, "a\tb c\nd\"e\\f")));
testCases.add(testCase);
testCase = new TestCase("\"\\u03b1\\u03B2\\u03b3\"", Arrays.asList(
new JsonAtomicToken(Type.STRING, "\u03b1\u03b2\u03b3")));
testCases.add(testCase);
testCase = new TestCase(indent(1) + "\"abcd\"" + newline, Arrays.asList(
new JsonAtomicToken(Type.STRING, "abcd")));
testCases.add(testCase);
return testCases;
}
private List<TestCase> getStringFailure() {
List<TestCase> testCases = new ArrayList<TestCase>();
testCases.add(new TestCase("", true));
testCases.add(new TestCase("\"\t\"", true));
testCases.add(new TestCase("abcd", true));
testCases.add(new TestCase("\"", true));
testCases.add(new TestCase("\"abcd", true));
testCases.add(new TestCase("\"\\a\"", true));
testCases.add(new TestCase("\"\\\"", true));
testCases.add(new TestCase("\"\\u03b\"", true));
testCases.add(new TestCase("\"\\u03bz\"", true));
testCases.add(new TestCase("\"\\u03", true));
testCases.add(new TestCase("\"abcd\"{", true));
return testCases;
}
private List<TestCase> getNumberSuccess() {
List<TestCase> testCases = new ArrayList<TestCase>();
TestCase testCase = new TestCase("271", Arrays.asList(
new JsonAtomicToken(Type.NUMBER, 271)));
testCases.add(testCase);
testCase = new TestCase("-271", Arrays.asList(
new JsonAtomicToken(Type.NUMBER, -271)));
testCases.add(testCase);
testCase = new TestCase("0", Arrays.asList(
new JsonAtomicToken(Type.NUMBER, 0)));
testCases.add(testCase);
testCase = new TestCase(Integer.toString(0x80000000), Arrays.asList(
new JsonAtomicToken(Type.NUMBER, Integer.MIN_VALUE)));
testCases.add(testCase);
testCase = new TestCase(Integer.toString(0x7fffffff), Arrays.asList(
new JsonAtomicToken(Type.NUMBER, Integer.MAX_VALUE)));
testCases.add(testCase);
testCase = new TestCase(Long.toString(0x80000000 - 1L), Arrays.asList(
new JsonAtomicToken(Type.NUMBER, Integer.MIN_VALUE - 1L)));
testCases.add(testCase);
testCase = new TestCase(Long.toString(0x80000000L), Arrays.asList(
new JsonAtomicToken(Type.NUMBER, Integer.MAX_VALUE + 1L)));
testCases.add(testCase);
testCase = new TestCase(Long.toString(Long.MIN_VALUE), Arrays.asList(
new JsonAtomicToken(Type.NUMBER, Long.MIN_VALUE)));
testCases.add(testCase);
testCase = new TestCase(Long.toString(Long.MAX_VALUE), Arrays.asList(
new JsonAtomicToken(Type.NUMBER, Long.MAX_VALUE)));
testCases.add(testCase);
testCase = new TestCase("32.075", Arrays.asList(
new JsonAtomicToken(Type.NUMBER, 32.075)));
testCases.add(testCase);
testCase = new TestCase("32.075E-02", Arrays.asList(
new JsonAtomicToken(Type.NUMBER, 32.075E-02)));
testCases.add(testCase);
testCase = new TestCase("32.075E+02", Arrays.asList(
new JsonAtomicToken(Type.NUMBER, 32.075E+02)));
testCases.add(testCase);
testCase = new TestCase("32e-3", Arrays.asList(
new JsonAtomicToken(Type.NUMBER, 32e-3)));
testCases.add(testCase);
testCase = new TestCase("32e3", Arrays.asList(
new JsonAtomicToken(Type.NUMBER, 32e3)));
testCases.add(testCase);
testCase = new TestCase(indent(1) + "271" + newline, Arrays.asList(
new JsonAtomicToken(Type.NUMBER, 271)));
testCases.add(testCase);
return testCases;
}
private List<TestCase> getNumberFailure() {
List<TestCase> testCases = new ArrayList<TestCase>();
testCases.add(new TestCase("01", true));
testCases.add(new TestCase("--1", true));
testCases.add(new TestCase("271.", true));
testCases.add(new TestCase("32.e3", true));
testCases.add(new TestCase("32e", true));
testCases.add(new TestCase("32e+", true));
testCases.add(new TestCase("271a", true));
testCases.add(new TestCase("32.34.36", true));
return testCases;
}
private List<TestCase> getBooleanSuccess() {
List<TestCase> testCases = new ArrayList<TestCase>();
TestCase testCase = new TestCase("true", Arrays.asList(
new JsonAtomicToken(Type.BOOLEAN, true)));
testCases.add(testCase);
testCase = new TestCase("false", Arrays.asList(
new JsonAtomicToken(Type.BOOLEAN, false)));
testCases.add(testCase);
testCase = new TestCase(indent(1) + "true" + newline, Arrays.asList(
new JsonAtomicToken(Type.BOOLEAN, true)));
testCases.add(testCase);
return testCases;
}
private List<TestCase> getBooleanFailure() {
List<TestCase> testCases = new ArrayList<TestCase>();
testCases.add(new TestCase("t", true));
testCases.add(new TestCase("tRUE", true));
testCases.add(new TestCase("TRUE", true));
testCases.add(new TestCase("True", true));
testCases.add(new TestCase("trues", true));
return testCases;
}
private List<TestCase> getNullSuccess() {
List<TestCase> testCases = new ArrayList<TestCase>();
TestCase testCase = new TestCase("null", Arrays.asList(
new JsonAtomicToken(Type.NULL)));
testCases.add(testCase);
testCase = new TestCase(indent(1) + "null" + newline, Arrays.asList(
new JsonAtomicToken(Type.NULL)));
testCases.add(testCase);
return testCases;
}
private List<TestCase> getNullFailure() {
List<TestCase> testCases = new ArrayList<TestCase>();
testCases.add(new TestCase("n", true));
testCases.add(new TestCase("nULL", true));
testCases.add(new TestCase("NULL", true));
testCases.add(new TestCase("Null", true));
testCases.add(new TestCase("null1", true));
return testCases;
}
private List<TestCase> getListSuccess() {
List<TestCase> testCases = new ArrayList<TestCase>();
testCases.add(getSimpleList(0));
testCases.add(getComplexList());
TestCase testCase = new TestCase("[]", Arrays.asList(
new JsonAtomicToken(Type.START_LIST),
new JsonAtomicToken(Type.END_LIST)));
testCases.add(testCase);
testCase = new TestCase(indent(1) + "[" + newline +
indent(1) + "]" + newline, Arrays.asList(
new JsonAtomicToken(Type.START_LIST),
new JsonAtomicToken(Type.END_LIST)));
testCases.add(testCase);
List<JsonAtomicToken> tokens = Arrays.asList(
new JsonAtomicToken(Type.START_LIST),
new JsonAtomicToken(Type.NUMBER, 1),
new JsonAtomicToken(Type.LIST_ITEM_SEPARATOR),
new JsonAtomicToken(Type.NUMBER, 2),
new JsonAtomicToken(Type.LIST_ITEM_SEPARATOR),
new JsonAtomicToken(Type.NUMBER, 3),
new JsonAtomicToken(Type.END_LIST));
testCase = new TestCase("[1,2,3]", tokens);
testCases.add(testCase);
testCase = new TestCase(indent(1) + "[" + newline +
indent(2) + "1 ," + newline +
indent(2) + "2 ," + newline +
indent(2) + "3" + newline +
indent(1) + "]" + newline, tokens);
testCases.add(testCase);
return testCases;
}
private List<TestCase> getListFailure() {
List<TestCase> testCases = new ArrayList<TestCase>();
testCases.add(new TestCase("[", true));
testCases.add(new TestCase("[1", true));
testCases.add(new TestCase("[true", true));
testCases.add(new TestCase("[\"a\"", true));
testCases.add(new TestCase("[[1]", true));
testCases.add(new TestCase("[1,", true));
testCases.add(new TestCase("[1,]", true));
testCases.add(new TestCase("[,1]", true));
testCases.add(new TestCase("[\"a\" \"b\"]", true));
testCases.add(new TestCase("[\"a\",\"b\"}", true));
return testCases;
}
private TestCase getSimpleList(int indent) {
return getListTestCaseForItems(indent, getSimpleListItems());
}
private TestCase getComplexList() {
return getListTestCaseForItems(0, getComplexListItems());
}
private TestCase getListTestCaseForItems(int indent,
List<TestCase> items) {
StringBuilder json = new StringBuilder("[" + newline);
List<JsonAtomicToken> tokens = new ArrayList<JsonAtomicToken>();
tokens.add(new JsonAtomicToken(Type.START_LIST));
for (int i = 0; i < items.size(); i++) {
TestCase item = items.get(i);
json.append(indent(indent + 1) + item.json);
tokens.addAll(item.tokens);
if (i < items.size() - 1) {
json.append(",");
tokens.add(new JsonAtomicToken(Type.LIST_ITEM_SEPARATOR));
}
json.append(newline);
}
json.append(indent(indent) + "]");
tokens.add(new JsonAtomicToken(Type.END_LIST));
return new TestCase(json.toString(), tokens);
}
private List<TestCase> getObjectSuccess() {
List<TestCase> testCases = new ArrayList<TestCase>();
testCases.add(getSimpleObject(0));
testCases.add(getComplexObject());
TestCase testCase = new TestCase("{}", Arrays.asList(
new JsonAtomicToken(Type.START_OBJECT),
new JsonAtomicToken(Type.END_OBJECT)));
testCases.add(testCase);
testCase = new TestCase(indent(1) + "{" + newline +
indent(1) + "}" + newline, Arrays.asList(
new JsonAtomicToken(Type.START_OBJECT),
new JsonAtomicToken(Type.END_OBJECT)));
testCases.add(testCase);
List<JsonAtomicToken> tokens = Arrays.asList(
new JsonAtomicToken(Type.START_OBJECT),
new JsonAtomicToken(Type.STRING, "a"),
new JsonAtomicToken(Type.OBJECT_KEY_VALUE_SEPARATOR),
new JsonAtomicToken(Type.NUMBER, 1),
new JsonAtomicToken(Type.OBJECT_PAIR_SEPARATOR),
new JsonAtomicToken(Type.STRING, "b"),
new JsonAtomicToken(Type.OBJECT_KEY_VALUE_SEPARATOR),
new JsonAtomicToken(Type.NUMBER, 2),
new JsonAtomicToken(Type.OBJECT_PAIR_SEPARATOR),
new JsonAtomicToken(Type.STRING, "c"),
new JsonAtomicToken(Type.OBJECT_KEY_VALUE_SEPARATOR),
new JsonAtomicToken(Type.NUMBER, 3),
new JsonAtomicToken(Type.END_OBJECT));
testCase = new TestCase("{\"a\":1,\"b\":2,\"c\":3}", tokens);
testCases.add(testCase);
testCase = new TestCase(indent(1) + "{" + newline +
indent(2) + "\"a\" : 1 ," + newline +
indent(2) + "\"b\" : 2 ," + newline +
indent(2) + "\"c\" : 3" + newline +
indent(1) + "}" + newline, tokens);
testCases.add(testCase);
return testCases;
}
private List<TestCase> getObjectFailure() {
List<TestCase> testCases = new ArrayList<TestCase>();
testCases.add(new TestCase("{", true));
testCases.add(new TestCase("{\"", true));
testCases.add(new TestCase("{\"a", true));
testCases.add(new TestCase("{\"a\"", true));
testCases.add(new TestCase("{\"a\":", true));
testCases.add(new TestCase("{\"a\":1", true));
testCases.add(new TestCase("{\"a\":1,", true));
testCases.add(new TestCase("{\"a\":true", true));
testCases.add(new TestCase("{\"a\":\"b\"", true));
testCases.add(new TestCase("{\"a\":[1]", true));
testCases.add(new TestCase("{\"}", true));
testCases.add(new TestCase("{\"a}", true));
testCases.add(new TestCase("{\"a\"}", true));
testCases.add(new TestCase("{\"a\":}", true));
testCases.add(new TestCase("{\"a\":1,}", true));
testCases.add(new TestCase("{,\"a\":1}", true));
testCases.add(new TestCase("{\"a\":1 \"b\":2}", true));
testCases.add(new TestCase("{\"a\":1,\"b\":2]", true));
testCases.add(new TestCase("{a:1}", true));
testCases.add(new TestCase("{\"a\":1,b:2}", true));
testCases.add(new TestCase("{\"a\",\"b\"}", true));
return testCases;
}
private TestCase getSimpleObject(int indent) {
return getObjectTestCaseForItems(indent, getSimpleListItems());
}
private TestCase getComplexObject() {
return getObjectTestCaseForItems(0, getComplexListItems());
}
private TestCase getObjectTestCaseForItems(int indent,
List<TestCase> items) {
StringBuilder json = new StringBuilder("{" + newline);
List<JsonAtomicToken> tokens = new ArrayList<JsonAtomicToken>();
tokens.add(new JsonAtomicToken(Type.START_OBJECT));
for (int i = 0; i < items.size(); i++) {
String key = "key" + (i + 1);
TestCase item = items.get(i);
json.append(indent(indent + 1) + "\"" + key + "\": " + item.json);
tokens.addAll(Arrays.asList(
new JsonAtomicToken(Type.STRING, key),
new JsonAtomicToken(Type.OBJECT_KEY_VALUE_SEPARATOR)));
tokens.addAll(item.tokens);
if (i < items.size() - 1) {
json.append(",");
tokens.add(new JsonAtomicToken(Type.OBJECT_PAIR_SEPARATOR));
}
json.append(newline);
}
json.append(indent(indent) + "}");
tokens.add(new JsonAtomicToken(Type.END_OBJECT));
return new TestCase(json.toString(), tokens);
}
private List<TestCase> getSimpleListItems() {
return Arrays.asList(
getStringSuccess().get(0),
getNumberSuccess().get(0),
new TestCase("[1,\"a\"]", Arrays.asList(
new JsonAtomicToken(Type.START_LIST),
new JsonAtomicToken(Type.NUMBER, 1),
new JsonAtomicToken(Type.LIST_ITEM_SEPARATOR),
new JsonAtomicToken(Type.STRING, "a"),
new JsonAtomicToken(Type.END_LIST))),
new TestCase("{\"a\":1,\"b\":2}", Arrays.asList(
new JsonAtomicToken(Type.START_OBJECT),
new JsonAtomicToken(Type.STRING, "a"),
new JsonAtomicToken(Type.OBJECT_KEY_VALUE_SEPARATOR),
new JsonAtomicToken(Type.NUMBER, 1),
new JsonAtomicToken(Type.OBJECT_PAIR_SEPARATOR),
new JsonAtomicToken(Type.STRING, "b"),
new JsonAtomicToken(Type.OBJECT_KEY_VALUE_SEPARATOR),
new JsonAtomicToken(Type.NUMBER, 2),
new JsonAtomicToken(Type.END_OBJECT))),
getNullSuccess().get(0),
getBooleanSuccess().get(0)
);
}
private List<TestCase> getComplexListItems() {
List<TestCase> items = new ArrayList<TestCase>(getSimpleListItems());
items.add(getSimpleList(1));
items.add(getSimpleObject(1));
return items;
}
private String indent(int n) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++) {
result.append(" ");
}
return result.toString();
}
public class TestCase extends JsonObject {
private String json;
private List<JsonAtomicToken> tokens = null;
private boolean exception = false;
private TestCase(String json, List<JsonAtomicToken> tokens) {
this.json = json;
this.tokens = tokens;
}
private TestCase(String json, boolean exception) {
this.json = json;
this.exception = exception;
}
public String getJson() {
return json;
}
public List<JsonAtomicToken> getTokens() {
return tokens;
}
public boolean isException() {
return exception;
}
}
}
| 36.566893 | 74 | 0.688515 |
f81c9b03923da82bdcd2e39ad5f3eaadb71dbd0e | 1,381 | package org.apache.hadoop.hive.contrib.udf.hiveudf;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
@Description(name = "hivelogo",
value = "_FUNC_(value, ...) - translate a tuple into hive logo.",
extended = "Example:\n"
+ " > SELECT _FUNC_(value, ...) FROM src;\n")
public class GenericUDFHiveLogo extends GenericUDF {
@Override
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments.length < 1) {
throw new UDFArgumentLengthException(
"The function HIVELOGO(v1, v2, ...) takes 1 or more arguments.");
}
return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
}
@Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
return HiveLogo.getHiveLogo();
}
@Override
public String getDisplayString(String[] children) {
assert (children.length > 0);
return "(" + children[0] + ", ...)";
}
}
| 37.324324 | 95 | 0.735699 |
f8cca5c19746deaead3602b28a5dc80b741bf33b | 9,160 | /*
* Copyright 2018 flow.ci
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.flowci.core.test.flow;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flowci.core.common.domain.GitSource;
import com.flowci.core.common.domain.Variables;
import com.flowci.core.common.domain.http.ResponseMessage;
import com.flowci.core.flow.domain.ConfirmOption;
import com.flowci.core.flow.domain.Flow;
import com.flowci.core.flow.domain.Flow.Status;
import com.flowci.core.flow.event.GitTestEvent;
import com.flowci.core.flow.service.FlowService;
import com.flowci.core.flow.service.GitService;
import com.flowci.core.job.event.CreateNewJobEvent;
import com.flowci.core.secret.domain.AuthSecret;
import com.flowci.core.secret.service.SecretService;
import com.flowci.core.test.SpringScenario;
import com.flowci.core.trigger.domain.GitPushTrigger;
import com.flowci.core.trigger.domain.GitTrigger;
import com.flowci.core.trigger.domain.GitUser;
import com.flowci.core.trigger.event.GitHookEvent;
import com.flowci.domain.SimpleAuthPair;
import com.flowci.domain.SimpleKeyPair;
import com.flowci.domain.VarValue;
import com.flowci.domain.Vars;
import com.flowci.exception.ArgumentException;
import com.flowci.util.StringHelper;
import org.junit.*;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @author yang
*/
@FixMethodOrder(value = MethodSorters.JVM)
public class FlowServiceTest extends SpringScenario {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private FlowService flowService;
@Autowired
private GitService gitService;
@Autowired
private SecretService secretService;
private String defaultYml;
@Before
public void login() throws IOException {
mockLogin();
defaultYml = StringHelper.toString(load("flow.yml"));
}
@Test
public void should_create_with_default_vars() {
final Flow flow = flowService.create("vars-test");
should_has_db_info(flow);
final Vars<VarValue> vars = flow.getLocally();
Assert.assertEquals(2, vars.size());
VarValue nameVar = vars.get(Variables.Flow.Name);
Assert.assertEquals(flow.getName(), nameVar.getData());
Assert.assertFalse(nameVar.isEditable());
}
@Test
public void should_list_all_flows_by_user_id() {
ConfirmOption confirmOption = new ConfirmOption().setYaml(defaultYml);
Flow first = flowService.create("test-1");
flowService.confirm(first.getName(), confirmOption);
Flow second = flowService.create("test-2");
flowService.confirm(second.getName(), confirmOption);
List<Flow> list = flowService.list(Status.CONFIRMED);
Assert.assertEquals(2, list.size());
Assert.assertEquals(first, list.get(0));
Assert.assertEquals(second, list.get(1));
}
@Test
public void should_create_and_confirm_flow() {
// when: create flow
String name = "hello";
flowService.create(name);
// then: flow with pending status
Flow created = flowService.get(name);
Assert.assertNotNull(created);
Assert.assertEquals(Status.PENDING, created.getStatus());
// when: confirm the flow
ConfirmOption option = new ConfirmOption()
.setYaml(defaultYml)
.setGitUrl("[email protected]:FlowCI/docs.git")
.setSecret("ssh-ras-credential");
flowService.confirm(name, option);
// then: flow should be with confirmed status
Flow confirmed = flowService.get(name);
Assert.assertNotNull(confirmed);
Assert.assertEquals(Status.CONFIRMED, confirmed.getStatus());
// then:
List<Flow> flows = flowService.list(Status.CONFIRMED);
Assert.assertEquals(1, flows.size());
}
@Test
public void should_list_flow_by_credential_name() {
// init:
String secretName = "flow-ssh-ras-name";
secretService.createRSA(secretName);
Flow flow = flowService.create("hello");
flowService.confirm(flow.getName(), new ConfirmOption().setYaml(defaultYml).setSecret(secretName));
Vars<VarValue> variables = flowService.get(flow.getName()).getLocally();
Assert.assertEquals(secretName, variables.get(Variables.Flow.GitCredential).getData());
// when:
List<Flow> flows = flowService.listByCredential(secretName);
Assert.assertNotNull(flows);
Assert.assertEquals(1, flows.size());
// then:
Assert.assertEquals(flow.getName(), flows.get(0).getName());
}
@Test(expected = ArgumentException.class)
public void should_throw_exception_if_flow_name_is_invalid_when_create() {
String name = "hello.world";
flowService.create(name);
}
@Test
public void should_start_job_with_condition() throws IOException, InterruptedException {
Flow flow = flowService.create("githook");
String yaml = StringHelper.toString(load("flow-with-condition.yml"));
flowService.confirm(flow.getName(), new ConfirmOption().setYaml(yaml));
GitPushTrigger trigger = new GitPushTrigger();
trigger.setEvent(GitTrigger.GitEvent.PUSH);
trigger.setSource(GitSource.GITEE);
trigger.setAuthor(new GitUser().setEmail("xx").setId("xx").setName("xx").setUsername("xx"));
trigger.setRef("master");
CountDownLatch c = new CountDownLatch(1);
addEventListener((ApplicationListener<CreateNewJobEvent>) e -> {
Assert.assertEquals(flow, e.getFlow());
c.countDown();
});
GitHookEvent e = new GitHookEvent(this, flow.getName(), trigger);
multicastEvent(e);
Assert.assertTrue(c.await(5, TimeUnit.SECONDS));
}
@Ignore
@Test
public void should_list_remote_branches_via_ssh_rsa() throws IOException, InterruptedException {
// init: load private key
TypeReference<ResponseMessage<SimpleKeyPair>> keyPairResponseType =
new TypeReference<ResponseMessage<SimpleKeyPair>>() {
};
ResponseMessage<SimpleKeyPair> r = objectMapper.readValue(load("rsa-test.json"), keyPairResponseType);
// given:
Flow flow = flowService.create("git-test");
CountDownLatch countDown = new CountDownLatch(2);
List<String> branches = new LinkedList<>();
addEventListener((ApplicationListener<GitTestEvent>) event -> {
if (!event.getFlowId().equals(flow.getId())) {
return;
}
if (event.getStatus() == GitTestEvent.Status.FETCHING) {
countDown.countDown();
}
if (event.getStatus() == GitTestEvent.Status.DONE) {
countDown.countDown();
branches.addAll(event.getBranches());
}
});
// when:
String gitUrl = "[email protected]:FlowCI/docs.git";
String privateKey = r.getData().getPrivateKey();
gitService.testConn(flow, gitUrl, privateKey);
// then:
countDown.await(30, TimeUnit.SECONDS);
Assert.assertTrue(branches.size() >= 1);
}
@Ignore
@Test
public void should_list_remote_branches_via_http_with_credential() throws InterruptedException {
// given:
String credentialName = "test-auth-c";
AuthSecret mocked = secretService.createAuth(credentialName, SimpleAuthPair.of("xxx", "xxx"));
Flow flow = flowService.create("git-test");
CountDownLatch countDown = new CountDownLatch(2);
List<String> branches = new LinkedList<>();
addEventListener((ApplicationListener<GitTestEvent>) event -> {
if (!event.getFlowId().equals(flow.getId())) {
return;
}
if (event.getStatus() == GitTestEvent.Status.FETCHING) {
countDown.countDown();
}
if (event.getStatus() == GitTestEvent.Status.DONE) {
countDown.countDown();
branches.addAll(event.getBranches());
}
});
String gitUrl = "https://xxxx";
gitService.testConn(flow, gitUrl, mocked.getName());
countDown.await(30, TimeUnit.SECONDS);
Assert.assertTrue(branches.size() >= 1);
}
}
| 34.828897 | 110 | 0.671943 |
4c273722bfe4195e16a2409849f0149112131f40 | 3,569 | /*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. 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 Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) 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 RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
package org.mpisws.p2p.transport.peerreview.message;
import java.io.IOException;
import java.util.Map;
import org.mpisws.p2p.transport.peerreview.PeerReviewConstants;
import org.mpisws.p2p.transport.peerreview.infostore.Evidence;
import org.mpisws.p2p.transport.peerreview.infostore.EvidenceRecord;
import org.mpisws.p2p.transport.peerreview.infostore.EvidenceSerializer;
import org.mpisws.p2p.transport.peerreview.statement.Statement;
import org.mpisws.p2p.transport.util.Serializer;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import rice.p2p.commonapi.rawserialization.RawSerializable;
/**
MSG_ACCUSATION
byte type = MSG_ACCUSATION
nodeID originator
nodeID subject
long long evidenceSeq
[evidence bytes follow]
*/
public class AccusationMessage<Identifier extends RawSerializable> extends Statement<Identifier> {
public AccusationMessage(Identifier originator, Identifier subject,
long evidenceSeq, Evidence evidence) {
super(originator, subject, evidenceSeq, evidence);
}
public AccusationMessage(InputBuffer buf,
Serializer<Identifier> idSerializer, EvidenceSerializer evSerializer)
throws IOException {
super(buf, idSerializer, evSerializer);
// TODO Auto-generated constructor stub
}
public AccusationMessage(Identifier subject,
EvidenceRecord<?, Identifier> evidenceRecord, Evidence evidence) {
this(evidenceRecord.getOriginator(),subject,evidenceRecord.getTimeStamp(),evidence);
}
public short getType() {
return MSG_ACCUSATION;
}
@Override
protected boolean isResponse() {
return false;
}
}
| 37.968085 | 98 | 0.759597 |
e79a96dd6d0120fae172a4158616ce4137fa9933 | 627 | package com.ch.model;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by Aaron.Witter on 01/08/2016.
*/
public class PresenterAuthRequest {
private String presenterId;
private String presenterAuth;
public PresenterAuthRequest() {// empty constructor for de serialisation
}
public PresenterAuthRequest(String presenterId, String presenterAuth) {
this.presenterId = presenterId;
this.presenterAuth = presenterAuth;
}
@JsonProperty
public String getPresenterId() {
return presenterId;
}
@JsonProperty
public String getPresenterAuth() {
return presenterAuth;
}
} | 20.9 | 74 | 0.744817 |
42039c068c7cebede662e1df58351c6abc28487f | 3,372 | package nablarch.core.db.statement.autoproperty;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import nablarch.core.cache.StaticDataCache;
import nablarch.core.db.statement.AutoPropertyHandler;
import nablarch.core.repository.IgnoreProperty;
import nablarch.core.util.annotation.Published;
/**
* フィールドのアノテーション情報を元に値を設定するクラスをサポートするクラス。
*
* @author Hisaaki Sioiri
*/
@Published(tag = "architect")
public abstract class FieldAnnotationHandlerSupport implements AutoPropertyHandler {
/**
* フィールドアノテーション保持クラスを設定する。
*
* @param fieldAnnotationCache フィールドアノテーション保持クラス
*/
@IgnoreProperty("フィールドではなくプロパティアクセスするよう仕様変更を行ったため本プロパティは廃止しました。(値を設定しても意味がありません)")
public void setFieldAnnotationCache(
StaticDataCache<Map<String, Map<String, ?>>> fieldAnnotationCache) {
}
/**
* 指定されたアノテーションが設定されているフィールド情報を取得する。<br>
* 指定されたオブジェクトに、指定されたアノテーションが設定されているフィールドが存在しない場合は、空のリストを返す。
*
* @param obj 対象のオブジェクト
* @param annotationType アノテーション
* @return 指定されたアノテーションが設定されているフィールドの情報
*/
protected <T extends Annotation> List<FieldHolder<T>> getFieldList(
final Object obj, final Class<T> annotationType) {
return findFieldsWithAnnotation(obj.getClass(), annotationType);
}
/**
* 指定されたアノテーションが設定されたフィールドを取得する。
* <p>
* 親クラスが存在する場合は、再帰的に親クラスのフィールドも対象とする。
*
* @param clazz クラス
* @param annotationType アノテーションクラス
* @param <T> アノテーションの型
* @return 指定されたアノテーションが設定されたフィールドのリスト
*/
private <T extends Annotation> List<FieldHolder<T>> findFieldsWithAnnotation(
final Class<?> clazz, final Class<T> annotationType) {
final List<FieldHolder<T>> result = new ArrayList<FieldHolder<T>>();
final Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
final T annotation = field.getAnnotation(annotationType);
if (annotation != null) {
field.setAccessible(true);
result.add(new FieldHolder<T>(field, annotation));
}
}
final Class<?> superclass = clazz.getSuperclass();
if (superclass != null) {
result.addAll(findFieldsWithAnnotation(superclass, annotationType));
}
return result;
}
/**
* フィールド情報を保持するクラス。
*
* このクラスでは、フィールドとフィールドに設定されたアノテーションの情報を保持する。
*
* @param <T> アノテーションの型
*/
@Published(tag = "architect")
public static class FieldHolder<T extends Annotation> {
/** フィールド */
private final Field field;
/** アノテーション */
private final T annotation;
/**
* フィールドとアノテーションを元に{@code FieldHolder}を構築する。
*
* @param field フィールド
* @param annotation アノテーション
*/
public FieldHolder(final Field field, final T annotation) {
this.field = field;
this.annotation = annotation;
}
/**
* フィールドを取得する。
*
* @return フィールド
*/
public Field getField() {
return field;
}
/**
* アノテーションを取得する。
*
* @return アノテーション
*/
public T getAnnotation() {
return annotation;
}
}
}
| 27.414634 | 86 | 0.622776 |
86f095d59590562f3e6eecac2d524968eee960e5 | 2,260 | /*
* Copyright (c) 2020-2021, Koninklijke Philips N.V., https://www.philips.com
* SPDX-License-Identifier: MIT
*/
package com.philips.research.spdxbuilder.controller;
import com.philips.research.spdxbuilder.core.BusinessException;
import com.philips.research.spdxbuilder.persistence.license_scanner.LicenseScannerException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Url;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
interface UploadApi {
@Multipart
@POST
Call<Void> uploadFile(@Url String path, @Part MultipartBody.Part filePart);
}
public class UploadClient {
private static final Duration MAX_UPLOAD_DURATION = Duration.ofMinutes(5);
private static final OkHttpClient CLIENT = new OkHttpClient.Builder()
.writeTimeout(MAX_UPLOAD_DURATION)
.readTimeout(MAX_UPLOAD_DURATION)
.build();
private final UploadApi rest;
private final URI uploadUrl;
UploadClient(URI uploadUrl) {
this.uploadUrl = uploadUrl;
var uploadPath = uploadUrl.toASCIIString();
if (!uploadPath.endsWith("/")) {
uploadPath += '/';
}
final var retrofit = new Retrofit.Builder()
.client(CLIENT)
.baseUrl(uploadPath)
.build();
rest = retrofit.create(UploadApi.class);
}
void upload(File file) {
try {
final var reqBody = RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), file);
final var filePart = MultipartBody.Part.createFormData("file", "sbom.spdx", reqBody);
final var response = rest.uploadFile(uploadUrl.getPath(), filePart).execute();
if (!response.isSuccessful()) {
throw new BusinessException("SPDX upload responded with status " + response.code());
}
} catch (IOException e) {
throw new LicenseScannerException("The SPDX upload server is not reachable at " + uploadUrl);
}
}
}
| 33.731343 | 105 | 0.680088 |
f341b14234a8619d7da8c633b049ab697e71f59d | 3,643 | package com.github.grzesiek_galezowski.collections.readonly.factory;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlyCollectionWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlyDequeWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlyListWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlyMapWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlyNavigableMapWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlyNavigableSetWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlyQueueWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlySetWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlySortedMapWrapper;
import com.github.grzesiek_galezowski.collections.readonly.implementation.ReadOnlySortedSetWrapper;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlyCollection;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlyDeque;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlyList;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlyMap;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlyNavigableMap;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlyNavigableSet;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlyQueue;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlySet;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlySortedMap;
import com.github.grzesiek_galezowski.collections.readonly.interfaces.ReadOnlySortedSet;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
public class ReadOnlyCollections {
public static <T> ReadOnlyCollection<T> readOnly(final Collection<T> collection) {
return new ReadOnlyCollectionWrapper<>(collection);
}
public static <T> ReadOnlyList<T> readOnly(final List<T> list) {
return new ReadOnlyListWrapper<>(list);
}
public static <T> ReadOnlySet<T> readOnly(final Set<T> set) {
return new ReadOnlySetWrapper<>(set);
}
public static <T> ReadOnlyQueue<T> readOnly(final Queue<T> queue) {
return new ReadOnlyQueueWrapper<>(queue);
}
public static <T> ReadOnlyDeque<T> readOnly(final Deque<T> deque) {
return new ReadOnlyDequeWrapper<>(deque);
}
public static <T> ReadOnlyNavigableSet<T> readOnly(final NavigableSet<T> navigableSet) {
return new ReadOnlyNavigableSetWrapper<>(navigableSet);
}
public static <T> ReadOnlySortedSet<T> readOnly(final SortedSet<T> sortedSet) {
return new ReadOnlySortedSetWrapper<>(sortedSet);
}
public static <K,V> ReadOnlyMap<K,V> readOnly(final Map<K, V> map) {
return new ReadOnlyMapWrapper<>(map);
}
public static <K,V> ReadOnlySortedMap<K,V> readOnly(final SortedMap<K, V> sortedMap) {
return new ReadOnlySortedMapWrapper<>(sortedMap);
}
public static <K,V> ReadOnlyNavigableMap<K,V> readOnly(final NavigableMap<K, V> navigableMap) {
return new ReadOnlyNavigableMapWrapper<>(navigableMap);
}
}
| 49.22973 | 102 | 0.808674 |
407afde364b3023050e6d7c1232401c6515d7e80 | 584 | package xyz.esion.manage.model.database;
import lombok.Data;
/**
* @author Esion
* @since 2021/7/17
*/
@Data
public class Field {
public static final String[] COLUMN = new String[]{"Field", "Type", "Collation", "Null", "Key", "Default",
"Extra", "Privileges", "Comment"};
/**
* 字段名
* */
private String name;
private String type;
private String collation;
private String isNull;
private String key;
private String defaultValue;
private String extra;
private String privileges;
private String comment;
}
| 15.783784 | 110 | 0.625 |
8d32691d1fe366c19b3f81947de3316c498e2267 | 1,676 | package com.forum.controllers;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.forum.commands.ForgotPasswordCommand;
import com.forum.services.UserService;
@Controller
@RequestMapping("/forgot-password")
public class ForgotPasswordController {
private static Log log = LogFactory.getLog(ForgotPasswordController.class);
@Autowired
private UserService userService;
@Autowired
private MessageSource messageSource;
@GetMapping
public String forgotPassword(Model model) {
model.addAttribute(new ForgotPasswordCommand());
return "forgot-password";
}
@PostMapping
public String doForgotPassword(
@Validated ForgotPasswordCommand forgotPasswordCommand,
BindingResult result,
RedirectAttributes redirectAttributes, Locale locale) {
if (result.hasErrors())
return "forgot-password";
userService.forgotPassword(forgotPasswordCommand);
redirectAttributes.addFlashAttribute("success", messageSource.getMessage("message.forgotPasswordMailSent", null, locale));
return "redirect:/login";
}
}
| 30.472727 | 124 | 0.819809 |
917b7a25c9163094d77c67cb291aee4ef80522d1 | 6,733 | /*******************************************************************************
* ENdoSnipe 5.0 - (https://github.com/endosnipe)
*
* The MIT License (MIT)
*
* Copyright (c) 2012 Acroquest Technology Co.,Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package jp.co.acroquest.endosnipe.perfdoctor.rule.code;
import java.util.Map;
import jp.co.acroquest.endosnipe.common.parser.JavelinConstants;
import jp.co.acroquest.endosnipe.common.parser.JavelinLogColumnNum;
import jp.co.acroquest.endosnipe.javelin.JavelinLogUtil;
import jp.co.acroquest.endosnipe.javelin.parser.JavelinLogElement;
import jp.co.acroquest.endosnipe.javelin.parser.JavelinParser;
import jp.co.acroquest.endosnipe.perfdoctor.rule.SingleElementRule;
/**
* I/O待ちの長い処理を検出するルールです。<br />
* I/O待ち時間は直接検出できないため、メソッドの TAT から CPU時間、WAIT時間、
* ブロック時間を引いてI/O待ち時間を検出します。<br />
* このようにして検出した I/O 待ち時間が閾値よりも長い場合に警告します。<br />
*
* @author akita
*/
public class IOWaitTimeRule extends SingleElementRule
{
/** メソッドのTATを表す文字列 */
private static final String DURATION = "duration";
/** ExtraInfoを表す文字列 */
private static final String EXTRA_INFO = "ExtraInfo";
/**
* 詳細情報取得キー:ThreadMXBean#getCurrentThreadCpuTimeパラメータの差分
* 現在のスレッドの合計 CPU 時間の差分をナノ秒単位で返します。
*/
private static final String JMXPARAM_THREAD_CURRENT_THREAD_CPU_TIME_DELTA =
"thread.currentThreadCpuTime.delta";
/**
* 詳細情報取得キー:ThreadMXBean#getThreadInfo#getWaitedTimeパラメータ
* スレッドコンテンション監視が有効になってから、この ThreadInfo に関連するスレッドが通知を待機した
* およその累積経過時間 (ミリ秒単位) の差分を返します。
*/
private static final String JMXPARAM_THREAD_THREADINFO_WAITED_TIME_DELTA =
"thread.threadInfo.waitedTime.delta";
/**
* 詳細情報取得キー:ThreadMXBean#getThreadInfo#getBlockedTimeパラメータの差分
* スレッドコンテンション監視が有効になってから、この ThreadInfo に関連するスレッドがモニターに入るか
* 再入するのをブロックしたおよその累積経過時間 (ミリ秒単位) の差分を返します。
*/
private static final String JMXPARAM_THREAD_THREADINFO_BLOCKED_TIME_DELTA =
"thread.threadInfo.blockedTime.delta";
/** 警告と判断する検出値のデフォルト値。 */
private static final int DEFAULT_THRESHOLD = 5000;
/** 検出値の閾値。この値を超えた際に警告を生成する。*/
public long threshold = DEFAULT_THRESHOLD;
/**
* CALLログ中のメソッドのTATの値を調査し、 閾値を超えていた際には警告する。
*
* @param javelinLogElement
* ログの要素
*
*/
@Override
public void doJudgeElement(final JavelinLogElement javelinLogElement)
{
// 識別子が"Call"でない場合は判定しない。
String type = javelinLogElement.getBaseInfo().get(JavelinLogColumnNum.ID);
boolean isCall = JavelinConstants.MSG_CALL.equals(type);
if (isCall == false)
{
return;
}
if (JavelinLogUtil.isExistTag(javelinLogElement, JavelinParser.TAG_TYPE_JMXINFO) == false)
{
// 計測時にJMX情報を取得していない場合は判定しない
return;
}
// ExtraInfoの内容を表すMapを取得する。
Map<String, String> extraInfo =
JavelinLogUtil.parseDetailInfo(javelinLogElement,
EXTRA_INFO);
//JMX情報を保持したmapを取得する。
Map<String, String> jmxInfo =
JavelinLogUtil.parseDetailInfo(javelinLogElement,
JavelinParser.TAG_TYPE_JMXINFO);
// ExtraInfoの情報を保持したmapよりメソッドのTATの値を得る。
String durationString = extraInfo.get(DURATION);
//JMX情報のmapより、Wait時間の値を得る。
String waitTimeString = jmxInfo.get(JMXPARAM_THREAD_THREADINFO_WAITED_TIME_DELTA);
//JMX情報のmapより、メソッドのCPU時間の値を得る。CPU時間をmsecに変換する。
String cpuTimeStr = jmxInfo.get(JMXPARAM_THREAD_CURRENT_THREAD_CPU_TIME_DELTA);
//JMX情報のmapより、ブロック時間の値を得る。
String blockTimeString = jmxInfo.get(JMXPARAM_THREAD_THREADINFO_BLOCKED_TIME_DELTA);
//TAT,Wait時間,CPU時間、ブロック時間をそれぞれ型変換する。(CPU時間はnsecからmsecに単位を変更する)
long waitTime = 0;
double cpuTimeDouble = 0;
long cpuTime = 0;
long blockTime = 0;
long duration = 0;
try
{
if (waitTimeString != null)
{
waitTime = Long.parseLong(waitTimeString);
}
if (cpuTimeStr != null)
{
cpuTimeDouble = Double.parseDouble(cpuTimeStr);
}
cpuTime = (long)cpuTimeDouble;
if (blockTimeString != null)
{
blockTime = Long.parseLong(blockTimeString);
}
if (durationString != null)
{
duration = Long.parseLong(durationString);
}
}
catch (NumberFormatException nfex)
{
return;
}
/*メソッドのTATとCPU時間、Wait時間、ブロック時間の和との差を求める。
(メソッドのTAT)-((CPU時間)+(Wait時間)+(ブロック時間))
*/
long status = duration - (waitTime + cpuTime + blockTime);
// もし検出値が閾値に達するのであれば、警告を出す。
if (status >= this.threshold)
{
addError(javelinLogElement, this.threshold, status);
}
}
}
| 40.560241 | 119 | 0.587851 |
0d162906b6c52203da3985d1832aa93ffa343bb7 | 781 | package bozels.layouthulp;
import java.awt.Color;
import java.awt.Component;
import javax.swing.*;
/**
*
* @author Titouan Vervack
*/
public class CellRenderer implements ListCellRenderer {
public CellRenderer() {
}
@Override
public Component getListCellRendererComponent(JList list, Object c, int i, boolean isSelected, boolean focus) {
if (c instanceof JPanel) {
JComponent component = (JComponent) c;
component.setForeground(Color.WHITE);
component.setBackground(Color.WHITE);
//Maak een kadertje rond het geselecteerde element
component.setBorder(isSelected ? BorderFactory.createLineBorder(Color.BLACK) : null);
return component;
}
return null;
}
}
| 26.931034 | 115 | 0.661972 |
7033ffc2754e5fb16c1a5fbd253a459c05b8813a | 5,561 | /*
* All GTAS code is Copyright 2016, The Department of Homeland Security (DHS), U.S. Customs and Border Protection (CBP).
*
* Please see LICENSE.txt for details.
*/
package gov.gtas.controller;
import gov.gtas.constant.CommonErrorConstants;
import gov.gtas.constant.WatchlistConstants;
import gov.gtas.constants.Constants;
import gov.gtas.enumtype.Status;
import gov.gtas.error.CommonServiceException;
import gov.gtas.json.JsonServiceResponse;
import gov.gtas.model.watchlist.json.WatchlistItemSpec;
import gov.gtas.model.watchlist.json.WatchlistSpec;
import gov.gtas.security.service.GtasSecurityUtils;
import gov.gtas.svc.RuleManagementService;
import gov.gtas.svc.WatchlistService;
import gov.gtas.util.SampleDataGenerator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* The REST service end-point controller for creating and managing watch lists.
*/
@RestController
public class WatchlistManagementController {
private static final Logger logger = LoggerFactory
.getLogger(WatchlistManagementController.class);
@Autowired
private WatchlistService watchlistService;
@Autowired
private RuleManagementService ruleManagementService;
/**
* Gets the watchlist.
*
* @param entity
* the entity
* @param name
* the name
* @return the watchlist
*/
@RequestMapping(value = Constants.WL_GET_BY_NAME, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public JsonServiceResponse getWatchlist(@PathVariable String entity,
@PathVariable String name) {
logger.debug("******** name =" + name);
WatchlistSpec resp = watchlistService.fetchWatchlist(name);
if (resp == null) {
resp = new WatchlistSpec(name, entity);
}
return new JsonServiceResponse(Status.SUCCESS,
"GET Watchlist By Name was successful", resp);
}
@RequestMapping(value = Constants.WL_GETALL, method = RequestMethod.GET)
public List<WatchlistSpec> getWatchlist() {
return watchlistService.fetchAllWatchlists();
}
@RequestMapping(value = Constants.WL_GETDRL, method = RequestMethod.GET)
public JsonServiceResponse getDrl() {
String rules = ruleManagementService
.fetchDrlRulesFromKnowledgeBase(WatchlistConstants.WL_KNOWLEDGE_BASE_NAME);
return createDrlRulesResponse(rules);
}
/**
* Creates the DRL rule response JSON object.
*
* @param rules
* the DRL rules.
* @return the JSON response object containing the rules.
*/
private JsonServiceResponse createDrlRulesResponse(String rules) {
JsonServiceResponse resp = new JsonServiceResponse(Status.SUCCESS,
"Drools rules fetched successfully");
String[] lines = rules.split("\n");
resp.addResponseDetails(new JsonServiceResponse.ServiceResponseDetailAttribute(
"DRL Rules", lines));
return resp;
}
/**
* Creates the watchlist.
*
* @param entity
* the entity
* @param inputSpec
* the input spec
* @return the json service response
*/
@RequestMapping(value = Constants.WL_CREATE_UPDATE_DELETE_ITEMS, method = {
RequestMethod.POST, RequestMethod.PUT }, produces = MediaType.APPLICATION_JSON_VALUE)
public JsonServiceResponse createWatchlist(@PathVariable String entity,
@RequestBody WatchlistSpec inputSpec) {
String userId = GtasSecurityUtils.fetchLoggedInUserId();
logger.info("******** Received Watchlist Create/Update request by user ="
+ userId);
validateInput(inputSpec);
return watchlistService.createUpdateDeleteWatchlistItems(userId, inputSpec);
}
private void validateInput(WatchlistSpec inputSpec) {
List<WatchlistItemSpec> items = inputSpec != null ? inputSpec
.getWatchlistItems() : null;
if (inputSpec == null || CollectionUtils.isEmpty(items)) {
throw new CommonServiceException(
CommonErrorConstants.NULL_ARGUMENT_ERROR_CODE,
String.format(
CommonErrorConstants.NULL_ARGUMENT_ERROR_MESSAGE,
"Create Query For Rule", "inputSpec"));
}
}
/**
* Delete all watchlist items.
*
* @param name
* the name
* @return the json service response
*/
@RequestMapping(value = Constants.WL_DELETE, method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public JsonServiceResponse deleteAllWatchlistItems(@PathVariable String name) {
String userId = GtasSecurityUtils.fetchLoggedInUserId();
logger.info("******** Received Watchlist DeleteAll request for watch list ="
+ name + " by user " + userId);
//return watchlistService.deleteWatchlist(userId,name);
return watchlistService.deleteWatchlist(userId,"NONE");
}
/**
* Compile watchlists.
*
* @return the json service response
*/
@RequestMapping(value = Constants.WL_COMPILE, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public JsonServiceResponse compileWatchlists() {
return watchlistService.activateAllWatchlists();
}
/**
*
* @return
*/
@RequestMapping(value = Constants.WL_TEST, method = RequestMethod.GET)
public WatchlistSpec getTestWatchlist() {
return SampleDataGenerator.createSampleWatchlist("TestWatchlist");
}
}
| 33.299401 | 123 | 0.759396 |
0996a6782224edd618c188d54761d2a855db9941 | 1,506 | package io.jenkins.plugins.casc;
import hudson.security.SecurityRealm;
import io.jenkins.plugins.casc.misc.ConfiguredWithCode;
import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.GithubSecurityRealm;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* Purpose:
* Test that we can configure: <a href="https://plugins.jenkins.io/github-oauth"/>
*/
public class GithubOAuthTest {
@Rule
public RuleChain rc = RuleChain.outerRule(new EnvironmentVariables().set("GITHUB_SECRET","j985j8fhfhh377"))
.around(new JenkinsConfiguredWithCodeRule());
@Test
@ConfiguredWithCode("GithubOAuth.yml")
public void testSampleVersionForOAuth() {
SecurityRealm realm = Jenkins.get().getSecurityRealm();
assertThat(realm, instanceOf(GithubSecurityRealm.class));
GithubSecurityRealm gsh = (GithubSecurityRealm)realm;
assertEquals("someId", gsh.getClientID());
assertEquals("https://api.github.com", gsh.getGithubApiUri());
assertEquals("https://github.com", gsh.getGithubWebUri());
assertEquals("j985j8fhfhh377", gsh.getClientSecret().getPlainText());
assertEquals("read:org,user:email", gsh.getOauthScopes());
}
}
| 38.615385 | 111 | 0.747676 |
d2f8c102b9ae3a3bda2b1816b1b19918d6b80dac | 1,056 | package com.bitwig.multisample;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.*;
@XmlRootElement(name = "multisample")
@XmlSeeAlso({Group.class, Sample.class})
public class Multisample
{
/**
* Name of the multisample.
*/
@XmlAttribute(required = true)
public String name;
/**
* Software which generated the file.
*/
@XmlElement(required = true)
public String generator;
/** Category of the multisample (ie Drum / Keyboard / FX) */
@XmlElement(required = true)
public String category;
/** User who created the file. */
@XmlElement(required = true)
public String creator;
/** A longer description of the multisample. */
@XmlElement(required = false)
public String description;
@XmlElementWrapper(name = "keywords")
@XmlElement(name = "keyword")
public List<String> keywords = new ArrayList<>();
@XmlElementRef
public List<Group> groups = new ArrayList<>();
@XmlElementRef
public List<Sample> samples = new ArrayList<>();
}
| 22.956522 | 63 | 0.67803 |
4ebe203e6539c8075253772b55fb4009fbcffab3 | 2,210 | /*
* Copyright 2017 Kenneth Yo
*
* 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 me.kennethyo.library.brakelight.internal;
import android.util.Log;
final class BrakeLightLog {
private static volatile Logger logger = new DefaultLogger();
interface Logger {
void d(String message, Object... args);
void d(Throwable throwable, String message, Object... args);
}
private static class DefaultLogger implements Logger {
DefaultLogger() { }
@Override public void d(String message, Object... args) {
String formatted = String.format(message, args);
if (formatted.length() < 4000) {
Log.d("BrakeLight", formatted);
} else {
String[] lines = formatted.split("\n");
for (String line : lines) {
Log.d("BrakeLight", line);
}
}
}
@Override public void d(Throwable throwable, String message, Object... args) {
d(String.format(message, args) + '\n' + Log.getStackTraceString(throwable));
}
}
public static void setLogger(Logger logger) {
BrakeLightLog.logger = logger;
}
static void d(String message, Object... args) {
// Local variable to prevent the ref from becoming null after the null check.
Logger logger = BrakeLightLog.logger;
if (logger == null) {
return;
}
logger.d(message, args);
}
static void d(Throwable throwable, String message, Object... args) {
// Local variable to prevent the ref from becoming null after the null check.
Logger logger = BrakeLightLog.logger;
if (logger == null) {
return;
}
logger.d(throwable, message, args);
}
private BrakeLightLog() {
throw new AssertionError();
}
}
| 28.701299 | 82 | 0.671041 |
18c04a111407e8e1e100059fc38d237fdc42aa8b | 645 | /*
* Copyright (c) 2012-2015 iWave Software LLC
* All Rights Reserved
*/
package com.iwave.ext.linux.command;
import org.apache.commons.lang.StringUtils;
public class MkfsCommand extends LinuxCommand {
public MkfsCommand(String device, String fileSystemType, String blockSize, boolean journaling) {
setCommand("echo n | " + CommandConstants.MKFS);
addArguments("-t", fileSystemType);
if (StringUtils.isNotBlank(blockSize)) {
addArguments("-b", blockSize);
}
if (journaling) {
addArgument("-j");
}
addArgument(device);
setRunAsRoot(true);
}
}
| 25.8 | 100 | 0.64031 |
29a7f76652d6c94d2f672a23f2ae2ce7c5d6ea3b | 1,783 | package net.dreamlu.easy.commons.config;
import java.util.Date;
import javax.servlet.ServletContext;
import com.jfinal.core.JFinal;
import com.jfinal.upload.OreillyCos;
import net.dreamlu.easy.commons.logs.LogPrintStream;
import net.dreamlu.easy.commons.owner.ConfigFactory;
import net.dreamlu.easy.commons.session.SessionRepositoryRequestWrapper;
import net.dreamlu.easy.commons.upload.EasyFileRenamePolicy;
import net.dreamlu.easy.commons.utils.WebUtils;
/**
* Easy4JFinal
* @author L.cm
*/
public final class Easy4JFinal {
private static final Easy4JFinal me = new Easy4JFinal();
private Easy4JFinal() {}
public static Easy4JFinal me() {
return me;
}
// 版本号
public static final String VERSION = "1.0";
private ApplicationConfig cfg;
void initCfg() {
cfg = ConfigFactory.create(ApplicationConfig.class);
}
void initAfterStart() {
// 正式环境,将System.out、err输出到log中
if (!cfg.devMode()) {
System.setOut(new LogPrintStream(false));
System.setErr(new LogPrintStream(true));
}
// 用户登陆是使用的cookie name和密钥
WebUtils.setUserKey(cfg.userKey());
WebUtils.setUserSecret(cfg.userSecret());
// 在JFinal启动时,加入启动时间 ${startTime}
JFinal jfinal = JFinal.me();
ServletContext servletContext = jfinal.getServletContext();
servletContext.setAttribute("startTime", new Date());
// ctxPath
String ctxPath = jfinal.getContextPath();
servletContext.setAttribute("ctxPath", ctxPath);
// 静态文件目录
servletContext.setAttribute("stcPath", ctxPath + "/static");
// 修改默认的重命名策略
OreillyCos.setFileRenamePolicy(new EasyFileRenamePolicy());
// 初始化Session
SessionRepositoryRequestWrapper.initCfg(cfg);
}
public final ApplicationConfig getCfg() {
return cfg;
}
}
| 25.471429 | 73 | 0.716769 |
014d05c51d6f81ee6b67e57d38a8cb118a3ef943 | 1,729 | package everyos.bot.luwu.run.command.modules.currency;
import everyos.bot.chat4j.entity.ChatPermission;
import everyos.bot.luwu.core.client.ArgumentParser;
import everyos.bot.luwu.core.command.CommandData;
import everyos.bot.luwu.core.entity.Channel;
import everyos.bot.luwu.core.entity.Locale;
import everyos.bot.luwu.core.entity.Member;
import everyos.bot.luwu.core.exception.TextException;
import everyos.bot.luwu.core.functionality.channel.ChannelTextInterface;
import everyos.bot.luwu.run.command.CommandBase;
import reactor.core.publisher.Mono;
public class FethDailyCommand extends CommandBase {
private static final long DAILY_AMOUNT = 20;
private static final long COOLDOWN_MILLIS = 1000*60*60*24;
public FethDailyCommand() {
super("command.feth.daily", e->true, ChatPermission.SEND_MESSAGES, ChatPermission.NONE);
}
@Override
public Mono<Void> execute(CommandData data, ArgumentParser parser) {
Locale locale = data.getLocale();
return
runCommand(data.getChannel(), data.getInvoker(), locale);
}
private Mono<Void> runCommand(Channel channel, Member invoker, Locale locale) {
FethMember invokerAs = invoker.as(FethMember.type);
return
invokerAs.edit(spec->{
FethMemberInfo info = spec.getInfo();
if (System.currentTimeMillis()-info.getCooldown()<COOLDOWN_MILLIS) {
return Mono.error(new TextException(locale.localize("command.feth.daily.cooldown")));
}
spec.setCurrency(info.getCurrency()+DAILY_AMOUNT);
spec.setCooldown(System.currentTimeMillis());
return Mono.empty();
})
.then(channel.getInterface(ChannelTextInterface.class).send(locale.localize("command.feth.daily.message")))
.then();
}
}
| 36.787234 | 111 | 0.748409 |
1522999302d42e5f18dcc93732da18db95e5bd4e | 1,162 | package example.grpc;
import example.grpc.service.HelloServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.util.TransmitStatusRuntimeExceptionInterceptor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class GrpcServerStartupRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
ServerBuilder serverBuilder = ServerBuilder
.forPort(8081)
.addService(new HelloServiceImpl());
Server server = serverBuilder.build();
serverBuilder.intercept(TransmitStatusRuntimeExceptionInterceptor.instance());
server.start();
startDaemonAwaitThread(server);
}
private void startDaemonAwaitThread(Server server) {
Thread awaitThread = new Thread(() -> {
try {
server.awaitTermination();
} catch (InterruptedException ignore) {
}
});
awaitThread.setDaemon(false);
awaitThread.start();
}
}
| 30.578947 | 86 | 0.697935 |
5d4ee602c0a60cc95405d9b225ed9adc5077a81e | 1,514 | package es.uniovi.asw.persistence.model;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@DiscriminatorValue("C")
@Table(name="VoteComment")
public class VoteComment extends Vote{
@ManyToOne
private Comment comment;
public VoteComment(){
}
public VoteComment(Citizen citizen, Comment comment) {
super(citizen);
this.comment = comment;
Association.Voting.linkComment(super.getCitizen(), this, comment);
}
public void setComment(Comment comment){
Association.Voting.linkComment(super.getCitizen(), this, comment);
}
void _setComment(Comment comment) {
this.comment = comment;
}
public Comment getComment() {
return comment;
}
@Override
public void setCitizen(Citizen citizen2) {
Association.Voting.linkComment(citizen2, this, comment);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((comment == null) ? 0 : comment.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VoteComment other = (VoteComment) obj;
if(super.getCitizen().equals(other.getCitizen())) {
if (comment == null)
{
if (other.comment != null)
return false;
}
else if (!comment.equals(other.comment))
return false;
return true;
}
return false;
}
}
| 19.662338 | 73 | 0.700793 |
d9452a0e169435fc0330e4124a06f10bf3499bac | 4,534 | /*
* BasicWorkflows Module
* %%
* Copyright (C) 2012 - 2018 e-Spirit AG
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.espirit.moddev.basicworkflows.util;
import de.espirit.firstspirit.agency.OperationAgent;
import de.espirit.firstspirit.ui.operations.RequestOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class DialogTest {
@Rule
public BaseContextRule contextRule = new BaseContextRule();
private Dialog testling;
private RequestOperation requestOperation;
private boolean verify = true;
@Before
public void setUp() throws Exception {
testling = new Dialog(contextRule.getContext());
OperationAgent operationAgent = mock(OperationAgent.class);
when(contextRule.getContext().requireSpecialist(OperationAgent.TYPE)).thenReturn(operationAgent);
requestOperation = mock(RequestOperation.class);
when(operationAgent.getOperation(RequestOperation.TYPE)).thenReturn(requestOperation);
final RequestOperation.Answer answer = mock(RequestOperation.Answer.class);
when(requestOperation.perform("message")).thenReturn(answer);
}
@After
public void tearDown() throws Exception {
if (verify) {
verify(requestOperation).setTitle("title");
verify(requestOperation).perform("message");
}
}
@Test(expected = IllegalArgumentException.class)
public void testConstructor() throws Exception {
verify = false;
new Dialog(null);
}
@Test(expected = IllegalArgumentException.class)
public void testShowDialogNullKind() throws Exception {
verify = false;
testling.showDialog(null, Dialog.QuestionType.NONE, "title", "message");
}
@Test(expected = IllegalArgumentException.class)
public void testShowDialogNullType() throws Exception {
verify = false;
testling.showDialog(RequestOperation.Kind.INFO, null, "title", "message");
}
@Test(expected = IllegalArgumentException.class)
public void testShowDialogNullTitle() throws Exception {
verify = false;
testling.showDialog(RequestOperation.Kind.INFO, Dialog.QuestionType.NONE, null, "message");
}
@Test(expected = IllegalArgumentException.class)
public void testShowDialogNullMessage() throws Exception {
verify = false;
testling.showDialog(RequestOperation.Kind.INFO, Dialog.QuestionType.NONE, "title", null);
}
@Test
public void testShowDialog() throws Exception {
final boolean result = testling.showDialog(RequestOperation.Kind.INFO, Dialog.QuestionType.NONE, "title", "message");
assertFalse("Info dialog returns always false", result);
}
@Test
public void testShowInfo() throws Exception {
testling.showInfo("title", "message");
verify(requestOperation).setKind(RequestOperation.Kind.INFO);
}
@Test
public void testShowError() throws Exception {
testling.showError("title", "message");
verify(requestOperation).setKind(RequestOperation.Kind.ERROR);
}
@Test
public void testShowQuestionYesNo() throws Exception {
final boolean result = testling.showQuestion(Dialog.QuestionType.YES_NO, "title", "message");
assertFalse("Question dialog should return false because we have no UI", result);
verify(requestOperation).setKind(RequestOperation.Kind.QUESTION);
}
@Test
public void testShowQuestionOkCancel() throws Exception {
final boolean result = testling.showQuestion(Dialog.QuestionType.OK_CANCEL, "title", "message");
assertFalse("Question dialog should return false because we have no UI", result);
verify(requestOperation).setKind(RequestOperation.Kind.QUESTION);
}
}
| 32.618705 | 125 | 0.711734 |
dfa3906338cba142c12cb8bbc3d6bc8b0b819463 | 21,952 | /*
* Copyright (c) 2020, https://github.com/911992 All rights reserved.
* License BSD 3-Clause (https://opensource.org/licenses/BSD-3-Clause)
*/
/*
WAsys_pojo_http_data
File: Fillable_Object_Parser.java
Created on: May 13, 2020 10:49:43 PM
@author https://github.com/911992
History:
0.3.3 (20200829)
• Small documentation fix
0.2.5 (20200813)
• Calling related getter of Field_Definition based on annotated field's type
• Fixes/changes becasue of Field_Definition and Fillable_Object_Field_Signature types changes
0.2.1 (20200724)
• Updated parse_field method to support new type policy about ignorring fields started with double-underscore "__" (and are not Field_Definition).
0.2 (20200605)
• Added some documentation
• Using ArrayList(non thread-safe) instead of Vector(thread-safe), as the Fillable_Object_Parse_Result constructor now works the same way
• Changed method find_marked_setter_method(:Class,:String,:Class):Method signature to find_marked_setter_method(:Class,:Field):Method
0.1.6 (20200525)
• Finding fields in reflection mode as parent-to-child fields order now
0.1.3 (20200521)
• Updated the header(this comment) part
• Added some javadoc
initial version: 0.1(20200510)
*/
package wasys.lib.pojo_http_data;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import wasys.lib.pojo_http_data.api.Fillable_Object;
import wasys.lib.pojo_http_data.api.Fillable_Object_Adapter;
import wasys.lib.pojo_http_data.api.Fillable_Object_Field_Signature;
import wasys.lib.pojo_http_data.api.Object_Fill_Mode;
import wasys.lib.pojo_http_data.api.Fillable_Object_Manipulator;
import wasys.lib.pojo_http_data.api.annotations.Field_Definition;
import wasys.lib.pojo_http_data.api.annotations.Field_Setter_Method;
import wasys.lib.pojo_http_data.api.annotations.No_Param;
import wasys.lib.pojo_http_data.api.annotations.No_Type_Cache;
import wasys.lib.pojo_http_data.api_ex.Fillable_Object_Parse_Cache_Accelerator;
/**
* Default {@link Fillable_Object} type parser.
* <p>
* Parses a {@link Fillable_Object} following the APi specific std. It also would cache the type fingerprint internally(or by the type cache accelerator/cache ({@link Fillable_Object_Parse_Cache_Accelerator})
* </p>
* <p>
* This class is part of default-impl of this lib, and could be replaced with another module that performs the POJO({@link Fillable_Object}) parsing.
* </p>
* @author https://github.com/911992
*/
public class Fillable_Object_Parser {
/**
* List of types, would be filled using an associated setter method, or directly by related field reflected pointer.
* <p>
* List contains String, all primitives, and their wrappers (except for char, and boolean types)
* </p>
* <p>
* Any filler/http-req implementation may support for more type, but the types are given here are essentially require.
* </p>
* <p>
* Any field that could be listed as this list should be filled explicitly using teh field reflected ptr, or associated setter method.
* </p>
*/
private static final Class FILLABLE_TYPES[] = {
byte.class, short.class, int.class, long.class, float.class, double.class,
Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class,
String.class
};
/**
* List of fields that should not be filled explicitly(unlike defined in {@code FILLABLE_TYPES}).
* <p>
* Types listed may or may not have some dedicated processes during POJO filling.
* </p>
* <p>
* Having a setter(neitehr getter) method for fields come with types included are not essential, however please refer to the filler, that may perform some out-of spec behavior.
* </p>
* <p>
* <b>Note:</b> Types defined in this array, may be abstract types(such as {@link OutputStream}), this means the target field should an inherited child.
* </p>
* <p>
* For more information, please refer to repo(home page) readme file.
* </p>
*/
private static final Class INHERITABLE_FILLABLE_TYPES[] = {
Fillable_Object.class, OutputStream.class
};
/**
* Pointer to {@link Fillable_Object_Signature_Context} instance(probably the global/singleton).
* <p>
* Depending to caching scope, this instance could be at jvm/application, or session, etc... level.
* </p>
* <p>
* By default the reference is supposed to be global across the application(considering singleton).
* </p>
*/
private static final Fillable_Object_Signature_Context ctx = Fillable_Object_Signature_Context.get_instance();
/**
* Default constructor as private, since there is no need for any object of this type, as all methods are static.
*/
private Fillable_Object_Parser() {
}
/**
* Tries to return the already parsed given {@code arg_obj} type, or attempt to parse and return.
* <p>
* It asks the local {@code ctx:}{@link Fillable_Object_Signature_Context} to find a signature of given {@link Fillable_Object} object, if any.
* </p>
* <p>
* This is {@link Fillable_Object_Signature_Context} policy to either return already exist obj type cache, or null to force the parser perform another object parsing.
* </p>
* <p>
* <b>Note:</b> The fast-global cache lookup is done at {@link Fillable_Object_Signature_Context} side.
* </p>
* <p>
* <b>Note:</b> this method is not thread-safe, so calling for cache look up may result an unexpected data. But mind method(s) are related for context data manipulation(add/remove) will be essentially thread-safe.
* </p>
* <p>
* <b>Important Note:</b> if the given {@code arg_obj} is annotated with a {@link No_Type_Cache}, then once it's parsed, it won't be placed at central type signature cache as {@link Fillable_Object_Signature_Context}
* </p>
* @param arg_obj the non-null
* @return a non-null successful type fingerprint, or <b>{@code null}</b> if the given {@code arg_obj} is not fillable.
* @throws NullPointerException if the give {@code null} is null.
*/
static Fillable_Object_Parse_Result find_or_parse_object(Fillable_Object arg_obj) {
Fillable_Object_Parse_Result _res = ctx.find_result(arg_obj);
if (_res != null) {
return _res;
}
return parse_object(arg_obj);
}
/**
* Tries to find or parse the given {@code arg_obj:}{@link Fillable_Object}.
* <p>
* <b>Note:</b> This method is called by {@code find_or_parse_object()} method, that performs a lookup over context, and then ask this method for parsing.
* <br>
* However, this method asks the {@code ctx:}{@link Fillable_Object_Signature_Context} <b>AGAIN</b>, but in a thread-safe manner mode, in order to avoid any thread related issues.
* </p>
* <p>There is no exception, but if the given {@code arg_obj} has no any field for filling, then a {@code null} will be returned, and the cache won't be saved.</p>
* @param arg_obj a non-{@code null} instance of a concreted pojo
* @return a type signature cache(with at-least one field cache) if given {@code arg_obj} has a right type definition for filling, or {@code null} otherwise.
*/
static private Fillable_Object_Parse_Result parse_object(Fillable_Object arg_obj) {
Class _type = arg_obj.getClass();
synchronized (_type) {
Fillable_Object_Parse_Result _res = ctx.find_result(arg_obj);
if (_res != null) {
return _res;
}
Fillable_Object_Field_Signature _field_signatures[];
Object_Fill_Mode _parse_fill_mode = arg_obj.fill_mode();
if (_parse_fill_mode == Object_Fill_Mode.Type_Manipulator) {
Fillable_Object_Manipulator _desc = arg_obj.get_type_descriptor();
_field_signatures = _desc.get_field_signatures();
} else {
ArrayList<Field> _fields = new ArrayList<Field>();
get_all_fields(_type, _fields);
_field_signatures = new Fillable_Object_Field_Signature[_fields.size()];
for (int a = 0; a < _fields.size(); a++) {
Field _fi = _fields.get(a);
_fi.setAccessible(true);
Fillable_Object_Field_Signature _field_sig = parse_field(_fi);
_field_signatures[a] = _field_sig;
}
}
ArrayList<Fillable_Object_Field_Signature_Cache> _cached_sigs = new ArrayList<Fillable_Object_Field_Signature_Cache>(_field_signatures.length);
for (int a = 0; a < _field_signatures.length; a++) {
Fillable_Object_Field_Signature _sig_ins = _field_signatures[a];
if (_sig_ins == null) {
continue;
}
Field _field_ins = find_field(_type, _sig_ins.getEntity_field_name());
if (_field_ins == null || (is_field_fillable(_field_ins) == false)) {
continue;
} else if (_parse_fill_mode == Object_Fill_Mode.Reflection_Type_Fields && field_should_be_ignorred(_field_ins)) {
continue;
}
_field_ins.setAccessible(true);
Method _setter_method = setter_method_from_field(_field_ins, _type);
if (_setter_method != null) {
_setter_method.setAccessible(true);
}
Fillable_Object_Field_Signature_Cache _sig_cache = new Fillable_Object_Field_Signature_Cache(_sig_ins, _field_ins, _setter_method);
_cached_sigs.add(_sig_cache);
}
_cached_sigs.trimToSize();
if (_cached_sigs.size() == 0) {
return null;
}
_res = new Fillable_Object_Parse_Result(_type, _cached_sigs);
boolean _fast = (arg_obj instanceof Fillable_Object_Parse_Cache_Accelerator);
if (_fast) {
Fillable_Object_Parse_Cache_Accelerator _acc = (Fillable_Object_Parse_Cache_Accelerator) arg_obj;
_acc._api_ex_set_type_parse_result(_res);
}
No_Type_Cache _no_cache = (No_Type_Cache)_type.getAnnotation(No_Type_Cache.class);
if(_no_cache==null){
ctx.add_result_to_ctx(_res);
}
return _res;
}
}
/**
* Checks if a fillable field should ignored.
* <p>It check if the given {@code arg_field} carry a {@link No_Param} annotation, that tells the filler/parser to explicitly ignore the field, regardless if it's fillable or not.</p>
* @param arg_field the field should be checked
* @return {@code true} if the field is annotated with {@link No_Param}, {@code false} otherwise
*/
private static boolean field_should_be_ignorred(Field arg_field) {
No_Param _not_a_param = arg_field.getAnnotation(No_Param.class);
return _not_a_param != null;
}
/**
* Checks if the field is a fillable or not.
* <p>It simply checks if the field's type either is listed in {@code FILLABLE_TYPES} array, or assignable to types of {@code INHERITABLE_FILLABLE_TYPES} array.</p>
* @param arg_field the field should be checked if it's a fillable one
* @return {@code true} if the field could be filled, {@code false} otherwise.
*/
private static boolean is_field_fillable(Field arg_field) {
int _mods = arg_field.getModifiers();
if (Modifier.isStatic(_mods)) {
return false;
}
Class _f_type = arg_field.getType();
Class _tp;
for (int a = 0; a < FILLABLE_TYPES.length; a++) {
_tp = FILLABLE_TYPES[a];
if (_tp == _f_type) {
if (Modifier.isFinal(_mods)) {
break;
}
return true;
}
}
for (int a = 0; a < INHERITABLE_FILLABLE_TYPES.length; a++) {
_tp = INHERITABLE_FILLABLE_TYPES[a];
if (_f_type == _tp || _tp.isAssignableFrom(_f_type)) {
return true;
}
}
return false;
}
/**
* Parse the given field, and returns the signature.
* <p>
* Check if the given field is a fillable type (by calling {@code is_field_fillable} method), or not.
* </p>
* <p>
* By default, if field has a associated {@link Field_Definition}, it consider the value of {@code param_name}(form annotation) as param name.
* </p>
* <p>
* If field has no annotation, or the param name is empty(default), then it consider the name of the field as the name of the param should be looked up of target http request.
* </p>
* <p>
* By existing the {@link Field_Definition}, it also grabs the other meta info of the field, such as being nullable, min, max, etc...
* </p>
* @param arg_field the field need to be parsed
* @return the field signature if the field is fillable, or {@code null} otherwise
*/
private static final Fillable_Object_Field_Signature parse_field(Field arg_field) {
boolean _is_fillable = is_field_fillable(arg_field);
if (_is_fillable == false) {
return null;
}
Class _ftyp = arg_field.getType();
Field_Definition _fannot = arg_field.getAnnotation(Field_Definition.class);
if (_fannot == null) {
if(_ftyp.getName().startsWith("__")){
return null;
}
return new Fillable_Object_Field_Signature(arg_field.getName(), _ftyp);
}
String _param_name = _fannot.param_name();
if (_param_name == null || _param_name.length() == 0) {
_param_name = arg_field.getName();
}
Number _min_val;
Number _max_val;
if(_ftyp == float.class || _ftyp == Float.class || _ftyp == double.class || _ftyp == Double.class){
_min_val = _fannot.min_float_point_val();
_max_val = _fannot.max_float_point_val();
}else{
_min_val = _fannot.min_val_or_len();
_max_val = _fannot.max_val_or_len();
}
return new Fillable_Object_Field_Signature(_param_name, _fannot.param_idx(), arg_field.getName(), _ftyp, _fannot.nullable(), _min_val,_max_val);
}
/**
* Tries to find the setter method for a field.
* <p>
* A setter method could be defined for the field either implicitly, or explicitly.
* </p>
* <p>
* The explicit way is doe using explicitly defined method name using {@link Field_Definition} by related field, or using {@link Field_Setter_Method} by a method(first index found).
* </p>
* <p>
* Please considering following steps are taken to find a setter method for the field, if the first one fails, it goes for second and so on.
* </p>
* <ol>
* <li>Method name that defined by {@link Field_Definition}, and exist, and comes with correct signature.</li>
* <li>Method name that that annotated by {@link Field_Setter_Method}, and name equals to the field name (<b>NOTE:</b> field name, not param name), and comes with a correct signature.</li>
* <li>Method name that comes with java std common name as {@code setAaa}, where {@code aaa} is the name of the field, and comes with correct signature.</li>
* </ol>
* <p>
* If there is no any setter method, the field still be able to get filled, by direct/explicit field accessing using its reflected pointer.
* </p>
* @param arg_field the field need to be used for looking up its setter method
* @param arg_type type of the POJO {@link Fillable_Object} that hosts the {@code arg_field}
* @return a valid reflected method ptr, that marked/found as setter method for give {@code arg_field}, or {@code null} otherwise
*/
private static Method setter_method_from_field(Field arg_field, Class arg_type) {
Method _mres;
Field_Definition _fannot = (Field_Definition) arg_field.getAnnotation(Field_Definition.class);
if (_fannot != null) {
String _method_name = _fannot.setter_method_name();
_mres = find_method(arg_type, _method_name, arg_field.getType());
} else {
_mres = null;
}
if (_mres == null) {
_mres = find_marked_setter_method(arg_type, arg_field);
}
if (_mres == null) {
String _field_name = arg_field.getName();
String _method_name = String.format("set%c%s", Character.toUpperCase(_field_name.charAt(0)), _field_name.substring(1));
_mres = find_method(arg_type, _method_name, arg_field.getType());
}
return _mres;
}
/**
* Tries to find a method with the given signature.
* <p>
* This method tries to find a method that accepts(as arg) the given {@code arg_arg_input}, and comes with given {@code arg_method_name} from type {@code arg_type}
* </p>
* <p>
* If there is no such method, it will return null.
* </p>
* @param arg_type the type/class(which is supposed to be a {@link Fillable_Object}) of POJO need to be checked
* @param arg_method_name name of the method should be checked
* @param arg_arg_input the only argument input type method must have
* @return a valid method reflected pointer that comes with signature given, or {@code null} otherwise
*/
private static Method find_method(Class arg_type, String arg_method_name, Class arg_arg_input) {
do {
try {
Method _m = arg_type.getDeclaredMethod(arg_method_name, arg_arg_input);
int _mods = _m.getModifiers();
if(!Modifier.isStatic(_mods)){
return _m;
}
} catch (Exception e) {
}
} while ((arg_type = arg_type.getSuperclass()) != Object.class);
return null;
}
/**
* Search through all defined methods of given {@code arg_type} type, to find an explicitly setter method.
* <p>
* This method is called when a field has not set any explicitly setter method with its {@link Field_Definition} annotation.
* </p>
* <p>
* Any method that comes without a {@link Field_Setter_Method} annotation will be skipped.
* </p>
* <p>
* Then parser tries to find any explicitly marked method(regardless of its name) that would point out to the given {@code arg_field_name}
* </p>
* <p>
* The target marked method must come with correct signature. It must accepts only one input arg, with the expected given {@code arg_field} type.
* </p>
* @param arg_type the type needs to be looking up the method(probably a {@link Fillable_Object})
* @param arg_field the field should be considered, to find its marked setter method
* @return a valid annotated method that works as a setter for given {@code arg_field}, or {@code null} otherwise
*/
private static Method find_marked_setter_method(Class arg_type, Field arg_field) {
Method _methods[];
Method _m;
String _field_name = arg_field.getName();
Class _field_type = arg_field.getType();
do {
_methods = arg_type.getDeclaredMethods();
for (int a = 0; a < _methods.length; a++) {
_m = _methods[a];
Field_Setter_Method _set_annot = _m.getAnnotation(Field_Setter_Method.class);
if (_set_annot != null && _set_annot.name().equals(_field_name) && _m.getParameterCount() == 1 && _m.getParameterTypes()[a].isAssignableFrom(_field_type)) {
return _m;
}
}
} while ((arg_type = arg_type.getSuperclass()) != Object.class);
return null;
}
/**
* Tries to find a field from the given type.
* @param arg_type the type need to be looked up
* @param arg_field_name the field name should be searched
* @return a field reflected ptr that can be used(exist) for give {@code arg_type}, or {@code null} otherwise.
*/
private static Field find_field(Class arg_type, String arg_field_name) {
do {
try {
return arg_type.getDeclaredField(arg_field_name);
} catch (Exception e) {
}
} while ((arg_type = arg_type.getSuperclass()) != Object.class);
return null;
}
/**
* Return all fields from top-level parent to this(child) order.
* <p>
* It grabs and return a list of all inherited, and self-declared fields of given {@code arg_type}
* </p>
* <p>
* <b>Important note:</b> The order is from top-parent to child as field were declared first come with lower index.
* </p>
* <p>
* <b>Important Note:</b> Field scraping stop at a parent it's the top level {@link Object}, or {@link Fillable_Object_Adapter} type.
* </p>
* @param arg_type the type need to be scraped
* @param arg_to_ctx the context field should be put
* @return number of fields have scraped and added to the given {@code arg_to_ctx}
*/
private static int get_all_fields(Class arg_type, ArrayList<Field> arg_to_ctx) {
int _res = 0;
do {
Field[] _dfs = arg_type.getDeclaredFields();
arg_to_ctx.ensureCapacity(_dfs.length + arg_to_ctx.size());
for (int a = 0; a < _dfs.length; a++) {
arg_to_ctx.add(a,_dfs[a]);
_res++;
}
arg_type = arg_type.getSuperclass();
} while (arg_type != Object.class && arg_type != Fillable_Object_Adapter.class);
return _res;
}
}
| 47.515152 | 220 | 0.646547 |
88cdc138ef8dce5f598b2246ddb2d6798cc8dd7f | 85 | package org.distributeme.core.locator;
public interface BService extends Parent{
}
| 14.166667 | 41 | 0.811765 |
ae23244a613e427b2a258750ddf0ae554c498799 | 619 | package com.CashOnline.dto;
import com.CashOnline.model.Loan;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.Page;
import java.util.List;
import java.util.stream.Collectors;
@Getter
@Setter
public class LoanPageDto {
private List<LoanResponseDto> items;
private PagingInformationDto paging;
public LoanPageDto(Page<Loan> loans) {
this.items = loans.getContent().stream().map(loan -> new LoanResponseDto(loan)).collect(Collectors.toList());
this.paging = new PagingInformationDto(loans.getNumber() + 1, loans.getSize(), loans.getTotalPages());
}
}
| 28.136364 | 117 | 0.74475 |
46beb029fbe263678bddb3d152966921a4130e1e | 554 | package com.mmadu.identity.models.user;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
public class MmaduUserImpl implements MmaduUser {
@JsonProperty("id")
private String id;
@JsonProperty("domainId")
private String domainId;
@JsonProperty("username")
private String username;
@JsonProperty("authorities")
private List<String> authorities;
@JsonProperty("roles")
private List<String> roles;
@JsonProperty("groups")
private List<String> groups;
}
| 24.086957 | 53 | 0.727437 |
335ef7be140253141bd61f6aec33e401972f30c5 | 1,800 | /*
* 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.dubbo.remoting.utils;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
public class PayloadDropper {
private static Logger logger = LoggerFactory.getLogger(PayloadDropper.class);
/**
* only log body in debugger mode for size & security consideration.
*
* @param message
* @return
*/
public static Object getRequestWithoutData(Object message) {
if (logger.isDebugEnabled()) {
return message;
}
if (message instanceof Request) {
Request request = (Request) message;
request.setData(null);
return request;
} else if (message instanceof Response) {
Response response = (Response) message;
response.setResult(null);
return response;
}
return message;
}
}
| 36.734694 | 81 | 0.697222 |
def7faa03897451773bd1f3d0c65d3cc7dff51db | 232 | package com.dust.exception;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ValidationException extends RuntimeException {
public ValidationException(String message) {
super(message);
}
}
| 16.571429 | 59 | 0.75 |
58724af69ef9fe182869a46d1b7cdd55f8a206ca | 2,866 | /*
* Copyright 2019 The JIMDB Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.jimdb.core.model.result.impl;
import java.util.List;
import io.jimdb.core.model.result.ResultType;
import io.jimdb.core.expression.ColumnExpr;
import io.jimdb.core.model.result.ExecResult;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* @version V1.0
*/
@SuppressFBWarnings({ "EI_EXPOSE_REP", "EI_EXPOSE_REP2" })
public final class PrepareResult extends ExecResult {
private int stmtId;
private int columnsNum;
private int parametersNum;
private int warnCount;
private SQLStatement sqlStatement;
private List<SQLVariantRefExpr> params;
private long metaVersion;
private boolean useCache;
private ColumnExpr[] columnExprs;
public void setColumnExprs(ColumnExpr[] columnExprs) {
this.columnExprs = columnExprs;
}
@Override
public ColumnExpr[] getColumns() {
return columnExprs;
}
public void setStmtId(int stmtId) {
this.stmtId = stmtId;
}
public void setColumnsNum(int columnsNum) {
this.columnsNum = columnsNum;
}
public void setParametersNum(int parametersNum) {
this.parametersNum = parametersNum;
}
public void setWarnCount(int warnCount) {
this.warnCount = warnCount;
}
public int getStmtId() {
return stmtId;
}
public int getColumnsNum() {
return columnsNum;
}
public int getParametersNum() {
return parametersNum;
}
public int getWarnCount() {
return warnCount;
}
public SQLStatement getSqlStatement() {
return sqlStatement;
}
public void setSqlStatement(SQLStatement sqlStatement) {
this.sqlStatement = sqlStatement;
}
public List<SQLVariantRefExpr> getParams() {
return params;
}
public void setParams(List<SQLVariantRefExpr> params) {
this.params = params;
}
public long getMetaVersion() {
return metaVersion;
}
public void setMetaVersion(long metaVersion) {
this.metaVersion = metaVersion;
}
public boolean isUseCache() {
return useCache;
}
public void setUseCache(boolean useCache) {
this.useCache = useCache;
}
@Override
public ResultType getType() {
return ResultType.PREPARE;
}
public void close(){
}
}
| 21.22963 | 70 | 0.722261 |
feb9cec1090adb6d180a165a0c3e2845c460cce5 | 2,197 | package net.neczpal.interstellarwar.android;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import net.neczpal.interstellarwar.clientcommon.UserInterface;
import net.neczpal.interstellarwar.common.connection.RoomData;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
public class InterstellarWarActivity extends Activity implements UserInterface, Runnable {
private InterstellarWarView mInterstellarWarView;
private Thread drawThread = new Thread (this);
private boolean isRunning = false;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
mInterstellarWarView = new InterstellarWarView (this, LoginActivity.mConnection.getGameClient ());
setContentView (mInterstellarWarView);
Intent intent = getIntent ();
ActionBar actionBar = getActionBar ();
if (actionBar != null)
actionBar.setTitle (intent.getStringExtra ("MAP_NAME"));
LoginActivity.mConnection.setUserInterface (this);
drawThread.start ();
}
@Override
protected void onStop () {
super.onStop ();
isRunning = false;
}
@Override
public void onBackPressed () {
super.onBackPressed ();
LoginActivity.mConnection.leaveRoom ();
}
@Override
public void connectionReady () {
}
@Override
public void connectionDropped () {
finish ();
}
@Override
public void listRooms(JSONArray roomData) {
}
@Override
public void setIsInRoom (boolean b) {
}
@Override
public void startGame (String s) {
}
@Override
public void stopGame () {
finish ();
}
@Override
public void receiveMessage(int uid, String uname, int roomIndex, String message) {
Log.w("IW", "receiveMessage not yet implemented");
}
@Override
public void run () {
isRunning = true;
while (isRunning) {
try {
runOnUiThread (new Runnable () {
@Override
public void run () {
mInterstellarWarView.invalidate ();
}
});
Thread.sleep (50);
} catch (InterruptedException e) {
e.printStackTrace ();
}
}
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
| 20.92381 | 100 | 0.729631 |
cd811005a3de9765ec083203ea7efd81c9e54eb9 | 1,131 | package io.tracee.contextlogger.utility;
import java.lang.reflect.Field;
/**
* Utility class to access fields via reflection.
*/
public final class FieldUtilities {
/**
* Hidden constructor.
*/
private FieldUtilities() {
}
/**
* @param clazz the clazz to look in
* @param fieldName the name of the field
* @return the field or null, if no field with passed name can be found
* @throws IllegalArgumentException if clazz or fieldName parameters is null
*/
public static Field getField(Class clazz, String fieldName) throws IllegalArgumentException {
if (clazz == null || fieldName == null) {
throw new IllegalArgumentException("Class and fieldname parameters must not be null");
}
// check if field is in the class
Field field = null;
try {
field = clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
// not found in this class, should check parent
}
// check superclass if field couldn't be found
Class superClass = clazz.getSuperclass();
if (field == null && superClass != null) {
field = getField(superClass, fieldName);
}
return field;
}
}
| 24.586957 | 94 | 0.701149 |
dfd5afa4874e72886de95e7fa469aeb66e043c2d | 1,653 | package com.example.android.flickster.models;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Movie {
public String getPosterPath() {
return String.format("https://image.tmdb.org/t/p/w342/%s",posterPath);
}
public String getOriginalTitle() {
return originalTitle;
}
public String getBackdropPath() {
return String.format("https://image.tmdb.org/t/p/w342/%s",backdropPath);
}
public String getOverview() {
return overview;
}
public boolean isPopular(){
return rating>5.0;
}
String posterPath;
String originalTitle;
String overview;
String backdropPath;
public int getMovieID() {
return movieID;
}
int movieID;
double rating;
public Movie(JSONObject jsonObject) throws JSONException{
posterPath = jsonObject.getString("poster_path");
originalTitle = jsonObject.getString("original_title");
overview = jsonObject.getString("overview");
backdropPath = jsonObject.getString("backdrop_path");
rating = jsonObject.getDouble("vote_average");
movieID = jsonObject.getInt("id");
}
public static ArrayList<Movie> fromJSonArray(JSONArray array) {
ArrayList<Movie> results = new ArrayList<>();
int length = array.length();
for(int i = 0; i <length; i++) {
try {
results.add(new Movie(array.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return results;
}
}
| 25.828125 | 80 | 0.626134 |
74f14b876d77b9ed7c92dde226693900f46b7947 | 2,022 | /*
* Copyright 2017 Danish Maritime Authority.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.maritimeconnectivity.identityregistry.model.data;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.maritimeconnectivity.identityregistry.model.JsonSerializable;
import static io.swagger.v3.oas.annotations.media.Schema.AccessMode.READ_ONLY;
/**
* Object that bundles a PEM certificate with keystores in JKS and PKCS12 format and a password for the keystores
*
* @deprecated only used when issuing certificates with server generated keys. Will be removed in the future
*/
@AllArgsConstructor
@Getter
@Deprecated
@Schema(description = "Represents a bundle containing an PEM encoded certificate, keystores in JKS and PKCS#12 format " +
"and a password for the keystores. Will be removed in the future", deprecated = true)
public class CertificateBundle implements JsonSerializable {
@Schema(description = "The PEM encoded certificate", accessMode = READ_ONLY)
private PemCertificate pemCertificate;
@Schema(description = "JKS keystore containing certificate and private key", accessMode = READ_ONLY)
private String jksKeystore;
@Schema(description = "PKCS#12 keystore containing certificate and private key", accessMode = READ_ONLY)
private String pkcs12Keystore;
@Schema(description = "The password for the keystores", accessMode = READ_ONLY)
private String keystorePassword;
}
| 44.933333 | 121 | 0.772008 |
5653ad9e1ffa2ef51f56ca435383981ea8cd8920 | 1,852 | import java.util.ArrayList;
import java.util.List;
public class Scorer {
//List<Slide> slidelist;
public Scorer() {
// Set references to Photo
//this.slidelist = slidelist;
}
public int score(List<Slide> slideList) {
int ans = 0;
// Iterate all the slides
Slide lstSlide = null;
for(Slide slide: slideList) {
if(lstSlide == null) {
lstSlide = slide;
continue;
}
List<Integer> intersection = new ArrayList<>(lstSlide.tags);
intersection.retainAll(slide.tags);
List<Integer> lstSlideDif = new ArrayList<>(lstSlide.tags);
lstSlideDif.removeAll(intersection);
List<Integer> curSlideDif = new ArrayList<>(slide.tags);
curSlideDif.removeAll(intersection);
int sharedTagsCnt = intersection.size();
int lstSlideTagsCnt = lstSlideDif.size();
int curSlideTagsCnt = curSlideDif.size();
ans += Math.min(sharedTagsCnt, Math.min(lstSlideTagsCnt, curSlideTagsCnt));
lstSlide = slide;
}
return ans;
}
public int scoretwo(Slide s1,Slide s2) {
List<Integer> intersection = new ArrayList<>(s1.tags);
intersection.retainAll(s2.tags);
List<Integer> lstSlideDif = new ArrayList<>(s1.tags);
lstSlideDif.removeAll(intersection);
List<Integer> curSlideDif = new ArrayList<>(s2.tags);
curSlideDif.removeAll(intersection);
int sharedTagsCnt = intersection.size();
int lstSlideTagsCnt = lstSlideDif.size();
int curSlideTagsCnt = curSlideDif.size();
return Math.min(sharedTagsCnt, Math.min(lstSlideTagsCnt, curSlideTagsCnt));
}
}
| 30.866667 | 88 | 0.580994 |
9155cc6e76d5e3c7f96a7e7c356b7b18e7aeaaf6 | 2,497 | package br.com.caelum.cadastro;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import br.com.caelum.cadastro.dao.AlunoDAO;
import br.com.caelum.cadastro.dao.ComumDAO;
import br.com.caelum.cadastro.model.AlunoModel;
public class FormularioAlunosActivity extends Activity {
private static final int TIRAR_FOTO = 123;
private FormularioAlunoHelper helper;
private ComumDAO dao;
private AlunoModel aluno;
private AlunoDAO alunoDAO;
private String localFoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.formulario_alunos);
this.dao = new ComumDAO(this);
this.alunoDAO = new AlunoDAO(dao);
this.helper = new FormularioAlunoHelper(this);
Button btnSalvar = (Button) findViewById(R.id.botao);
ImageView foto = helper.getBotaoFoto();
foto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent iCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
localFoto = Environment.getExternalStorageDirectory() + "/"
+ System.currentTimeMillis() + ".jpg";
Uri local = Uri.fromFile(new File(localFoto));
iCamera.putExtra(MediaStore.EXTRA_OUTPUT, local);
startActivityForResult(iCamera, TIRAR_FOTO);
}
});
Intent intent = getIntent();
aluno = (AlunoModel) intent
.getSerializableExtra(Extras.ALUNO_SELECIONADO);
if (aluno != null) {
helper.populaAluno(aluno);
btnSalvar.setText("Alterar");
}
btnSalvar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlunoModel novoAluno = helper.getAlunoPopulado();
if (aluno != null) {
novoAluno.setId(aluno.getId());
}
alunoDAO.inserirOuAtualizar(novoAluno);
finish();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == TIRAR_FOTO){
if(resultCode == Activity.RESULT_OK){
helper.setFoto(localFoto);
}
}
}
@Override
protected void onStop() {
dao.close();
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
| 23.556604 | 80 | 0.734882 |
a4eef40f2c8455b6d4bf4bba330df4e630a45a59 | 5,987 | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.xquery;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class XQueryEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
XQueryEndpoint target = (XQueryEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "allowstax":
case "allowStAX": target.setAllowStAX(property(camelContext, boolean.class, value)); return true;
case "headername":
case "headerName": target.setHeaderName(property(camelContext, java.lang.String.class, value)); return true;
case "namespaceprefixes":
case "namespacePrefixes": target.setNamespacePrefixes(property(camelContext, java.util.Map.class, value)); return true;
case "resultsformat":
case "resultsFormat": target.setResultsFormat(property(camelContext, org.apache.camel.component.xquery.ResultFormat.class, value)); return true;
case "resulttype":
case "resultType": target.setResultType(property(camelContext, java.lang.Class.class, value)); return true;
case "stripsallwhitespace":
case "stripsAllWhiteSpace": target.setStripsAllWhiteSpace(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "pollstrategy":
case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "basicpropertybinding":
case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
case "configuration": target.setConfiguration(property(camelContext, net.sf.saxon.Configuration.class, value)); return true;
case "configurationproperties":
case "configurationProperties": target.setConfigurationProperties(property(camelContext, java.util.Map.class, value)); return true;
case "moduleuriresolver":
case "moduleURIResolver": target.setModuleURIResolver(property(camelContext, net.sf.saxon.lib.ModuleURIResolver.class, value)); return true;
case "parameters": target.setParameters(property(camelContext, java.util.Map.class, value)); return true;
case "properties": target.setProperties(property(camelContext, java.util.Properties.class, value)); return true;
case "staticquerycontext":
case "staticQueryContext": target.setStaticQueryContext(property(camelContext, net.sf.saxon.query.StaticQueryContext.class, value)); return true;
case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
case "backofferrorthreshold":
case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true;
case "backoffidlethreshold":
case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true;
case "backoffmultiplier":
case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true;
case "delay": target.setDelay(property(camelContext, long.class, value)); return true;
case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true;
case "initialdelay":
case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true;
case "repeatcount":
case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true;
case "runlogginglevel":
case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true;
case "scheduledexecutorservice":
case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true;
case "scheduler": target.setScheduler(property(camelContext, java.lang.String.class, value)); return true;
case "schedulerproperties":
case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true;
case "startscheduler":
case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true;
case "timeunit":
case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true;
case "usefixeddelay":
case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
}
| 70.435294 | 173 | 0.741607 |
1252d41d3f9287015a0433d855322fa9292dfbf3 | 3,174 | package com.wbars.php.folding.functionCallProviders;
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.ObjectUtils;
import com.jetbrains.php.lang.lexer.PhpTokenTypes;
import com.jetbrains.php.lang.psi.elements.BinaryExpression;
import com.jetbrains.php.lang.psi.elements.FunctionReference;
import com.wbars.php.folding.FoldingDescriptorBuilder;
import com.wbars.php.folding.NumberUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import static com.jetbrains.php.lang.psi.PhpPsiUtil.isOfType;
public class EmptinessCheckWithCountCallFoldingProvider extends FunctionCallFoldingProvider {
private static final TokenSet EQUALS_SET = TokenSet.create(PhpTokenTypes.opIDENTICAL, PhpTokenTypes.opEQUAL);
private static final TokenSet NOT_EQUALS_SET = TokenSet.create(PhpTokenTypes.opNOT_IDENTICAL, PhpTokenTypes.opNOT_EQUAL);
@Override
public String getCheckBoxName() {
return "Emptiness check with count/sizeof call";
}
@Override
public String getName() {
return "function_call_sizeof_condition";
}
@Override
protected boolean isAvailable(FunctionReference functionCall) {
return (StringUtil.equals(functionCall.getName(), "count") || StringUtil.equals(functionCall.getName(), "sizeof")) &&
functionCall.getParameters().length == 1;
}
@Override
public void addDescriptors(FunctionReference functionCall, List<FoldingDescriptor> descriptors) {
final BinaryExpression relation = ObjectUtils.tryCast(functionCall.getParent(), BinaryExpression.class);
if (relation != null) {
if (isOfType(relation.getOperation(), PhpTokenTypes.tsCOMPARE_OPS)) {
final String foldName = getFoldName(relation, functionCall);
final ASTNode nameNode = functionCall.getNameNode();
if (foldName != null && nameNode != null) {
final FoldingDescriptorBuilder fold = new FoldingDescriptorBuilder(functionCall, "count_empty", descriptors);
fold.fromStart(relation).toStart(functionCall).empty();
fold.text(nameNode.getPsi(), foldName);
fold.fromEnd(functionCall).toEnd(relation).empty();
}
}
}
}
@Nullable
private static String getFoldName(@NotNull BinaryExpression relation, @NotNull FunctionReference functionCall) {
final PsiElement leftOperand = relation.getLeftOperand();
final boolean functionCallIsLeftOperand = leftOperand == functionCall;
if (NumberUtils.isZero(functionCallIsLeftOperand ? relation.getRightOperand() : leftOperand)) {
final IElementType operationType = relation.getOperationType();
if (EQUALS_SET.contains(operationType)) {
return "empty";
}
else if (NOT_EQUALS_SET.contains(operationType) ||
(functionCallIsLeftOperand ? operationType != PhpTokenTypes.opLESS : operationType != PhpTokenTypes.opGREATER)) {
return "notEmpty";
}
}
return null;
}
}
| 41.220779 | 128 | 0.755829 |
1c2ed4cac3c2e8e729d43c9ffa10a0948477997b | 1,858 | /*
* Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.dynamodb.bootstrap;
import static org.junit.Assert.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.easymock.PowerMock.*;
import static org.easymock.EasyMock.expect;
import com.amazonaws.dynamodb.bootstrap.BlockingQueueConsumer;
/**
* Unit Tests for LogStashExecutor
*
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(BlockingQueueConsumer.class)
@PowerMockIgnore("javax.management.*")
public class BlockingQueueConsumerTest {
int totalThreads = 8;
/**
* Test the initialization of a BlockingQueueConsumer and make sure it adds
* the unique item to the end of the queue when shutting down.
*/
@Test
public void testInitializeAndShutdown() {
BlockingQueueConsumer logExec = new BlockingQueueConsumer(totalThreads);
mockStatic(Executors.class);
ExecutorService mockThreadPool = createMock(ExecutorService.class);
expect(Executors.newFixedThreadPool(totalThreads)).andReturn(
mockThreadPool);
BlockingQueue<DynamoDBEntryWithSize> queue = logExec.getQueue();
assertNotNull(queue);
assertEquals(queue.size(), 0);
logExec.shutdown(true);
assertEquals(queue.size(), 1);
DynamoDBEntryWithSize poisonPill = queue.poll();
assertNull(poisonPill.getEntry());
assertEquals(-1, poisonPill.getSize());
}
}
| 29.967742 | 80 | 0.740043 |
91b6be054105e1ea5fc6362ed1c33ff98cf25bf9 | 2,559 | package com.markgrand.moving_ratio;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This is a class that can be used to track the ratio of some subset of events to the total number of events. For
* example, the number of requests that produced an error result to the total number of requests. The ratio is
* maintained as a weighted moving average. More recent measurements have more weight than older measurements.
*
* <p>The way that it works is that there are two counters. These are referred to as counterA and counterB. Each can be
* incremented independently of the other.</p>
*
* <p> The counters are kept as 15 bit quantities. When any of the counters overflow, all the counters are
* right-shifted. These operations are thread-safe and do not block.</p>
*/
public class MovingWeightedRatio extends AbstractMovingWeightedRatio {
private static final int A_INCREMENT = 0x10000;
private static final int A_OVERFLOW_MASK = 0x80000000;
private static final int B_INCREMENT = 1;
private static final int B_OVERFLOW_MASK = 0x8000;
private static final int CLEAR_OVERFLOW_BITS_MASK = 0x7fff7fff;
private static final int LOW_ORDER_15_BITS_MASK = 0x7fff;
private final AtomicInteger counter = new AtomicInteger(0);
/**
* Increment counter A
*/
public void incrementCounterA() {
counter.updateAndGet(i -> {
int newValue = i + A_INCREMENT;
if ((newValue & A_OVERFLOW_MASK) != 0) {
newValue = (newValue >> 1) & CLEAR_OVERFLOW_BITS_MASK;
}
return newValue;
});
}
/**
* increment counter B
*/
public void incrementCounterB() {
counter.updateAndGet(i -> {
int newValue = i + B_INCREMENT;
if ((newValue & B_OVERFLOW_MASK) != 0) {
newValue = (newValue >> 1) & CLEAR_OVERFLOW_BITS_MASK;
}
return newValue;
});
}
/**
* compute A / B
*
* @return A / B unless B == 0. If B == 0 then return 0.
*/
public float getAOverB() {
int i = counter.get();
int b = i & LOW_ORDER_15_BITS_MASK;
int a = (i >> 16) & LOW_ORDER_15_BITS_MASK;
return ratio(a, b);
}
/**
* compute B / A
*
* @return B / A unless A == 0. If A == 0 then return 0.
*/
public float getBOverA() {
int i = counter.get();
int b = i & LOW_ORDER_15_BITS_MASK;
int a = (i >> 16) & LOW_ORDER_15_BITS_MASK;
return ratio(b, a);
}
}
| 32.392405 | 119 | 0.624853 |
f51a3210e61b14469103622a04628b0c7f997352 | 1,553 | package com.example.customer.service;
import com.example.customer.model.Customer;
import com.example.customer.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class CustomerServiceImpl implements CustomerService {
private final CustomerRepository customerRepository;
@Autowired
public CustomerServiceImpl(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@Transactional
@Override
public List<Customer> listAllCustomers() {
return customerRepository.listAllCustomers();
}
@Transactional
@Override
public void createCustomer(Customer customer) {
customerRepository.createCustomer(customer);
}
@Transactional
@Override
public Customer findCustomer(int id) {
return customerRepository.findCustomer(id);
}
// public List<Customer> findCustomer(String find) {
// return customerRepository.findCustomer(find);
// }
@Transactional
@Override
public void updateCustomer(Customer customer) {
customerRepository.updateCustomer(customer);
}
@Transactional
@Override
public void deleteCustomer(int id) {
customerRepository.deleteCustomer(id);
}
// public void deleteCustomer(Customer customer) {
// customerRepository.deleteCustomer(customer);
// }
}
| 26.775862 | 71 | 0.736639 |
cc04af0682b05a183812899ff866bd1ddbc0ec07 | 1,394 | package com.ice.mr.base;
import java.io.Serializable;
import java.util.List;
import org.apache.ibatis.annotations.Param;
/**
* 所有Dao基类
* @author maguangming
*
* @param <T>
*/
public interface IDao<T> {
/**
* 根据id查询对象
*/
public T findById(@Param("id") Serializable id);
/**
* 根据联合主键查询对象
*/
public T findById(java.util.Map<String, String> ids);
/**
* 根据实体查询对象
*/
public List<T> findByParam(@Param("obj") T param);
/**
* 根据map查询对象并分页
*/
public List<T> findByParamForPage(@Param("obj") PageParameter param);
/**
* 添加对象
* @param param 对象
* @return 对象id
*/
public Integer insert(T param);
/**
* 更新对象
* @param param 对象
* @param versionId 版本号
* @return 影响条数
*/
public Integer update(@Param("obj") T param,@Param("versionId") Integer versionId);
/**
* 根据主键删除对象
* @param id 主键
* @return 影响条数
*/
public Integer deleteById(@Param("id") Serializable id);
/**
* 根据主键删除对象
* @return 影响条数
*/
public Integer deleteById(java.util.Map<String, String> keys);
/**
* 更新封存
* @param id 主键
* @param val 值
* @param versionId 版本号(可空)
* @return
*/
public Integer updateSealFlag(@Param("id")Serializable id,@Param("val")Boolean val,@Param("versionId") Integer versionId);
}
| 19.09589 | 126 | 0.568867 |
6b66d9ffa9e6763afbb693b6c660f9da378254f4 | 4,199 | package com.vaani.leetcode.interval;
import com.vaani.dsa.ds.core.visual.Interval;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
/**
* https://leetcode.com/problems/insert-interval/
* <p>
* 57. Insert Interval
* Hard
* <p>
* Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
* <p>
* You may assume that the intervals were initially sorted according to their start times.
* <p>
* Example 1:
* <p>
* Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
* Output: [[1,5],[6,9]]
* <p>
* Example 2:
* <p>
* Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
* Output: [[1,2],[3,10],[12,16]]
* Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
* <p>
* NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
*/
/*
* <p>Solution: O(n): Iterate through each interval and check for each overlapping case
*/
public class InsertInterval {
public static void main(String[] args) throws Exception {
Interval i1 = new Interval(1, 2);
Interval i2 = new Interval(3, 5);
Interval i3 = new Interval(6, 7);
Interval i4 = new Interval(8, 10);
Interval i5 = new Interval(12, 16);
List<Interval> list = Arrays.asList(i1, i2, i3, i4, i5);
int[][] result = new InsertInterval.UsingDataModel().insert(new int[][]{
{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}
}, new int[]{2, 5});
Arrays.stream(result).map(x -> x[0] + " " + x[1]).forEach(System.out::println);
}
static class UsingDataModel {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<Interval> intervalList = Arrays.stream(intervals).map(intervalArr -> new Interval(intervalArr[0], intervalArr[1])).collect(Collectors.toList());
Interval newIntervalObj = new Interval(newInterval[0], newInterval[1]);
int start = newIntervalObj.start;
int end = newIntervalObj.end;
List<Interval> result = new LinkedList<>();
int i = 0;
// add all the intervals ending before newInterval starts
while (i < intervalList.size() && intervalList.get(i).end < start) {
result.add(intervalList.get(i++));
}
// merge all overlapping intervals to one considering newInterval
// Note we are updating start and end now
while (i < intervalList.size() && intervalList.get(i).start <= end) {
start = Math.min(start, intervalList.get(i).start);
end = Math.max(end, intervalList.get(i).end);
i++;
}
result.add(new Interval(start, end));
// add all the rest
while (i < intervalList.size()) {
result.add(intervalList.get(i++));
}
return result.stream().map(interval -> new int[]{interval.start, interval.end}).toArray(int[][]::new);
}
}
static class WithoutDataModel {
public int[][] insert(int[][] intervals, int[] newInterval) {
int start = newInterval[0];
int end = newInterval[1];
List<int[]> result = new LinkedList<>();
int i = 0;
// add all the intervals ending before newInterval starts
while (i < intervals.length && intervals[i][1] < start) {
result.add(intervals[i++]);
}
// merge all overlapping intervals to one considering newInterval
// Note we are updating start and end now
while (i < intervals.length && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
i++;
}
result.add(new int[]{start, end});
// add all the rest
while (i < intervals.length) {
result.add(intervals[i++]);
}
return result.toArray(int[][]::new);
}
}
}
| 37.491071 | 161 | 0.567754 |
6b76683a8f15580a1ef11e1407e1f063c0a22373 | 2,095 | /*
* Copyright (C) 2014.
*
* BaasBox - [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.baasbox.android.samples.aloa.activities.loaders;
import android.content.Context;
import com.baasbox.android.BaasHandler;
import com.baasbox.android.BaasResult;
import com.baasbox.android.RequestOptions;
import com.baasbox.android.RequestToken;
import com.baasbox.android.json.JsonArray;
import com.baasbox.android.json.JsonObject;
import com.baasbox.android.net.HttpRequest;
import com.baasbox.android.samples.aloa.Aloa;
import com.baasbox.android.samples.aloa.utils.BaasLoader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Andrea Tortorella on 11/08/14.
*/
public class ChannelsLoader extends BaasLoader<JsonObject,List<String>> {
public ChannelsLoader(Context context) {
super(context);
}
@Override
protected BaasResult<List<String>> remapResult(BaasResult<JsonObject> result) {
if (result.isFailed()){
return BaasResult.failure(result.error());
} else {
JsonObject value = result.value();
JsonArray channels = value.getObject("data").getArray("channels");
List<String> chs = new ArrayList<String>();
for (Object ch:channels){
chs.add(ch.toString());
}
return BaasResult.success(chs);
}
}
@Override
protected RequestToken load(BaasHandler<JsonObject> handler) {
return Aloa.box().rest(HttpRequest.GET,"scripts/channels",(JsonObject)null,true,handler);
}
}
| 32.734375 | 101 | 0.705012 |
89c7edfdda6abc6e2df7ae3f3c11ba660d0117c5 | 2,409 | import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class CountWorkingDays {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date startDate = sdf.parse(scan.nextLine());
Date endDate = sdf.parse(scan.nextLine());
Calendar s = Calendar.getInstance();
s.setTime(startDate);
Calendar e = Calendar.getInstance();
e.setTime(endDate);
e.add(Calendar.DATE, 1);
Date[] officialHolidays = getHolidaysDates(sdf);
int workingDays = 0;
for (Calendar i = s; i.before(e); i.add(Calendar.DATE, 1)) {
if(isWorkingDay(i, officialHolidays)){
workingDays++;
}
}
System.out.println(workingDays);
}
private static Date[] getHolidaysDates(SimpleDateFormat sdf) throws ParseException {
Date[] officialHolidays = new Date[11];
String[] officialHolidaysAsStrings = {
"01-01-2014", "03-03-2014", "01-05-2014", "06-05-2014",
"24-05-2014", "06-09-2014", "22-09-2014", "01-11-2014",
"24-12-2014", "25-12-2014", "26-12-2014"};
for (int i = 0; i < officialHolidays.length; i++) {
Date currentDate = sdf.parse(officialHolidaysAsStrings[i]);
officialHolidays[i] = currentDate;
}
return officialHolidays;
}
private static boolean isWorkingDay(Calendar date, Date[] officialHolidays) {
int currentDay = date.get(Calendar.DAY_OF_MONTH);
int currentMonth = date.get(Calendar.MONTH);
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == 7 || dayOfWeek == 1){
return false;
}
Calendar currentHoliday = Calendar.getInstance();
for (int j = 0; j < officialHolidays.length; j++) {
currentHoliday.setTime(officialHolidays[j]);
int currentHolidayDay = currentHoliday.get(Calendar.DAY_OF_MONTH);
int currentHolidayMonth = currentHoliday.get(Calendar.MONTH);
if(currentHolidayDay == currentDay && currentHolidayMonth == currentMonth){
return false;
}
}
return true;
}
}
| 31.697368 | 88 | 0.60523 |
7c2268455f22f49eb3a09260109dfadedb35d03e | 641 | package cz.mg.toolkit.component.window;
import cz.mg.toolkit.event.adapters.WindowStateAdapter;
import cz.mg.toolkit.event.events.WindowStateEvent;
import static cz.mg.toolkit.utilities.properties.PropertiesInterface.*;
public class DialogWindow extends Window {
public static final String DEFAULT_DESIGN_NAME = "dialog window";
public DialogWindow(Window parent) {
getEventListeners().addLast(new WindowStateAdapter(){
@Override
public void onEventEnter(WindowStateEvent e) {
setDisabled(parent, isOpened());
parent.redraw();
}
});
}
}
| 30.52381 | 71 | 0.678627 |
394f94eb6f96d535bdeac4095fae8fd8c900c410 | 3,254 | package chronosacaria.mcdar.entities;
import chronosacaria.mcdar.api.interfaces.Summonable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.attribute.DefaultAttributeContainer;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.data.DataTracker;
import net.minecraft.entity.data.TrackedData;
import net.minecraft.entity.data.TrackedDataHandlerRegistry;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.entity.passive.BeeEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.UUID;
public class BuzzyNestBeeEntity extends BeeEntity implements Summonable {
protected static final TrackedData<Optional<UUID>> SUMMONER_UUID;
public BuzzyNestBeeEntity(EntityType<? extends BuzzyNestBeeEntity> type, World world){
super(EntityType.BEE, world);
}
public static DefaultAttributeContainer.Builder createBuzzyNestBeeAttributes(){
return MobEntity.createMobAttributes()
.add(EntityAttributes.GENERIC_MAX_HEALTH, 15.0D)
.add(EntityAttributes.GENERIC_FLYING_SPEED, 2.5D)
.add(EntityAttributes.GENERIC_MOVEMENT_SPEED, 2.5D)
.add(EntityAttributes.GENERIC_ATTACK_DAMAGE, 5.0D)
.add(EntityAttributes.GENERIC_FOLLOW_RANGE, 48.0D);
}
protected void initDataTracker(){
super.initDataTracker();
this.dataTracker.startTracking(SUMMONER_UUID, Optional.empty());
}
public Optional<UUID> getSummonerUuid(){
return this.dataTracker.get(SUMMONER_UUID);
}
@Override
public void setSummonerUuid(@Nullable UUID uuid) {
this.dataTracker.set(SUMMONER_UUID, Optional.ofNullable(uuid));
}
@Override
public void setSummoner(Entity player) {
this.setSummonerUuid(player.getUuid());
}
public LivingEntity getSummoner(){
try {
Optional<UUID> uUID = this.getSummonerUuid();
return uUID.map(value -> this.world.getPlayerByUuid(value)).orElse(null);
} catch (IllegalArgumentException var2){
return null;
}
}
protected void mobTick(){
if (getSummoner() instanceof PlayerEntity){
if (getSummoner().getAttacker() != null){
this.setBeeAttacker(getSummoner().getAttacker());
}
if (getSummoner().getAttacking() != null){
this.setBeeAttacker(getSummoner().getAttacking());
}
}
super.mobTick();
}
private boolean setBeeAttacker(LivingEntity attacker){
if (attacker.equals(getSummoner()))
return false;
setAttacker(attacker);
return true;
}
public boolean tryAttack(Entity target){
if (target.equals(getSummoner()) || this.hasStung())
return false;
return super.tryAttack(target);
}
static {
SUMMONER_UUID = DataTracker.registerData(BuzzyNestBeeEntity.class, TrackedDataHandlerRegistry.OPTIONAL_UUID);
}
}
| 32.54 | 117 | 0.693301 |
c9291f5a8f89607e8a81a420944360d81218d42a | 1,080 | package E3_StackIterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
//SecondStack stackTwo = new SecondStack();
FirstStack stack = new FirstStack();
while (!(line = reader.readLine()).equals("END")) {
line = line.replaceAll(",", "");
String[] tokens = line.split("\\s+", 0);
if (tokens[0].equals("Push")) {
stack.push(Arrays.stream(tokens)
.skip(1)
.mapToInt(Integer::parseInt)
.boxed()
.toArray(Integer[]::new));
} else {
stack.pop();
}
}
for (Integer integer : stack) {
System.out.println(integer);
}
System.out.println(stack.toString());
}
}
| 28.421053 | 85 | 0.531481 |
2ac53b32cab2c1128fb20456e6574e45fd5a708c | 1,285 |
package Sesion8;
import java.io.*;
/**
* Esta clase copia el contenido de un archivo a otro archivo
*/
public class Copia2 {
public static void main(String[] args) {
try {
// Definicion de flujos para procesar el archivo fuente
FileReader archReader = new FileReader("archivo3");
BufferedReader bufReader = new BufferedReader(archReader);
// Definicion de flujos para procesar el archivo destino
FileWriter archWriter = new FileWriter("archivo22");
BufferedWriter bufWriter = new BufferedWriter(archWriter);
String fila;
// Realiza la copia
while ((fila = bufReader.readLine()) != null) {
bufWriter.write(fila);
bufWriter.newLine();
}
try {
// Cerrar archivos
bufReader.close();
bufWriter.close();
} catch (IOException e2) {
System.out.println("Ocurrio una excepcion al intentar cerrar los archivos");
e2.printStackTrace();
}
} catch (IOException e) {
System.out.println("Ocurrio una excepcion al intentar copiar");
e.printStackTrace();
}
}
} | 29.883721 | 92 | 0.554086 |
7585caba149e68e72cc70b6b97f6ede14478474b | 328 | package org.guppy4j.plankton.tempfiles;
/**
* Temp file manager.
* <p/>
* <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup
* temporary io created as a result of handling the request.</p>
*/
public interface TempFiles {
TempFile createNew() throws Exception;
void clear();
}
| 21.866667 | 89 | 0.707317 |
cfb6c4b7899391b6b5f25a3d4a49045b8f367fd1 | 5,000 | /*
* Copyright 2020 Jeremy KUHN
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.inverno.mod.web.internal;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import io.inverno.mod.http.base.Method;
import io.inverno.mod.http.base.MethodNotAllowedException;
import io.inverno.mod.http.server.Exchange;
import io.inverno.mod.http.server.ExchangeContext;
import io.inverno.mod.web.spi.MethodAware;
import io.inverno.mod.web.spi.Route;
import reactor.core.publisher.Mono;
/**
* <p>
* A routing link responsible to route an exchange based on the HTTP method as
* defined by {@link MethodAware}.
* </p>
*
* @author <a href="mailto:[email protected]">Jeremy Kuhn</a>
* @since 1.0
*
* @param <A> the type of the exchange context
* @param <B> the type of exchange handled by the route
* @param <C> the route type
*/
class MethodRoutingLink<A extends ExchangeContext, B extends Exchange<A>, C extends MethodAware & Route<A, B>> extends RoutingLink<A, B, MethodRoutingLink<A, B, C>, C> {
private final Map<Method, RoutingLink<A, B, ?, C>> handlers;
private Map<Method, RoutingLink<A, B, ?, C>> enabledHandlers;
/**
* <p>
* Creates a method routing link.
* </p>
*/
public MethodRoutingLink() {
super(MethodRoutingLink::new);
this.handlers = new HashMap<>();
this.enabledHandlers = Map.of();
}
private void updateEnabledHandlers() {
this.enabledHandlers = this.handlers.entrySet().stream()
.filter(e -> !e.getValue().isDisabled())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
@Override
public MethodRoutingLink<A, B, C> setRoute(C route) {
Method method = route.getMethod();
if (method != null) {
if (this.handlers.containsKey(method)) {
this.handlers.get(method).setRoute(route);
}
else {
this.handlers.put(method, this.nextLink.createNextLink().setRoute(route));
}
this.updateEnabledHandlers();
}
else {
this.nextLink.setRoute(route);
}
return this;
}
@Override
public void enableRoute(C route) {
Method method = route.getMethod();
if (method != null) {
RoutingLink<A, B, ?, C> handler = this.handlers.get(method);
if (handler != null) {
handler.enableRoute(route);
this.updateEnabledHandlers();
}
// route doesn't exist so let's do nothing
}
else {
this.nextLink.enableRoute(route);
}
}
@Override
public void disableRoute(C route) {
Method method = route.getMethod();
if (method != null) {
RoutingLink<A, B, ?, C> handler = this.handlers.get(method);
if (handler != null) {
handler.disableRoute(route);
this.updateEnabledHandlers();
}
// route doesn't exist so let's do nothing
}
else {
this.nextLink.disableRoute(route);
}
}
@Override
public void removeRoute(C route) {
Method method = route.getMethod();
if (method != null) {
RoutingLink<A, B, ?, C> handler = this.handlers.get(method);
if (handler != null) {
handler.removeRoute(route);
if (!handler.hasRoute()) {
// The link has no more routes, we can remove it for good
this.handlers.remove(method);
this.updateEnabledHandlers();
}
}
// route doesn't exist so let's do nothing
}
else {
this.nextLink.removeRoute(route);
}
}
@Override
public boolean hasRoute() {
return !this.handlers.isEmpty() || this.nextLink.hasRoute();
}
@Override
public boolean isDisabled() {
return this.handlers.values().stream().allMatch(RoutingLink::isDisabled) && this.nextLink.isDisabled();
}
@SuppressWarnings("unchecked")
@Override
public <F extends RouteExtractor<A, B, C>> void extractRoute(F extractor) {
if (!(extractor instanceof MethodAwareRouteExtractor)) {
throw new IllegalArgumentException("Route extractor is not method aware");
}
this.handlers.entrySet().stream().forEach(e -> {
e.getValue().extractRoute(((MethodAwareRouteExtractor<A, B, C, ?>) extractor).method(e.getKey()));
});
super.extractRoute(extractor);
}
@Override
public Mono<Void> defer(B exchange) {
if (this.handlers.isEmpty()) {
return this.nextLink.defer(exchange);
}
else {
RoutingLink<A, B, ?, C> handler = this.enabledHandlers.get(exchange.request().getMethod());
if (handler != null) {
return handler.defer(exchange);
}
else if (this.enabledHandlers.isEmpty()) {
return this.nextLink.defer(exchange);
}
else {
throw new MethodNotAllowedException(this.handlers.keySet());
}
}
}
}
| 28.248588 | 169 | 0.6896 |
0c9ec85b75dce71e5cb031a79af0cbe1e547e822 | 195 | package com.yandex.disk.client.exceptions;
public class RangeNotSatisfiableException extends WebdavException {
public RangeNotSatisfiableException(String msg) {
super(msg);
}
}
| 21.666667 | 67 | 0.758974 |
feea62e64f008368f24c7509ae5cc01fbd9e0721 | 989 | package com.yclouds.myhelper.web.convert;
import com.yclouds.myhelper.utils.DateUtils;
import com.yclouds.myhelper.utils.StringUtils;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import javax.annotation.Nonnull;
import org.springframework.core.convert.converter.Converter;
/**
* @author ye17186
* @version 2019/5/29 17:04
*/
public class StringToYearMonthConverter implements Converter<String, YearMonth> {
private String pattern;
public StringToYearMonthConverter() {
}
public StringToYearMonthConverter(String pattern) {
this.pattern = pattern;
}
@Override
public YearMonth convert(@Nonnull String source) {
YearMonth yearMonth = null;
if (StringUtils.isNotEmpty(source)) {
String format = StringUtils.isEmpty(pattern) ? DateUtils.PATTERN_DATE_01 : pattern;
yearMonth = YearMonth.parse(source, DateTimeFormatter.ofPattern(format));
}
return yearMonth;
}
}
| 28.257143 | 95 | 0.722952 |
63dbe3d6483ce5a3e6694e2c3a18927db00d3a3a | 1,465 | package eu.de4a.connector.mock.exampledata;
import eu.de4a.iem.xml.de4a.EDE4ACanonicalEvidenceType;
import eu.de4a.iem.xml.de4a.IDE4ACanonicalEvidenceType;
import lombok.Getter;
import java.util.Arrays;
public enum EvidenceID {
MARRIAGE_EVIDENCE("urn:de4a-eu:CanonicalEvidenceType::MarriageEvidence", EDE4ACanonicalEvidenceType.T43_MARRIAGE_EVIDENCE_V16B),
BIRTH_EVIDENCE("urn:de4a-eu:CanonicalEvidenceType::BirthEvidence", EDE4ACanonicalEvidenceType.T43_BIRTH_EVIDENCE_V16B),
DOMICILE_REGISTRATION_EVIDENCE("urn:de4a-eu:CanonicalEvidenceType::DomicileRegistrationEvidence", EDE4ACanonicalEvidenceType.T43_DOMREG_EVIDENCE_V16B),
COMPANY_REGISTRATION("urn:de4a-eu:CanonicalEvidenceType::CompanyRegistration", EDE4ACanonicalEvidenceType.T42_COMPANY_INFO_V06),
HIGHER_EDUCATION_DIPLOMA("urn:de4a-eu:CanonicalEvidenceType::HigherEducationDiploma", EDE4ACanonicalEvidenceType.T41_UC1_2021_04_13);
@Getter
private final String id;
@Getter
private final IDE4ACanonicalEvidenceType canonicalEvidenceType;
private EvidenceID(String id, IDE4ACanonicalEvidenceType canonicalEvidenceType) {
this.id = id;
this.canonicalEvidenceType = canonicalEvidenceType;
}
public static EvidenceID selectEvidenceId(String evidenceId) {
return Arrays.stream(EvidenceID.values())
.filter(eID -> eID.id.equals(evidenceId))
.findFirst()
.orElseGet(() -> null);
}
}
| 44.393939 | 155 | 0.779522 |
ceabbe22abdd173fc8c805e1f724be0e34f79e77 | 2,674 | package com.tiny.demo.firstlinecode.materialdesign;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.tiny.demo.firstlinecode.base.BaseActivity;
import com.tiny.demo.firstlinecode.R;
/**
* 水果详情页
*/
public class FruitDetailActivity extends BaseActivity {
public static final String FRUIT_NAME = "FRUIT_NAME";
public static final String FRUIT_IMG = "FRUIT_IMG";
private String name;
private Integer imgId;
public static void actionStart(Context context, Bundle bundle) {
Intent intent = new Intent(context, FruitDetailActivity.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
@Override
protected int setContentLayout() {
return R.layout.activity_fruit_detail;
}
@Override
protected void buildContentView() {
Intent intent = getIntent();
if (intent != null) {
name = intent.getStringExtra(FRUIT_NAME);
imgId = intent.getIntExtra(FRUIT_IMG, 0);
}
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
ImageView img = (ImageView) findViewById(R.id.fruit_image_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView txtContent = (TextView) findViewById(R.id.fruit_content_text);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
//设置收缩起来时toolBar的标题和展开时CollapsingToolbarLayout左下角的标题。
collapsingToolbarLayout.setTitle("童童");
Glide.with(mContext).load(imgId).into(img);
String fruitContent = generateFruitContent(name);
txtContent.setText(fruitContent);
}
private String generateFruitContent(String name) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 500; j++) {
sb.append(name).append(" --> ");
}
return sb.toString();
}
@Override
protected void initViewData() {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 32.216867 | 122 | 0.678758 |
b9c41bdd2c7eb1aa76034b99fe444a62239fa72e | 2,683 | /*
* Copyright 2016 Code Above Lab LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codeabovelab.dm.common.format;
import com.codeabovelab.dm.common.utils.Callback;
import com.codeabovelab.dm.common.utils.Callbacks;
import com.codeabovelab.dm.common.utils.Key;
import org.springframework.format.Formatter;
import org.springframework.util.Assert;
import java.text.ParseException;
import java.util.Locale;
import java.util.Set;
/**
* A wrapper which allow combine formatter with validation callbacks. <p/>
* Validation callbacks will be invoked on parse and on print.
*/
public class ValidableFormatter<T> implements Formatter<T>, SelfDescribedFormatter<T> {
private final Formatter<T> formatter;
private final Callback<T> objectValidator;
private final Callback<String> textValidator;
/**
*
* @param formatter
* @param objectValidator the callback in which do object validation after parsing and before printing
* @param textValidator the callback in which do text validation before parsing and after printing
*/
public ValidableFormatter(Formatter<T> formatter, Callback<T> objectValidator, Callback<String> textValidator) {
this.formatter = formatter;
Assert.notNull(this.formatter, "formatter is null");
this.objectValidator = objectValidator;
this.textValidator = textValidator;
Assert.isTrue(this.objectValidator != null || this.textValidator != null, "text and object validators is null");
}
@Override
public Set<Key<?>> getHandledMetatypes() {
return FormatterUtils.getHandledMetatypes(this.formatter);
}
@Override
public T parse(String text, Locale locale) throws ParseException {
Callbacks.call(this.textValidator, text);
T object = formatter.parse(text, locale);
Callbacks.call(this.objectValidator, object);
return object;
}
@Override
public String print(T object, Locale locale) {
Callbacks.call(this.objectValidator, object);
String text = formatter.print(object, locale);
Callbacks.call(this.textValidator, text);
return text;
}
}
| 36.256757 | 120 | 0.723817 |
1a811a75adf2c94337f7fd2d5f76a3c0995653d9 | 2,013 | package com.jumpwatch.tit.Utils;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorldReader;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import javax.annotation.Nullable;
public class EnergyUtils {
/**
* Pushes energy between two energy storages
*
* @param provider the energy provider
* @param receiver the energy receiver
* @param maxAmount the maximum amount to push
* @return the amount that actually got transferred
*/
public static int pushEnergy(IEnergyStorage provider, IEnergyStorage receiver, int maxAmount) {
int energySim = provider.extractEnergy(maxAmount, true);
int receivedSim = receiver.receiveEnergy(energySim, true);
int energy = provider.extractEnergy(receivedSim, false);
receiver.receiveEnergy(energy, false);
return energy;
}
/**
* Gets the energy storage at the specified position and direction
*
* @param world the world
* @param pos the position
* @param side the side
* @return the energy storage
*/
@Nullable
public static IEnergyStorage getEnergyStorage(IWorldReader world, BlockPos pos, Direction side) {
TileEntity te = world.getBlockEntity(pos);
if (te == null) {
return null;
}
return te.getCapability(CapabilityEnergy.ENERGY, side.getOpposite()).orElse(null);
}
/**
* Gets the energy storage at the specified position offset one block to the specified direction
*
* @param world the world
* @param pos the position
* @param side the side
* @return the energy storage
*/
@Nullable
public static IEnergyStorage getEnergyStorageOffset(IWorldReader world, BlockPos pos, Direction side) {
return getEnergyStorage(world, pos.relative(side), side.getOpposite());
}
} | 30.969231 | 107 | 0.690512 |
38fe37e45a601c4743f60d45d80ddfd5d07c0f25 | 494 | package edu.fiuba.algo3.modelo.grados;
import edu.fiuba.algo3.modelo.tablero.Dificultad;
public class Novato extends GradoDePolicia {
public Novato(){
this.tiempoDeViaje = 900;
this.tiempoDeDescanso = 8;
this.tiempoDeHeridaDeBala = 4;
this.dificultadMasFrecuente = new Dificultad("Facil");
this.dificultadMenosFrecuente = new Dificultad("Medio");
this.rarezaMasFrecuente = "comun";
this.rarezaMenosFrecuente = "valioso";
}
}
| 26 | 64 | 0.684211 |
09d2ec02f9c41e11c471ec535102e47078517531 | 3,472 | /*
* 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.netbeans.modules.xml.axi;
import java.util.List;
import org.netbeans.modules.xml.axi.visitor.AXIVisitor;
import org.netbeans.modules.xml.schema.model.SchemaComponent;
/**
* Abstract element.
*
* @author Samaresh ([email protected])
*/
public abstract class AbstractElement extends AXIContainer {
/**
* Creates a new instance of Element
*/
public AbstractElement(AXIModel model) {
super(model);
}
/**
* Creates a new instance of Element
*/
public AbstractElement(AXIModel model, SchemaComponent schemaComponent) {
super(model, schemaComponent);
}
/**
* Creates a proxy for this Element.
*/
public AbstractElement(AXIModel model, AXIComponent sharedComponent) {
super(model, sharedComponent);
}
/**
* Allows a visitor to visit this Element.
*/
public abstract void accept(AXIVisitor visitor);
/**
* Returns the MinOccurs.
*/
public String getMinOccurs() {
return minOccurs;
}
/**
* Sets the MinOccurs.
*/
public void setMinOccurs(String value) {
String oldValue = getMinOccurs();
if( (oldValue == null && value == null) ||
(oldValue != null && oldValue.equals(value)) ) {
return;
}
this.minOccurs = value;
firePropertyChangeEvent(PROP_MINOCCURS, oldValue, value);
}
/**
* Returns the MaxOccurs.
*/
public String getMaxOccurs() {
return maxOccurs;
}
/**
* Sets the MaxOccurs.
*/
public void setMaxOccurs(String value) {
String oldValue = getMaxOccurs();
if( (oldValue == null && value == null) ||
(oldValue != null && oldValue.equals(value)) ) {
return;
}
this.maxOccurs = value;
firePropertyChangeEvent(PROP_MAXOCCURS, oldValue, value);
}
/**
* true if #getMaxOccurs() and #getMinOccurs() allow multiciplity outside
* [0,1], false otherwise. This method is only accurate after the element
* has been inserted into the model.
*/
public boolean allowsFullMultiplicity() {
return !(getParent() instanceof Compositor &&
((Compositor)getParent()).getType() == Compositor.CompositorType.ALL);
}
protected String minOccurs = "1";
protected String maxOccurs = "1";
public static final String PROP_MINOCCURS = "minOccurs"; // NOI18N
public static final String PROP_MAXOCCURS = "maxOccurs"; // NOI18N
public static final String PROP_ELEMENT = "element"; // NOI18N
}
| 30.191304 | 77 | 0.638825 |
6d547b32caef6dd31aa2fef90c3588719ad06b9f | 527 | package iftorrent.gui.janelaConfiguracoes;
import iftorrent.gui.ferramentas.TuplaXY;
public class ConstantesJanelaConfiguracoes {
public static final String BOTAO_COR1 = "darksalmon";
public static final String BOTAO_COR2 = "gainsboro";
public static final TuplaXY BOTAO_TAMANHO2 = new TuplaXY(15, 15);
public static final Double TAMANHO_PADRAO = 350.0;
public static final String NOME_ARQUIVO_DIRETORIOS = "diretorios";
public static final String NOME_ARQUIVO_CONFIGURACOES = "config";
}
| 40.538462 | 71 | 0.764706 |
4e5989b8c4a42188df9b121358a29b4bec89f8f3 | 1,542 | package net.sf.esfinge.metadata.container.reading;
import static org.apache.commons.beanutils.PropertyUtils.setProperty;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import net.sf.esfinge.metadata.AnnotationReadingException;
import net.sf.esfinge.metadata.container.AnnotationReadingProcessor;
import net.sf.esfinge.metadata.container.ContainerTarget;
public class ReflectionReferenceReadingProcessor implements AnnotationReadingProcessor {
private String containerAnnotatedField;
private Field fieldAnn;
@Override
public void initAnnotation(Annotation an, AnnotatedElement elementWithMetadata) {
fieldAnn = (Field) elementWithMetadata;
containerAnnotatedField = fieldAnn.getName();
}
@Override
public void read(AnnotatedElement elementWithMetadata, Object container, ContainerTarget target) throws AnnotationReadingException {
try {
if(target == ContainerTarget.FIELDS)
{
Field field= (Field)elementWithMetadata;
setProperty(container, containerAnnotatedField,field);
}
else if(target == ContainerTarget.TYPE) {
Class clazz= (Class)elementWithMetadata;
setProperty(container, containerAnnotatedField,clazz);
}
else
{
setProperty(container, containerAnnotatedField,elementWithMetadata);
}
} catch (Exception e) {
throw new AnnotationReadingException("Cannot read and record the file "+elementWithMetadata+"in "+containerAnnotatedField,e);
}
}
} | 32.808511 | 134 | 0.771077 |
ed29135972a807da69d88bcfd07b63f27dd534e6 | 1,826 | /**
* Copyright 2012 Rainer Bieniek ([email protected])
*
* 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.bgp4j.netty.service;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import org.bgp4j.config.global.ApplicationConfiguration;
import org.bgp4j.netty.fsm.FSMRegistry;
import org.slf4j.Logger;
/**
* @author Rainer Bieniek ([email protected])
*
*/
public class BGPv4Service {
private @Inject Logger log;
private @Inject Instance<BGPv4Server> serverProvider;
private @Inject FSMRegistry fsmRegistry;
private @Inject ApplicationConfiguration applicationConfiguration;
private BGPv4Server serverInstance;
/**
* start the service
*
* @param configuration the initial service configuration
*/
public void startService() {
fsmRegistry.createRegistry();
if(applicationConfiguration.getBgpServerConfiguration()!= null) {
log.info("starting local BGPv4 server");
this.serverInstance = serverProvider.get();
serverInstance.startServer();
}
fsmRegistry.startFiniteStateMachines();
}
/**
* stop the running service
*
*/
public void stopService() {
fsmRegistry.stopFiniteStateMachines();
if(serverInstance != null)
serverInstance.stopServer();
fsmRegistry.destroyRegistry();
}
}
| 24.675676 | 76 | 0.734392 |
6084d5338e64bf5c49ec76d0b08796ef586032e9 | 376 | package gui;
import javax.swing.*;
import java.awt.*;
public class BoardGame extends JFrame {
public BoardGame() {
super("New Game");
SplashScreenLayout SSL = new SplashScreenLayout();
setSize(new Dimension(800,800));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().add(SSL);
setVisible(true);
}
}
| 23.5 | 58 | 0.654255 |
4c6c02b74203ec3f571b84f5d676d9966c19faf7 | 1,771 | package com.mygcc.api;
import com.mygcc.datacollection.Chapel;
import com.mygcc.datacollection.ExpiredSessionException;
import com.mygcc.datacollection.InvalidCredentialsException;
import com.mygcc.datacollection.NetworkException;
import com.mygcc.datacollection.Token;
import com.mygcc.datacollection.UnexpectedResponseException;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;
/**
* Chapel resource endpoint.
*
* Endpoint resource for accessing chapel information.
*/
@Path("/1/user")
public class ChapelResource extends MyGCCResource {
/**
* Handles authenticating user and returning their encrypted token.
*
* @param token Authorization token
* @return Response to client
*/
@Path("/chapel")
@GET
@Produces(MediaType.APPLICATION_JSON)
public final Response getChapelData(
@HeaderParam("Authorization") final String token) {
try {
Token auth = new Token(token);
Chapel chap = new Chapel(auth);
Map<String, Integer> chapelData = chap.getChapelData();
return Response.status(Response.Status.OK)
.entity(chapelData)
.type("application/json")
.build();
} catch (ExpiredSessionException e) {
return sessionExpiredMessage();
} catch (InvalidCredentialsException e) {
return invalidCredentialsException();
} catch (NetworkException e) {
return networkException();
} catch (UnexpectedResponseException e) {
return unexpectedResponseException();
}
}
}
| 32.2 | 71 | 0.673066 |
a081380e00a1744401da36c3d03912fc2dde1e2c | 1,734 | package fimEntityResolution.bitsets;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import javax.transaction.NotSupportedException;
import fimEntityResolution.Utilities;
import fimEntityResolution.interfaces.BitSetIF;
import fimEntityResolution.interfaces.IFRecord;
import fimEntityResolution.interfaces.SetPairIF;
public class Java_BitSet implements BitSetIF{
private BitSet bs = null;
public Java_BitSet(){
bs = new BitSet();
}
public Java_BitSet(int size){
bs = new BitSet(size);
}
public BitSetIF and(final BitSetIF other) {
Java_BitSet jother = (Java_BitSet)other;
bs.and(jother.bs);
return this;
}
public boolean get(int recordId) {
return bs.get(recordId);
}
public int getCardinality() {
return bs.cardinality();
}
public String getSupportString() {
return bs.toString();
}
public void set(int recordId) {
bs.set(recordId);
}
public void clearAll() {
bs.clear();
}
public BitSetIF or(final BitSetIF other) throws NotSupportedException {
bs.or(((Java_BitSet)other).bs);
return this;
}
public List<IFRecord> getRecords() {
List<IFRecord> retVal = new ArrayList<IFRecord>(bs.cardinality());
for(int i=bs.nextSetBit(1); i>=0; i=bs.nextSetBit(i+1)){
retVal.add(Utilities.globalRecords.get(i));
}
return retVal;
}
public int markPairs(SetPairIF spf, double score) {
int cnt =0;
for(int i=bs.nextSetBit(0); i>=0; i=bs.nextSetBit(i+1)) {
for(int j=bs.nextSetBit(i+1); j>=0; j=bs.nextSetBit(j+1)) {
spf.setPair(i, j,score);
cnt++;
}
}
return cnt;
}
public void orInto(BitSetIF other) {
for(int i=bs.nextSetBit(0); i>=0; i=bs.nextSetBit(i+1)) {
other.set(i);
}
}
}
| 18.252632 | 72 | 0.689158 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.