hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923d4f1938f3c0aa9ac309bf3c979e701e6b258b | 2,843 | java | Java | src/main/java/com/semuxpool/pool/block/PayoutFactory.java | orogvany/semux-pool | 5c1f420ff8ee40347b048c9c100e8c808524993e | [
"Apache-2.0",
"MIT"
] | 5 | 2018-01-17T07:05:15.000Z | 2021-08-20T07:23:02.000Z | src/main/java/com/semuxpool/pool/block/PayoutFactory.java | orogvany/semux-pool | 5c1f420ff8ee40347b048c9c100e8c808524993e | [
"Apache-2.0",
"MIT"
] | 8 | 2018-03-04T12:06:31.000Z | 2021-12-09T20:20:59.000Z | src/main/java/com/semuxpool/pool/block/PayoutFactory.java | orogvany/semux-pool | 5c1f420ff8ee40347b048c9c100e8c808524993e | [
"Apache-2.0",
"MIT"
] | 5 | 2018-01-24T20:16:09.000Z | 2019-08-22T13:40:44.000Z | 30.569892 | 102 | 0.597608 | 1,000,267 | package com.semuxpool.pool.block;
import com.semuxpool.pool.api.BlockResult;
import com.semuxpool.pool.api.Payout;
import com.semuxpool.pool.pay.PoolProfitAddresses;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Construct Payouts from BlockResults
*/
public class PayoutFactory {
//the address for pool profits to be paid out to.
private final PoolProfitAddresses profitsAddress;
private final String delegateName;
private final long fee;
public PayoutFactory(String delegateName, PoolProfitAddresses profitsAddress, long fee) {
this.delegateName = delegateName;
this.profitsAddress = profitsAddress;
this.fee = fee;
}
/**
* Construct a Payout object from a collection of forged block results.
*
* @param blocks blocks
* @param startBlockId startBlockId
* @return Payout
*/
public synchronized Payout getPayoutForBlockResults(List<BlockResult> blocks, Long startBlockId) {
Payout payout = new Payout();
if (blocks.isEmpty()) {
return null;
}
long totalPoolFees = 0l;
TreeMap<Long, String> blocksForged = new TreeMap<>();
for (BlockResult blockResult : blocks) {
blocksForged.put(blockResult.getBlockId(), delegateName);
//add up pool fees
Long poolProfit = 0l;
if (blockResult.getPayouts() != null) {
for (String address : profitsAddress.getAddresses()) {
Long blockProfit = blockResult.getPayouts().get(address);
if (blockProfit != null) {
poolProfit += blockProfit;
}
}
}
if (poolProfit != null) {
totalPoolFees += poolProfit;
}
}
payout.setBlocksForged(blocksForged);
payout.setStartBlock(startBlockId);
payout.setEndBlock(blocks.get(blocks.size() - 1).getBlockId());
payout.setPayouts(getPayouts(blocks));
payout.setPoolProfits(totalPoolFees);
payout.setFee(fee);
payout.setDate(new Date());
return payout;
}
private synchronized Map<String, Long> getPayouts(List<BlockResult> blockResults) {
Map<String, Long> unPaidPayouts = new HashMap<>();
for (BlockResult result : blockResults) {
for (Map.Entry<String, Long> payout : result.getPayouts().entrySet()) {
Long val = unPaidPayouts.get(payout.getKey());
if (val == null) {
val = 0l;
}
val += payout.getValue();
unPaidPayouts.put(payout.getKey(), val);
}
}
return unPaidPayouts;
}
}
|
923d504290f9e7ab8c5c368fb3aad7936919ee89 | 1,579 | java | Java | etl/src/main/java/com/cezarykluczynski/stapi/etl/template/common/factory/PlatformFactory.java | tj-harris/stapi | a7db769841d2dbf4c0bd05f00e26bdc9fd9e5341 | [
"MIT"
] | 104 | 2017-04-27T17:50:40.000Z | 2022-03-20T07:50:34.000Z | etl/src/main/java/com/cezarykluczynski/stapi/etl/template/common/factory/PlatformFactory.java | tj-harris/stapi | a7db769841d2dbf4c0bd05f00e26bdc9fd9e5341 | [
"MIT"
] | 15 | 2017-06-17T11:54:29.000Z | 2022-03-02T02:38:51.000Z | etl/src/main/java/com/cezarykluczynski/stapi/etl/template/common/factory/PlatformFactory.java | tj-harris/stapi | a7db769841d2dbf4c0bd05f00e26bdc9fd9e5341 | [
"MIT"
] | 14 | 2017-05-05T19:50:46.000Z | 2022-01-15T12:58:23.000Z | 31.58 | 142 | 0.804307 | 1,000,268 | package com.cezarykluczynski.stapi.etl.template.common.factory;
import com.cezarykluczynski.stapi.etl.platform.service.PlatformCodeToNameMapper;
import com.cezarykluczynski.stapi.model.common.service.UidGenerator;
import com.cezarykluczynski.stapi.model.platform.entity.Platform;
import com.cezarykluczynski.stapi.model.platform.repository.PlatformRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@Slf4j
public class PlatformFactory {
private final PlatformCodeToNameMapper platformCodeToNameMapper;
private final PlatformRepository platformRepository;
private final UidGenerator uidGenerator;
public PlatformFactory(PlatformCodeToNameMapper platformCodeToNameMapper, PlatformRepository platformRepository, UidGenerator uidGenerator) {
this.platformCodeToNameMapper = platformCodeToNameMapper;
this.platformRepository = platformRepository;
this.uidGenerator = uidGenerator;
}
public synchronized Optional<Platform> createForCode(String code) {
String name = platformCodeToNameMapper.map(code);
if (name == null) {
log.warn("Could not map code \"{}\" to platform name", code);
return Optional.empty();
}
Optional<Platform> platformOptional = platformRepository.findByName(name);
if (platformOptional.isPresent()) {
return platformOptional;
} else {
Platform platform = new Platform();
platform.setName(name);
platform.setUid(uidGenerator.generateForPlatform(code));
platformRepository.save(platform);
return Optional.of(platform);
}
}
}
|
923d50e415c91e80dc1f73ef2d6627a760376f83 | 633 | java | Java | src/main/java/com/citihub/configr/namespace/NamespaceSerializer.java | composr/configr | ec868691b597ddb253fc77db1023e06daead8264 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/citihub/configr/namespace/NamespaceSerializer.java | composr/configr | ec868691b597ddb253fc77db1023e06daead8264 | [
"Apache-2.0"
] | 11 | 2022-02-04T17:24:03.000Z | 2022-03-31T17:31:27.000Z | src/main/java/com/citihub/configr/namespace/NamespaceSerializer.java | citihub/configr | ec868691b597ddb253fc77db1023e06daead8264 | [
"Apache-2.0"
] | null | null | null | 28.772727 | 95 | 0.802528 | 1,000,269 | package com.citihub.configr.namespace;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@NoArgsConstructor
public class NamespaceSerializer extends JsonSerializer<Namespace> {
@Override
public void serialize(Namespace namespace, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
log.info("Writing object {}", namespace.getKey());
gen.writeObject(namespace.getValue());
}
}
|
923d534803478bf603daf0bfe1d42655e962a344 | 709 | java | Java | src/main/java/problems/algorithm/hashtable/ContainsNearbyAlmostDuplicate_220.java | small-Teenager/letecode | 9c1caacdef7093563c50870b547a2c7534910e3b | [
"Apache-2.0"
] | 4 | 2019-01-23T01:13:36.000Z | 2020-11-04T01:31:46.000Z | src/main/java/problems/algorithm/hashtable/ContainsNearbyAlmostDuplicate_220.java | small-Teenager/letecode | 9c1caacdef7093563c50870b547a2c7534910e3b | [
"Apache-2.0"
] | 1 | 2020-03-13T08:29:45.000Z | 2020-03-13T08:30:09.000Z | src/main/java/problems/algorithm/hashtable/ContainsNearbyAlmostDuplicate_220.java | small-Teenager/letecode | 9c1caacdef7093563c50870b547a2c7534910e3b | [
"Apache-2.0"
] | null | null | null | 22.28125 | 80 | 0.611501 | 1,000,270 | package problems.algorithm.hashtable;
import java.util.TreeSet;
/**
*
* @author Search lyhxr@example.com 找到字符串中所有字母异位词
*
*/
public class ContainsNearbyAlmostDuplicate_220 {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
// 这个问题的测试数据在使用int进行加减运算时会溢出
// 所以使用long long
TreeSet<Long> record = new TreeSet<Long>();
for (int i = 0; i < nums.length; i++) {
if (record.ceiling((long) nums[i] - (long) t) != null
&& record.ceiling((long) nums[i] - (long) t) <= (long) nums[i] + (long) t)
return true;
record.add((long) nums[i]);
if (record.size() == k + 1)
record.remove((long) nums[i - k]);
}
return false;
}
}
|
923d534bf277b490797688ef7758b6ce6c9db8b3 | 3,627 | java | Java | webapp/idol/src/main/java/com/hp/autonomy/frontend/find/idol/stats/IdolStatsService.java | chris-blanks-mf/find | b28c217c1cb51f0bb54805294f7aa6d41e693496 | [
"MIT"
] | null | null | null | webapp/idol/src/main/java/com/hp/autonomy/frontend/find/idol/stats/IdolStatsService.java | chris-blanks-mf/find | b28c217c1cb51f0bb54805294f7aa6d41e693496 | [
"MIT"
] | null | null | null | webapp/idol/src/main/java/com/hp/autonomy/frontend/find/idol/stats/IdolStatsService.java | chris-blanks-mf/find | b28c217c1cb51f0bb54805294f7aa6d41e693496 | [
"MIT"
] | null | null | null | 39 | 146 | 0.718224 | 1,000,271 | /*
* Copyright 2014-2016 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.idol.stats;
import com.autonomy.aci.client.services.AciService;
import com.autonomy.aci.client.util.AciParameters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.hp.autonomy.frontend.configuration.ConfigService;
import com.hp.autonomy.frontend.find.core.stats.Event;
import com.hp.autonomy.frontend.find.core.stats.StatsService;
import com.hp.autonomy.frontend.find.idol.configuration.IdolFindConfig;
import com.hp.autonomy.types.idol.marshalling.ProcessorFactory;
import com.hp.autonomy.types.requests.idol.actions.stats.StatsServerActions;
import com.hp.autonomy.types.requests.idol.actions.stats.params.EventParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
@Service
@Slf4j
class IdolStatsService implements StatsService {
private final BlockingQueue<Event> queue = new LinkedBlockingQueue<>();
private final AciService statsServerAciService;
private final ProcessorFactory processorFactory;
private final XmlMapper xmlMapper;
private final ConfigService<IdolFindConfig> configService;
@Autowired
public IdolStatsService(
final AciService statsServerAciService,
final ProcessorFactory processorFactory,
final XmlMapper xmlMapper,
final ConfigService<IdolFindConfig> configService
) {
this.statsServerAciService = statsServerAciService;
this.processorFactory = processorFactory;
this.xmlMapper = xmlMapper;
this.configService = configService;
}
@Override
public void recordEvent(final Event event) {
// if not enabled, throw the event away
if (isEnabled()) {
queue.add(event);
}
}
@Scheduled(fixedRate = 5000L)
public void drainQueue() {
final List<Event> eventsList = new ArrayList<>();
queue.drainTo(eventsList);
// if no events, no work to do
// if not enabled, throw the events away
// (it's still useful to drain the queue if stats are disabled while the app is running)
if (isEnabled() && !eventsList.isEmpty()) {
final Events events = new Events(eventsList);
try {
final String xml = xmlMapper.writeValueAsString(events);
final AciParameters parameters = new AciParameters(StatsServerActions.Event.name());
parameters.put(EventParams.Data.name(), xml);
statsServerAciService.executeAction(parameters, processorFactory.getVoidProcessor());
} catch (final JsonProcessingException e) {
// includes XML errors which should only occur during development
// throwing won't result in the exception going anywhere useful anyway
log.error("Error constructing XML: ", e);
}
}
}
private boolean isEnabled() {
return configService.getConfig().getStatsServer() != null && BooleanUtils.isTrue(configService.getConfig().getStatsServer().getEnabled());
}
}
|
923d53fa223c6d1f1ce779e022da16fffc452016 | 4,920 | java | Java | main/plugins/org.talend.designer.components.libs/libs_src/talend-mscrm/src/main/java/com/microsoft/schemas/crm/_2011/contracts/impl/ArrayOfSdkMessageProcessingStepImageRegistrationDocumentImpl.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 114 | 2015-03-05T15:34:59.000Z | 2022-02-22T03:48:44.000Z | main/plugins/org.talend.designer.components.libs/libs_src/talend-mscrm/src/main/java/com/microsoft/schemas/crm/_2011/contracts/impl/ArrayOfSdkMessageProcessingStepImageRegistrationDocumentImpl.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 1,137 | 2015-03-04T01:35:42.000Z | 2022-03-29T06:03:17.000Z | main/plugins/org.talend.designer.components.libs/libs_src/talend-mscrm/src/main/java/com/microsoft/schemas/crm/_2011/contracts/impl/ArrayOfSdkMessageProcessingStepImageRegistrationDocumentImpl.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 219 | 2015-01-21T10:42:18.000Z | 2022-02-17T07:57:20.000Z | 48.712871 | 246 | 0.729268 | 1,000,272 | /*
* An XML document type.
* Localname: ArrayOfSdkMessageProcessingStepImageRegistration
* Namespace: http://schemas.microsoft.com/crm/2011/Contracts
* Java type: com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistrationDocument
*
* Automatically generated - do not modify.
*/
package com.microsoft.schemas.crm._2011.contracts.impl;
/**
* A document containing one ArrayOfSdkMessageProcessingStepImageRegistration(@http://schemas.microsoft.com/crm/2011/Contracts) element.
*
* This is a complex type.
*/
public class ArrayOfSdkMessageProcessingStepImageRegistrationDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistrationDocument
{
private static final long serialVersionUID = 1L;
public ArrayOfSdkMessageProcessingStepImageRegistrationDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName ARRAYOFSDKMESSAGEPROCESSINGSTEPIMAGEREGISTRATION$0 =
new javax.xml.namespace.QName("http://schemas.microsoft.com/crm/2011/Contracts", "ArrayOfSdkMessageProcessingStepImageRegistration");
/**
* Gets the "ArrayOfSdkMessageProcessingStepImageRegistration" element
*/
public com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration getArrayOfSdkMessageProcessingStepImageRegistration()
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration target = null;
target = (com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration)get_store().find_element_user(ARRAYOFSDKMESSAGEPROCESSINGSTEPIMAGEREGISTRATION$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Tests for nil "ArrayOfSdkMessageProcessingStepImageRegistration" element
*/
public boolean isNilArrayOfSdkMessageProcessingStepImageRegistration()
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration target = null;
target = (com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration)get_store().find_element_user(ARRAYOFSDKMESSAGEPROCESSINGSTEPIMAGEREGISTRATION$0, 0);
if (target == null) return false;
return target.isNil();
}
}
/**
* Sets the "ArrayOfSdkMessageProcessingStepImageRegistration" element
*/
public void setArrayOfSdkMessageProcessingStepImageRegistration(com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration arrayOfSdkMessageProcessingStepImageRegistration)
{
generatedSetterHelperImpl(arrayOfSdkMessageProcessingStepImageRegistration, ARRAYOFSDKMESSAGEPROCESSINGSTEPIMAGEREGISTRATION$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "ArrayOfSdkMessageProcessingStepImageRegistration" element
*/
public com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration addNewArrayOfSdkMessageProcessingStepImageRegistration()
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration target = null;
target = (com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration)get_store().add_element_user(ARRAYOFSDKMESSAGEPROCESSINGSTEPIMAGEREGISTRATION$0);
return target;
}
}
/**
* Nils the "ArrayOfSdkMessageProcessingStepImageRegistration" element
*/
public void setNilArrayOfSdkMessageProcessingStepImageRegistration()
{
synchronized (monitor())
{
check_orphaned();
com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration target = null;
target = (com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration)get_store().find_element_user(ARRAYOFSDKMESSAGEPROCESSINGSTEPIMAGEREGISTRATION$0, 0);
if (target == null)
{
target = (com.microsoft.schemas.crm._2011.contracts.ArrayOfSdkMessageProcessingStepImageRegistration)get_store().add_element_user(ARRAYOFSDKMESSAGEPROCESSINGSTEPIMAGEREGISTRATION$0);
}
target.setNil();
}
}
}
|
923d54214c20e013f313665626a463a16b0ef568 | 3,869 | java | Java | testamation-jdk7-common/src/main/java/nz/co/testamation/common/util/XmlUtil.java | rlon008/testamation-jdk7 | 38e6dde9031cb8509b1f0aac96a9f4b83bb80f37 | [
"Apache-2.0"
] | null | null | null | testamation-jdk7-common/src/main/java/nz/co/testamation/common/util/XmlUtil.java | rlon008/testamation-jdk7 | 38e6dde9031cb8509b1f0aac96a9f4b83bb80f37 | [
"Apache-2.0"
] | null | null | null | testamation-jdk7-common/src/main/java/nz/co/testamation/common/util/XmlUtil.java | rlon008/testamation-jdk7 | 38e6dde9031cb8509b1f0aac96a9f4b83bb80f37 | [
"Apache-2.0"
] | null | null | null | 38.306931 | 132 | 0.699406 | 1,000,273 | /*
* Copyright 2016 Ratha Long
*
* 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 nz.co.testamation.common.util;
import com.google.common.collect.ImmutableMap;
import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.namespace.NamespaceContext;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
public class XmlUtil {
public static Document toDocument( String str ) {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Document document = new DocumentBuilderFactoryImpl().newDocumentBuilder().newDocument();
transformerFactory.newTransformer().transform( new StreamSource( new StringReader( str ) ), new DOMResult( document ) );
return document;
} catch ( Exception e ) {
throw new RuntimeException( e );
}
}
public static NamespaceContext toNameSpaceContext( Map<String, String> namespace ) {
return new PrefixMapNamespaceContext( namespace );
}
public static XPathExpression compileXPath( String xPathExpression, NamespaceContext namespaceContext ) {
try {
final XPath xPath = XPathFactory.newInstance().newXPath();
if ( namespaceContext != null ) {
xPath.setNamespaceContext( namespaceContext );
}
return xPath.compile( xPathExpression );
} catch ( XPathExpressionException e ) {
throw new IllegalArgumentException( "Invalid XPath : " + xPathExpression, e );
}
}
public static XPathExpression compileXPath( String xPathExpression, Map<String, String> namespaceContext ) {
return compileXPath( xPathExpression, toNameSpaceContext( namespaceContext ) );
}
public static String toString( Node node ) {
try {
StringWriter writer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform( new DOMSource( node ), new StreamResult( writer ) );
return writer.toString();
} catch ( Exception ex ) {
throw new RuntimeException( ex );
}
}
public static String toString( DOMResult domResult ) {
return toString( ( (Document) domResult.getNode() ).getDocumentElement() );
}
public static String selectString( Node node, String xPathExpression, ImmutableMap<String, String> namespaces ) {
try {
return compileXPath( xPathExpression, namespaces ).evaluate( node );
} catch ( XPathExpressionException e ) {
throw new RuntimeException( e );
}
}
public static String selectString( Node node, String xPathExpression ) {
return selectString( node, xPathExpression, ImmutableMap.<String, String>of() );
}
}
|
923d5443b24452a95e854ae8513c10859c88ac1d | 2,128 | java | Java | cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/guidance/GridGuidanceRequest.java | drjoeycadieux/awips2 | 3b467b15915cba23d9216eefd97a21758e66c748 | [
"Apache-2.0"
] | null | null | null | cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/guidance/GridGuidanceRequest.java | drjoeycadieux/awips2 | 3b467b15915cba23d9216eefd97a21758e66c748 | [
"Apache-2.0"
] | null | null | null | cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/guidance/GridGuidanceRequest.java | drjoeycadieux/awips2 | 3b467b15915cba23d9216eefd97a21758e66c748 | [
"Apache-2.0"
] | 1 | 2021-10-30T00:03:05.000Z | 2021-10-30T00:03:05.000Z | 26.936709 | 75 | 0.603853 | 1,000,274 | /**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.viz.aviation.guidance;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Base request class used by the tab viewers and to be notified of alerts.
*
* <pre>
*
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 11, 2009 njensen Initial creation
* Apr 28, 2011 8065 rferrel Implement data caching
*
* </pre>
*
* @author njensen
* @version 1.0
*/
public class GridGuidanceRequest extends GuidanceRequest {
protected List<String> siteObjs;
protected boolean routine;
public void setSiteObjs(List<String> siteObjs) {
this.siteObjs = siteObjs;
}
/**
* Place in the map arguments need for grid.
*/
@Override
public Map<String, Object> getPythonArguments() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("siteObjs", siteObjs);
map.put("format", format);
map.put("routine", routine);
return map;
}
/**
* @param routine
* the routine to set
*/
public void setRoutine(boolean routine) {
this.routine = routine;
}
/**
* @return the routine
*/
public boolean isRoutine() {
return routine;
}
}
|
923d54806fe3959f51f276e163c6c3f8596b5eb3 | 132,322 | java | Java | k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java | FAU-Inf2/k-9 | f14ef2f043e8f2b1779c2184aed4f0c6b44f0d80 | [
"Apache-2.0",
"BSD-3-Clause"
] | 17 | 2015-10-06T03:24:23.000Z | 2021-08-10T23:39:02.000Z | k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java | FAU-Inf2/k-9 | f14ef2f043e8f2b1779c2184aed4f0c6b44f0d80 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2015-10-06T21:06:52.000Z | 2017-08-14T18:40:11.000Z | k9mail/src/main/java/com/fsck/k9/activity/MessageCompose.java | FAU-Inf2/k-9 | f14ef2f043e8f2b1779c2184aed4f0c6b44f0d80 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2015-10-14T19:56:05.000Z | 2019-03-01T02:42:05.000Z | 41.519297 | 206 | 0.608221 | 1,000,275 | package com.fsck.k9.activity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.LoaderManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.internal.view.ContextThemeWrapper;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.MessageFormat;
import com.fsck.k9.Account.QuoteStyle;
import com.fsck.k9.FontSizes;
import com.fsck.k9.Identity;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.activity.misc.AttachmentContentLoaderCallback;
import com.fsck.k9.activity.misc.AttachmentInfoLoaderCallback;
import com.fsck.k9.activity.misc.Attachment;
import com.fsck.k9.activity.misc.AttachmentMessageComposeHelper;
import com.fsck.k9.adapter.IdentityAdapter;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.controller.MessagingListener;
import com.fsck.k9.crypto.OpenPgpMessageCompose;
import com.fsck.k9.crypto.PgpData;
import com.fsck.k9.crypto.SmimeMessageCompose;
import com.fsck.k9.fragment.ProgressDialogFragment;
import com.fsck.k9.helper.ContactItem;
import com.fsck.k9.helper.Contacts;
import com.fsck.k9.helper.HtmlConverter;
import com.fsck.k9.helper.IdentityHelper;
import com.fsck.k9.helper.SimpleTextWatcher;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Multipart;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.internet.MessageExtractor;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mailstore.LocalMessage;
import com.fsck.k9.message.IdentityField;
import com.fsck.k9.message.IdentityHeaderParser;
import com.fsck.k9.message.InsertableHtmlContent;
import com.fsck.k9.message.MessageBuilder;
import com.fsck.k9.message.QuotedTextMode;
import com.fsck.k9.message.SimpleMessageFormat;
import com.fsck.k9.ui.EolConvertingEditText;
import com.fsck.k9.view.MessageComposeRecipient;
import com.fsck.k9.view.MessageWebView;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.SimpleHtmlSerializer;
import org.htmlcleaner.TagNode;
import org.openintents.openpgp.util.OpenPgpServiceConnection;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.fau.cs.mad.smile.android.R;
import de.fau.cs.mad.smime_api.ISMimeService;
import de.fau.cs.mad.smime_api.SMimeApi;
import de.fau.cs.mad.smime_api.SMimeServiceConnection;
public class MessageCompose extends K9Activity implements View.OnClickListener,
ProgressDialogFragment.CancelListener {
private static final long INVALID_DRAFT_ID = MessagingController.INVALID_MESSAGE_ID;
private static final String ACTION_COMPOSE = "com.fsck.k9.intent.action.COMPOSE";
private static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY";
private static final String ACTION_REPLY_ALL = "com.fsck.k9.intent.action.REPLY_ALL";
private static final String ACTION_FORWARD = "com.fsck.k9.intent.action.FORWARD";
private static final String ACTION_EDIT_DRAFT = "com.fsck.k9.intent.action.EDIT_DRAFT";
private static final String EXTRA_ACCOUNT = "account";
private static final String EXTRA_MESSAGE_BODY = "messageBody";
private static final String EXTRA_MESSAGE_REFERENCE = "message_reference";
private static final String STATE_KEY_ATTACHMENTS =
"com.fsck.k9.activity.MessageCompose.attachments";
private static final String STATE_KEY_CC_SHOWN =
"com.fsck.k9.activity.MessageCompose.ccShown";
private static final String STATE_KEY_BCC_SHOWN =
"com.fsck.k9.activity.MessageCompose.bccShown";
private static final String STATE_KEY_QUOTED_TEXT_MODE =
"com.fsck.k9.activity.MessageCompose.QuotedTextShown";
private static final String STATE_KEY_SOURCE_MESSAGE_PROCED =
"com.fsck.k9.activity.MessageCompose.stateKeySourceMessageProced";
private static final String STATE_KEY_DRAFT_ID = "com.fsck.k9.activity.MessageCompose.draftId";
private static final String STATE_KEY_HTML_QUOTE = "com.fsck.k9.activity.MessageCompose.HTMLQuote";
private static final String STATE_IDENTITY_CHANGED =
"com.fsck.k9.activity.MessageCompose.identityChanged";
private static final String STATE_IDENTITY =
"com.fsck.k9.activity.MessageCompose.identity";
private static final String STATE_PGP_DATA = "pgpData";
private static final String STATE_IN_REPLY_TO = "com.fsck.k9.activity.MessageCompose.inReplyTo";
private static final String STATE_REFERENCES = "com.fsck.k9.activity.MessageCompose.references";
private static final String STATE_KEY_READ_RECEIPT = "com.fsck.k9.activity.MessageCompose.messageReadReceipt";
private static final String STATE_KEY_DRAFT_NEEDS_SAVING = "com.fsck.k9.activity.MessageCompose.mDraftNeedsSaving";
private static final String STATE_KEY_FORCE_PLAIN_TEXT =
"com.fsck.k9.activity.MessageCompose.forcePlainText";
private static final String STATE_KEY_QUOTED_TEXT_FORMAT =
"com.fsck.k9.activity.MessageCompose.quotedTextFormat";
private static final String STATE_KEY_NUM_ATTACHMENTS_LOADING = "numAttachmentsLoading";
private static final String STATE_KEY_WAITING_FOR_ATTACHMENTS = "waitingForAttachments";
public static final String LOADER_ARG_ATTACHMENT = "attachment";
private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment";
/**
* package accessible so handler can use the following constants
*/
static final int MSG_PROGRESS_ON = 1;
static final int MSG_PROGRESS_OFF = 2;
static final int MSG_SKIPPED_ATTACHMENTS = 3;
static final int MSG_SAVED_DRAFT = 4;
static final int MSG_DISCARDED_DRAFT = 5;
static final int MSG_PERFORM_STALLED_ACTION = 6;
private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1;
private static final int CONTACT_PICKER_TO = 4;
private static final int CONTACT_PICKER_CC = 5;
private static final int CONTACT_PICKER_BCC = 6;
private static final int CONTACT_PICKER_TO2 = 7;
private static final int CONTACT_PICKER_CC2 = 8;
private static final int CONTACT_PICKER_BCC2 = 9;
public static final int REQUEST_CODE_SIGN_ENCRYPT_OPENPGP = 12;
/**
* Regular expression to remove the first localized "Re:" prefix in subjects.
*
* Currently:
* - "Aw:" (german: abbreviation for "Antwort")
*/
private static final Pattern PREFIX = Pattern.compile("^AW[:\\s]\\s*", Pattern.CASE_INSENSITIVE);
/**
* The account used for message composition.
*/
private Account mAccount;
private Contacts mContacts;
/**
* This identity's settings are used for message composition.
* Note: This has to be an identity of the account {@link #mAccount}.
*/
private Identity mIdentity;
private boolean mIdentityChanged = false;
private boolean mSignatureChanged = false;
/**
* Reference to the source message (in case of reply, forward, or edit
* draft actions).
*/
private MessageReference mMessageReference;
private Message mSourceMessage;
private MimeMessage currentMessage;
/**
* "Original" message body
*
* <p>
* The contents of this string will be used instead of the body of a referenced message when
* replying to or forwarding a message.<br>
* Right now this is only used when replying to a signed or encrypted message. It then contains
* the stripped/decrypted body of that message.
* </p>
* <p><strong>Note:</strong>
* When this field is not {@code null} we assume that the message we are composing right now
* should be encrypted.
* </p>
*/
private String mSourceMessageBody;
/**
* Indicates that the source message has been processed at least once and should not
* be processed on any subsequent loads. This protects us from adding attachments that
* have already been added from the restore of the view state.
*/
private boolean mSourceMessageProcessed = false;
private int mMaxLoaderId = 0;
private MessagingController controller;
private MenuItem sendMenuButton;
enum Action {
COMPOSE,
REPLY,
REPLY_ALL,
FORWARD,
EDIT_DRAFT
}
/**
* Contains the action we're currently performing (e.g. replying to a message)
*/
private Action mAction;
private boolean mReadReceipt = false;
private QuotedTextMode mQuotedTextMode = QuotedTextMode.NONE;
/**
* Contains the format of the quoted text (text vs. HTML).
*/
private SimpleMessageFormat mQuotedTextFormat;
/**
* When this it {@code true} the message format setting is ignored and we're always sending
* a text/plain message.
*/
private boolean mForcePlainText = false;
private Button mChooseIdentityButton;
private MessageComposeRecipient mToView;
private MessageComposeRecipient mCcView;
private MessageComposeRecipient mBccView;
private EditText mSubjectView;
private EolConvertingEditText mSignatureView;
private EolConvertingEditText mMessageContentView;
private LinearLayout mAttachments;
private Button mQuotedTextShow;
private View mQuotedTextBar;
private ImageButton mQuotedTextEdit;
private EolConvertingEditText mQuotedText;
private MessageWebView mQuotedHTML;
private InsertableHtmlContent mQuotedHtmlContent; // Container for HTML reply as it's being built.
private CheckBox mCryptoSignatureCheckbox;
private CheckBox mEncryptCheckbox;
private TextView mCryptoSignatureUserId;
private TextView mCryptoSignatureUserIdRest;
private Spinner mSpinner;
private PgpData mPgpData = null;
private String mOpenPgpProvider;
private String mSmimeProvider;
private OpenPgpServiceConnection mOpenPgpServiceConnection;
private SMimeServiceConnection mSmimeServiceConnection;
private SMimeApi sMimeApi;
private OpenPgpMessageCompose openPgpMessageCompose;
private String mReferences;
private String mInReplyTo;
private Menu mMenu;
private boolean mSourceProcessed = false;
/**
* The currently used message format.
*
* <p>
* <strong>Note:</strong>
* Don't modify this field directly. Use {@link #updateMessageFormat()}.
* </p>
*/
private SimpleMessageFormat mMessageFormat;
private QuoteStyle mQuoteStyle;
private boolean mDraftNeedsSaving = false;
private boolean mPreventDraftSaving = false;
/**
* If this is {@code true} we don't save the message as a draft in {@link #onPause()}.
*/
private boolean mIgnoreOnPause = false;
/**
* The database ID of this message's draft. This is used when saving drafts so the message in
* the database is updated instead of being created anew. This property is INVALID_DRAFT_ID
* until the first save.
*/
private long mDraftId = INVALID_DRAFT_ID;
/**
* Number of attachments currently being fetched.
*/
private int mNumAttachmentsLoading = 0;
private enum WaitingAction {
NONE,
SEND,
SAVE
}
private enum CryptoProvider {
NONE("None"),
PGP("OpenPGP"),
SMIME("S/MIME");
private final String name;
private CryptoProvider(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
/**
* Specifies what action to perform once attachments have been fetched.
*/
private WaitingAction mWaitingForAttachments = WaitingAction.NONE;
private MessageComposeHandler mHandler = new MessageComposeHandler(this);
private Listener mListener = new Listener();
private FontSizes mFontSizes = K9.getFontSizes();
private ContextThemeWrapper mThemeContext;
private CryptoProvider selectedCryptoProvider = CryptoProvider.NONE;
/**
* Compose a new message using the given account. If account is null the default account
* will be used.
* @param context
* @param account
*/
public static void actionCompose(Context context, Account account) {
String accountUuid = (account == null) ?
Preferences.getPreferences(context).getDefaultAccount().getUuid() :
account.getUuid();
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_ACCOUNT, accountUuid);
i.setAction(ACTION_COMPOSE);
context.startActivity(i);
}
/**
* Get intent for composing a new message as a reply to the given message. If replyAll is true
* the function is reply all instead of simply reply.
* @param context
* @param message
* @param replyAll
* @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message
*/
public static Intent getActionReplyIntent(
Context context,
LocalMessage message,
boolean replyAll,
String messageBody) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_BODY, messageBody);
i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference());
if (replyAll) {
i.setAction(ACTION_REPLY_ALL);
} else {
i.setAction(ACTION_REPLY);
}
return i;
}
public static Intent getActionReplyIntent(Context context, MessageReference messageReference) {
Intent intent = new Intent(context, MessageCompose.class);
intent.setAction(ACTION_REPLY);
intent.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
/**
* Compose a new message as a reply to the given message. If replyAll is true the function
* is reply all instead of simply reply.
* @param context
* @param message
* @param replyAll
* @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message
*/
public static void actionReply(
Context context,
LocalMessage message,
boolean replyAll,
String messageBody) {
context.startActivity(getActionReplyIntent(context, message, replyAll, messageBody));
}
/**
* Compose a new message as a forward of the given message.
* @param context
* @param message
* @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message
*/
public static void actionForward(
Context context,
LocalMessage message,
String messageBody) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_BODY, messageBody);
i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference());
i.setAction(ACTION_FORWARD);
context.startActivity(i);
}
/**
* Continue composition of the given message. This action modifies the way this Activity
* handles certain actions.
* Save will attempt to replace the message in the given folder with the updated version.
* Discard will delete the message from the given folder.
* @param context
* @param messageReference
*/
public static void actionEditDraft(Context context, MessageReference messageReference) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference);
i.setAction(ACTION_EDIT_DRAFT);
context.startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) {
finish();
return;
}
setupTheme();
final Intent intent = getIntent();
final String accountUuid = acquireExtras(intent);
if (!ensureAccount(accountUuid)) {
return;
}
if (mIdentity == null) {
mIdentity = mAccount.getIdentity(0);
}
mReadReceipt = mAccount.isMessageReadReceiptAlways();
mQuoteStyle = mAccount.getQuoteStyle();
mOpenPgpProvider = mAccount.getOpenPgpProvider();
mSmimeProvider = mAccount.getSmimeProvider();
controller = MessagingController.getInstance(getApplication());
acquireLayout();
setupLayout();
if (savedInstanceState != null) {
/*
* This data gets used in onCreate, so grab it here instead of onRestoreInstanceState
*/
mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false);
}
if (initFromIntent(intent)) {
mAction = Action.COMPOSE;
mDraftNeedsSaving = true;
} else {
String action = intent.getAction();
if (ACTION_COMPOSE.equals(action)) {
mAction = Action.COMPOSE;
} else if (ACTION_REPLY.equals(action)) {
mAction = Action.REPLY;
} else if (ACTION_REPLY_ALL.equals(action)) {
mAction = Action.REPLY_ALL;
} else if (ACTION_FORWARD.equals(action)) {
mAction = Action.FORWARD;
} else if (ACTION_EDIT_DRAFT.equals(action)) {
mAction = Action.EDIT_DRAFT;
} else {
// This shouldn't happen
Log.w(K9.LOG_TAG, "MessageCompose was started with an unsupported action");
mAction = Action.COMPOSE;
}
}
updateFrom();
if (!mSourceMessageProcessed) {
updateSignature();
if (mAction == Action.REPLY || mAction == Action.REPLY_ALL ||
mAction == Action.FORWARD || mAction == Action.EDIT_DRAFT) {
/*
* If we need to load the message we add ourself as a message listener here
* so we can kick it off. Normally we add in onResume but we don't
* want to reload the message every time the activity is resumed.
* There is no harm in adding twice.
*/
controller.addListener(mListener);
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.getAccountUuid());
final String folderName = mMessageReference.getFolderName();
final String sourceMessageUid = mMessageReference.getUid();
controller.loadMessageForView(account, folderName, sourceMessageUid, null);
}
if (mAction != Action.EDIT_DRAFT) {
mBccView.addRecipients(Address.parseUnencoded(mAccount.getAlwaysBcc()));
}
}
if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) {
mMessageReference = mMessageReference.withModifiedFlag(Flag.ANSWERED);
}
if (mAction == Action.REPLY || mAction == Action.REPLY_ALL ||
mAction == Action.EDIT_DRAFT) {
//change focus to message body.
mMessageContentView.requestFocus();
} else {
// TODO: check if recipient box receives focus
// Explicitly set focus to "To:" input field (see issue 2998)
mToView.requestFocus();
}
if (mAction == Action.FORWARD) {
mMessageReference = mMessageReference.withModifiedFlag(Flag.FORWARDED);
}
final View mEncryptLayout = findViewById(R.id.layout_encrypt);
initializeCrypto();
if (isCryptoProviderEnabled()) {
mCryptoSignatureCheckbox = (CheckBox)findViewById(R.id.cb_crypto_signature);
final CompoundButton.OnCheckedChangeListener updateListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateMessageFormat();
}
};
mCryptoSignatureCheckbox.setOnCheckedChangeListener(updateListener);
mCryptoSignatureUserId = (TextView)findViewById(R.id.userId);
mCryptoSignatureUserIdRest = (TextView)findViewById(R.id.userIdRest);
mEncryptCheckbox = (CheckBox)findViewById(R.id.cb_encrypt);
mEncryptCheckbox.setOnCheckedChangeListener(updateListener);
if (mSourceMessageBody != null) {
// mSourceMessageBody is set to something when replying to and forwarding decrypted
// messages, so the sender probably wants the message to be encrypted.
mEncryptCheckbox.setChecked(true);
}
// New OpenPGP Provider API
// bind to service
new Thread(new Runnable() {
@Override
public void run() {
if(mOpenPgpProvider != null && !mOpenPgpProvider.equals("")) {
mOpenPgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), mOpenPgpProvider);
mOpenPgpServiceConnection.bindToService();
}
if(mSmimeProvider != null && !mSmimeProvider.equals("")) {
mSmimeServiceConnection = new SMimeServiceConnection(getApplicationContext(), mSmimeProvider, new SMimeServiceConnection.OnBound() {
@Override
public void onBound(ISMimeService service) {
sMimeApi = new SMimeApi(getApplicationContext(), service);
}
@Override
public void onError(Exception e) {
K9.logDebug( "smime api failed: ", e);
}
});
mSmimeServiceConnection.bindToService();
}
}
}).start();
mEncryptLayout.setVisibility(View.VISIBLE);
mCryptoSignatureCheckbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked()) {
mPreventDraftSaving = true;
}
}
});
updateMessageFormat();
} else {
mEncryptLayout.setVisibility(View.GONE);
}
updateMessageFormat();
setTitle();
}
private void setupLayout() {
ImageButton mQuotedTextDelete = (ImageButton) findViewById(R.id.quoted_text_delete);
TextWatcher draftNeedsChangingTextWatcher = new SimpleTextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mDraftNeedsSaving = true;
}
};
mToView.addTextChangedListener(draftNeedsChangingTextWatcher);
mCcView.addTextChangedListener(draftNeedsChangingTextWatcher);
mBccView.addTextChangedListener(draftNeedsChangingTextWatcher);
mSubjectView.addTextChangedListener(draftNeedsChangingTextWatcher);
mMessageContentView.addTextChangedListener(draftNeedsChangingTextWatcher);
mQuotedText.addTextChangedListener(draftNeedsChangingTextWatcher);
/* Yes, there really are people who ship versions of android without a contact picker */
if (mContacts.hasContactPicker()) {
mToView.setAddContactListener(new DoLaunchOnClickListener(CONTACT_PICKER_TO));
mCcView.setAddContactListener(new DoLaunchOnClickListener(CONTACT_PICKER_CC));
mBccView.setAddContactListener(new DoLaunchOnClickListener(CONTACT_PICKER_BCC));
}
/*
* We set this to invisible by default. Other methods will turn it back on if it's
* needed.
*/
showOrHideQuotedText(QuotedTextMode.NONE);
mQuotedTextShow.setOnClickListener(this);
mQuotedTextEdit.setOnClickListener(this);
mQuotedTextDelete.setOnClickListener(this);
EolConvertingEditText upperSignature = (EolConvertingEditText)findViewById(R.id.upper_signature);
EolConvertingEditText lowerSignature = (EolConvertingEditText)findViewById(R.id.lower_signature);
TextWatcher signTextWatcher = new SimpleTextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mDraftNeedsSaving = true;
mSignatureChanged = true;
}
};
if (mAccount.isSignatureBeforeQuotedText()) {
mSignatureView = upperSignature;
lowerSignature.setVisibility(View.GONE);
} else {
mSignatureView = lowerSignature;
upperSignature.setVisibility(View.GONE);
}
mSignatureView.addTextChangedListener(signTextWatcher);
if (!mIdentity.getSignatureUse()) {
mSignatureView.setVisibility(View.GONE);
}
// Set font size of input controls
int fontSize = mFontSizes.getMessageComposeInput();
mFontSizes.setViewTextSize(mSubjectView, fontSize);
mFontSizes.setViewTextSize(mMessageContentView, fontSize);
mFontSizes.setViewTextSize(mQuotedText, fontSize);
mFontSizes.setViewTextSize(mSignatureView, fontSize);
List<CryptoProvider> cryptoProviders = new ArrayList<>();
cryptoProviders.add(CryptoProvider.NONE);
if(mOpenPgpProvider != null && mOpenPgpProvider.trim().length() > 0) {
cryptoProviders.add(CryptoProvider.PGP);
}
if(mSmimeProvider != null && mSmimeProvider.trim().length() > 0) {
cryptoProviders.add(CryptoProvider.SMIME);
}
ArrayAdapter<CryptoProvider> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, cryptoProviders);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCryptoProvider = (CryptoProvider) parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
selectedCryptoProvider = CryptoProvider.NONE;
}
});
for(int i = 0; i < mSpinner.getCount(); i++) {
if(mSpinner.getItemAtPosition(i).toString().equals(mAccount.getDefaultCryptoProvider())) {
mSpinner.setSelection(i);
break;
}
}
if(cryptoProviders.size() == 1) {
mSpinner.setVisibility(View.GONE);
}
}
private void acquireLayout() {
mContacts = Contacts.getInstance(MessageCompose.this);
mChooseIdentityButton = (Button) findViewById(R.id.identity);
mChooseIdentityButton.setOnClickListener(this);
if (mAccount.getIdentities().size() == 1 &&
Preferences.getPreferences(this).getAvailableAccounts().size() == 1) {
mChooseIdentityButton.setVisibility(View.GONE);
}
mToView = (MessageComposeRecipient) findViewById(R.id.to_wrapper);
mCcView = (MessageComposeRecipient) findViewById(R.id.cc_wrapper);
mBccView = (MessageComposeRecipient) findViewById(R.id.bcc_wrapper);
mSubjectView = (EditText) findViewById(R.id.subject);
mSubjectView.getInputExtras(true).putBoolean("allowEmoji", true);
if (mAccount.isAlwaysShowCcBcc()) {
onAddCcBcc();
}
mMessageContentView = (EolConvertingEditText)findViewById(R.id.message_content);
mMessageContentView.getInputExtras(true).putBoolean("allowEmoji", true);
mAttachments = (LinearLayout)findViewById(R.id.attachments);
mQuotedTextShow = (Button)findViewById(R.id.quoted_text_show);
mQuotedTextBar = findViewById(R.id.quoted_text_bar);
mQuotedTextEdit = (ImageButton)findViewById(R.id.quoted_text_edit);
mQuotedText = (EolConvertingEditText)findViewById(R.id.quoted_text);
mQuotedText.getInputExtras(true).putBoolean("allowEmoji", true);
mQuotedHTML = (MessageWebView) findViewById(R.id.quoted_html);
mQuotedHTML.configure();
// Disable the ability to click links in the quoted HTML page. I think this is a nice feature, but if someone
// feels this should be a preference (or should go away all together), I'm ok with that too. -achen 20101130
mQuotedHTML.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});
mSpinner = (Spinner)findViewById(R.id.crypto_provider);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(false);
}
}
private boolean ensureAccount(final String accountUuid) {
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
if (mAccount == null) {
mAccount = Preferences.getPreferences(this).getDefaultAccount();
}
if (mAccount == null) {
/*
* There are no accounts set up. This should not have happened. Prompt the
* user to set up an account as an acceptable bailout.
*/
startActivity(new Intent(this, Accounts.class));
mDraftNeedsSaving = false;
finish();
return false;
}
return true;
}
private String acquireExtras(Intent intent) {
mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE);
mSourceMessageBody = intent.getStringExtra(EXTRA_MESSAGE_BODY);
if (K9.DEBUG && mSourceMessageBody != null) {
Log.d(K9.LOG_TAG, "Composing message with explicitly specified message body.");
}
return (mMessageReference != null) ?
mMessageReference.getAccountUuid() :
intent.getStringExtra(EXTRA_ACCOUNT);
}
private void setupTheme() {
setContentView(R.layout.message_compose);
mThemeContext = new ContextThemeWrapper(this, K9.getK9ThemeResourceId(K9.getK9Theme()));
}
@Override
public void onDestroy() {
super.onDestroy();
if (mOpenPgpServiceConnection != null) {
if(mOpenPgpServiceConnection.isBound()) {
mOpenPgpServiceConnection.unbindFromService();
}
}
if (mSmimeServiceConnection != null) {
if(mSmimeServiceConnection.isBound()) {
mSmimeServiceConnection.unbindFromService();
}
}
}
/**
* Handle external intents that trigger the message compose activity.
*
* <p>
* Supported external intents:
* <ul>
* <li>{@link Intent#ACTION_VIEW}</li>
* <li>{@link Intent#ACTION_SENDTO}</li>
* <li>{@link Intent#ACTION_SEND}</li>
* <li>{@link Intent#ACTION_SEND_MULTIPLE}</li>
* </ul>
* </p>
*
* @param intent
* The (external) intent that started the activity.
*
* @return {@code true}, if this activity was started by an external intent. {@code false},
* otherwise.
*/
private boolean initFromIntent(final Intent intent) {
boolean startedByExternalIntent = false;
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) {
/*
* Someone has clicked a mailto: link. The address is in the URI.
*/
if (intent.getData() != null) {
Uri uri = intent.getData();
if ("mailto".equals(uri.getScheme())) {
initializeFromMailto(uri);
}
}
/*
* Note: According to the documentation ACTION_VIEW and ACTION_SENDTO don't accept
* EXTRA_* parameters.
* And previously we didn't process these EXTRAs. But it looks like nobody bothers to
* read the official documentation and just copies wrong sample code that happens to
* work with the AOSP Email application. And because even big players get this wrong,
* we're now finally giving in and read the EXTRAs for those actions (below).
*/
}
if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action) ||
Intent.ACTION_SENDTO.equals(action) || Intent.ACTION_VIEW.equals(action)) {
startedByExternalIntent = true;
/*
* Note: Here we allow a slight deviation from the documented behavior.
* EXTRA_TEXT is used as message body (if available) regardless of the MIME
* type of the intent. In addition one or multiple attachments can be added
* using EXTRA_STREAM.
*/
CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
// Only use EXTRA_TEXT if the body hasn't already been set by the mailto URI
if (text != null && mMessageContentView.getText().length() == 0) {
mMessageContentView.setCharacters(text);
}
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action)) {
Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (stream != null) {
AttachmentMessageComposeHelper.addAttachment(this, stream, type, mAttachmentInfoLoaderCallback);
}
} else {
List<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (list != null) {
for (Parcelable parcelable : list) {
Uri stream = (Uri) parcelable;
if (stream != null) {
AttachmentMessageComposeHelper.addAttachment(this, stream, type, mAttachmentInfoLoaderCallback);
}
}
}
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
// Only use EXTRA_SUBJECT if the subject hasn't already been set by the mailto URI
if (subject != null && mSubjectView.getText().length() == 0) {
mSubjectView.setText(subject);
}
String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC);
String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC);
if (extraEmail != null) {
mToView.addRecipients(Arrays.asList(extraEmail));
}
boolean ccOrBcc = false;
if (extraCc != null) {
ccOrBcc |= mCcView.addRecipients(Arrays.asList(extraCc));
}
if (extraBcc != null) {
ccOrBcc |= mBccView.addRecipients(Arrays.asList(extraBcc));
}
if (ccOrBcc) {
// Display CC and BCC text fields if CC or BCC recipients were set by the intent.
onAddCcBcc();
}
}
return startedByExternalIntent;
}
private void initializeCrypto() {
if (mPgpData != null) {
return;
}
mPgpData = new PgpData();
}
/**
* Fill the encrypt layout with the latest data about signature key and encryption keys.
*/
public void updateEncryptLayout() {
if (!isCryptoProviderEnabled()) {
return;
}
if (!mPgpData.hasSignatureKey()) {
mCryptoSignatureCheckbox.setText(R.string.btn_crypto_sign);
mCryptoSignatureCheckbox.setChecked(false);
mCryptoSignatureUserId.setVisibility(View.INVISIBLE);
mCryptoSignatureUserIdRest.setVisibility(View.INVISIBLE);
} else {
// if a signature key is selected, then the checkbox itself has no text
mCryptoSignatureCheckbox.setText("");
mCryptoSignatureCheckbox.setChecked(true);
mCryptoSignatureUserId.setVisibility(View.VISIBLE);
mCryptoSignatureUserIdRest.setVisibility(View.VISIBLE);
mCryptoSignatureUserId.setText(R.string.unknown_crypto_signature_user_id);
mCryptoSignatureUserIdRest.setText("");
String userId = mPgpData.getSignatureUserId();
if (userId != null) {
String chunks[] = mPgpData.getSignatureUserId().split(" <", 2);
mCryptoSignatureUserId.setText(chunks[0]);
if (chunks.length > 1) {
mCryptoSignatureUserIdRest.setText("<" + chunks[1]);
}
}
}
updateMessageFormat();
}
@Override
public void onResume() {
super.onResume();
mIgnoreOnPause = false;
controller.addListener(mListener);
}
@Override
public void onPause() {
super.onPause();
controller.removeListener(mListener);
// Save email as draft when activity is changed (go to home screen, call received) or screen locked
// don't do this if only changing orientations
if (!mIgnoreOnPause && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
saveIfNeeded();
}
}
/**
* The framework handles most of the fields, but we need to handle stuff that we
* dynamically show and hide:
* Attachment list,
* Cc field,
* Bcc field,
* Quoted text,
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_KEY_NUM_ATTACHMENTS_LOADING, mNumAttachmentsLoading);
outState.putString(STATE_KEY_WAITING_FOR_ATTACHMENTS, mWaitingForAttachments.name());
outState.putParcelableArrayList(STATE_KEY_ATTACHMENTS, AttachmentMessageComposeHelper.createAttachmentList(mAttachments));
outState.putBoolean(STATE_KEY_CC_SHOWN, mCcView.getVisibility() == View.VISIBLE);
outState.putBoolean(STATE_KEY_BCC_SHOWN, mBccView.getVisibility() == View.VISIBLE);
outState.putSerializable(STATE_KEY_QUOTED_TEXT_MODE, mQuotedTextMode);
outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, mSourceMessageProcessed);
outState.putLong(STATE_KEY_DRAFT_ID, mDraftId);
outState.putSerializable(STATE_IDENTITY, mIdentity);
outState.putBoolean(STATE_IDENTITY_CHANGED, mIdentityChanged);
outState.putSerializable(STATE_PGP_DATA, mPgpData);
outState.putString(STATE_IN_REPLY_TO, mInReplyTo);
outState.putString(STATE_REFERENCES, mReferences);
outState.putSerializable(STATE_KEY_HTML_QUOTE, mQuotedHtmlContent);
outState.putBoolean(STATE_KEY_READ_RECEIPT, mReadReceipt);
outState.putBoolean(STATE_KEY_DRAFT_NEEDS_SAVING, mDraftNeedsSaving);
outState.putBoolean(STATE_KEY_FORCE_PLAIN_TEXT, mForcePlainText);
outState.putSerializable(STATE_KEY_QUOTED_TEXT_FORMAT, mQuotedTextFormat);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mAttachments.removeAllViews();
mMaxLoaderId = 0;
mNumAttachmentsLoading = savedInstanceState.getInt(STATE_KEY_NUM_ATTACHMENTS_LOADING);
mWaitingForAttachments = WaitingAction.NONE;
try {
String waitingFor = savedInstanceState.getString(STATE_KEY_WAITING_FOR_ATTACHMENTS);
mWaitingForAttachments = WaitingAction.valueOf(waitingFor);
} catch (Exception e) {
Log.w(K9.LOG_TAG, "Couldn't read value \" + STATE_KEY_WAITING_FOR_ATTACHMENTS +" +
"\" from saved instance state", e);
}
List<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_KEY_ATTACHMENTS);
for (Attachment attachment : attachments) {
AttachmentMessageComposeHelper.addAttachmentView(this, mAttachments, attachment);
if (attachment.loaderId > mMaxLoaderId) {
mMaxLoaderId = attachment.loaderId;
}
if (attachment.state == Attachment.LoadingState.URI_ONLY) {
AttachmentMessageComposeHelper.initAttachmentInfoLoader(this, mAttachmentInfoLoaderCallback, attachment);
} else if (attachment.state == Attachment.LoadingState.METADATA) {
AttachmentMessageComposeHelper.initAttachmentContentLoader(this, mAttachmentContentLoaderCallback, attachment);
}
}
mReadReceipt = savedInstanceState
.getBoolean(STATE_KEY_READ_RECEIPT);
mCcView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN) ? View.VISIBLE
: View.GONE);
mBccView.setVisibility(savedInstanceState
.getBoolean(STATE_KEY_BCC_SHOWN) ? View.VISIBLE : View.GONE);
// This method is called after the action bar menu has already been created and prepared.
// So compute the visibility of the "Add Cc/Bcc" menu item again.
computeAddCcBccVisibility();
mQuotedHtmlContent =
(InsertableHtmlContent) savedInstanceState.getSerializable(STATE_KEY_HTML_QUOTE);
if (mQuotedHtmlContent != null && mQuotedHtmlContent.getQuotedContent() != null) {
mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent());
}
mDraftId = savedInstanceState.getLong(STATE_KEY_DRAFT_ID);
mIdentity = (Identity)savedInstanceState.getSerializable(STATE_IDENTITY);
mIdentityChanged = savedInstanceState.getBoolean(STATE_IDENTITY_CHANGED);
mPgpData = (PgpData) savedInstanceState.getSerializable(STATE_PGP_DATA);
mInReplyTo = savedInstanceState.getString(STATE_IN_REPLY_TO);
mReferences = savedInstanceState.getString(STATE_REFERENCES);
mDraftNeedsSaving = savedInstanceState.getBoolean(STATE_KEY_DRAFT_NEEDS_SAVING);
mForcePlainText = savedInstanceState.getBoolean(STATE_KEY_FORCE_PLAIN_TEXT);
mQuotedTextFormat = (SimpleMessageFormat) savedInstanceState.getSerializable(
STATE_KEY_QUOTED_TEXT_FORMAT);
showOrHideQuotedText(
(QuotedTextMode) savedInstanceState.getSerializable(STATE_KEY_QUOTED_TEXT_MODE));
initializeCrypto();
updateFrom();
updateSignature();
updateEncryptLayout();
updateMessageFormat();
}
private void setTitle() {
switch (mAction) {
case REPLY: {
setTitle(R.string.compose_title_reply);
break;
}
case REPLY_ALL: {
setTitle(R.string.compose_title_reply_all);
break;
}
case FORWARD: {
setTitle(R.string.compose_title_forward);
break;
}
case COMPOSE:
default: {
setTitle(R.string.compose_title_compose);
break;
}
}
}
/*
* Returns an Address array of recipients this email will be sent to.
* @return Address array of recipients this email will be sent to.
*/
private List<Address> getRecipientAddresses() {
ArrayList<Address> recipients = new ArrayList<Address>();
recipients.addAll(mToView.getRecipients());
recipients.addAll(mCcView.getRecipients());
recipients.addAll(mBccView.getRecipients());
return recipients;
}
protected TextBody buildText(boolean isDraft) {
return createMessageBuilder(isDraft).buildText();
}
private MimeMessage createDraftMessage() throws MessagingException {
return createMessageBuilder(true).build();
}
protected MimeMessage createMessage() throws MessagingException {
return createMessageBuilder(false).build();
}
private MessageBuilder createMessageBuilder(final boolean isDraft) {
return new MessageBuilder(getApplicationContext())
.setSubject(mSubjectView.getText().toString())
.setTo(mToView.getRecipients())
.setCc(mCcView.getRecipients())
.setBcc(mBccView.getRecipients())
.setInReplyTo(mInReplyTo)
.setReferences(mReferences)
.setRequestReadReceipt(mReadReceipt)
.setIdentity(mIdentity)
.setMessageFormat(mMessageFormat)
.setText(mMessageContentView.getCharacters())
.setPgpData(mPgpData)
.setAttachments(AttachmentMessageComposeHelper.createAttachmentList(mAttachments))
.setSignature(mSignatureView.getCharacters())
.setQuoteStyle(mQuoteStyle)
.setQuotedTextMode(mQuotedTextMode)
.setQuotedText(mQuotedText.getCharacters())
.setQuotedHtmlContent(mQuotedHtmlContent)
.setReplyAfterQuote(mAccount.isReplyAfterQuote())
.setSignatureBeforeQuotedText(mAccount.isSignatureBeforeQuotedText())
.setIdentityChanged(mIdentityChanged)
.setSignatureChanged(mSignatureChanged)
.setCursorPosition(mMessageContentView.getSelectionStart())
.setMessageReference(mMessageReference)
.setDraft(isDraft);
}
private void sendMessage() {
new SendMessageTask().execute();
}
private void saveMessage() {
new SaveMessageTask().execute();
}
private void saveIfNeeded() {
if (!mDraftNeedsSaving || mPreventDraftSaving || mPgpData.hasEncryptionKeys() ||
shouldEncrypt() || !mAccount.hasDraftsFolder()) {
return;
}
mDraftNeedsSaving = false;
saveMessage();
}
public void onEncryptionKeySelectionDone() {
if (mPgpData.hasEncryptionKeys()) {
onSend();
} else {
Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show();
}
}
public void onEncryptDone() {
if (mPgpData.getEncryptedData() != null) {
onSend();
} else {
Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show();
}
}
protected void onSend() {
if (mToView.getRecipients().size() == 0 && mCcView.getRecipients().size() == 0 && mBccView.getRecipients().size() == 0) {
mToView.setError(getString(R.string.message_compose_error_no_recipients));
Toast.makeText(this, getString(R.string.message_compose_error_no_recipients), Toast.LENGTH_LONG).show();
sendMenuButton.setEnabled(true);
return;
}
if (mWaitingForAttachments != WaitingAction.NONE) {
sendMenuButton.setEnabled(true);
return;
}
if (mNumAttachmentsLoading > 0) {
mWaitingForAttachments = WaitingAction.SEND;
sendMenuButton.setEnabled(true);
showWaitingForAttachmentDialog();
} else {
performSend();
}
}
private void performSend() {
if (isCryptoProviderEnabled() && handleEncrypt()) {
return;
}
sendMessage();
updateMessageFlags();
mDraftNeedsSaving = false;
finish();
}
private void updateMessageFlags() {
if (mMessageReference != null && mMessageReference.getFlag() != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Setting referenced message (" + mMessageReference.getFolderName() + ", " + mMessageReference.getUid() + ") flag to " + mMessageReference.getFlag());
}
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.getAccountUuid());
final String folderName = mMessageReference.getFolderName();
final String sourceMessageUid = mMessageReference.getUid();
controller.setFlag(account, folderName, sourceMessageUid, mMessageReference.getFlag(), true);
}
}
private boolean handleEncrypt() {
// user does not want to encrypt...
if ((!mEncryptCheckbox.isChecked() && !mCryptoSignatureCheckbox.isChecked())) {
return false;
}
// SMIME already encrypted
if(currentMessage != null) {
return false;
}
// PGP already encrypted
if(mPgpData.getEncryptedData() != null) {
return false;
}
switch (selectedCryptoProvider) {
case PGP:
openPgpMessageCompose = new OpenPgpMessageCompose(buildText(false), mOpenPgpServiceConnection, getRecipientAddresses(), mPgpData, mHandler, this, mAccount);
openPgpMessageCompose.handlePgp(mEncryptCheckbox.isChecked(), mCryptoSignatureCheckbox.isChecked());
break;
case SMIME:
SmimeMessageCompose smimeMessageCompose = new SmimeMessageCompose(mCryptoSignatureCheckbox.isChecked(), mEncryptCheckbox.isChecked(), getRecipientAddresses(), mIdentity, sMimeApi, mHandler);
smimeMessageCompose.handleSmime();
break;
case NONE:
return false;
}
// onSend() is called again in OpenPgpSignEncryptCallback and with
// encryptedData set in pgpData!
return true;
}
private void onDiscard() {
if (mDraftId != INVALID_DRAFT_ID) {
controller.deleteDraft(mAccount, mDraftId);
mDraftId = INVALID_DRAFT_ID;
}
mHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT);
mDraftNeedsSaving = false;
finish();
}
private void onSave() {
if (mWaitingForAttachments != WaitingAction.NONE) {
return;
}
if (mNumAttachmentsLoading > 0) {
mWaitingForAttachments = WaitingAction.SAVE;
showWaitingForAttachmentDialog();
} else {
performSave();
}
}
private void performSave() {
saveIfNeeded();
finish();
}
private void onAddCcBcc() {
mCcView.setVisibility(View.VISIBLE);
mBccView.setVisibility(View.VISIBLE);
computeAddCcBccVisibility();
}
/**
* Hide the 'Add Cc/Bcc' menu item when both fields are visible.
*/
private void computeAddCcBccVisibility() {
if (mMenu != null && mCcView.getVisibility() == View.VISIBLE &&
mBccView.getVisibility() == View.VISIBLE) {
mMenu.findItem(R.id.add_cc_bcc).setVisible(false);
}
}
private void onReadReceipt() {
CharSequence txt;
if (mReadReceipt == false) {
txt = getString(R.string.read_receipt_enabled);
mReadReceipt = true;
} else {
txt = getString(R.string.read_receipt_disabled);
mReadReceipt = false;
}
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, txt, Toast.LENGTH_SHORT);
toast.show();
}
/**
* Kick off a picker for the specified MIME type and let Android take over.
*
* @param mime_type
* The MIME type we want our attachment to have.
*/
@SuppressLint("InlinedApi")
private void onAddAttachment(final String mime_type) {
if (isCryptoProviderEnabled()) {
Toast.makeText(this, R.string.attachment_encryption_unsupported, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(mime_type);
mIgnoreOnPause = true;
startActivityForResult(Intent.createChooser(i, null), ACTIVITY_REQUEST_PICK_ATTACHMENT);
}
public int increaseAndReturnMaxLoadId() {
return ++mMaxLoaderId;
}
private LoaderManager.LoaderCallbacks<Attachment> mAttachmentContentLoaderCallback =
new AttachmentContentLoaderCallback(this);
private LoaderManager.LoaderCallbacks<Attachment> mAttachmentInfoLoaderCallback =
new AttachmentInfoLoaderCallback(this, mAttachmentContentLoaderCallback);
public void onFetchAttachmentStarted() {
mNumAttachmentsLoading += 1;
}
public void onFetchAttachmentFinished() {
// We're not allowed to perform fragment transactions when called from onLoadFinished().
// So we use the Handler to call performStalledAction().
mHandler.sendEmptyMessage(MSG_PERFORM_STALLED_ACTION);
}
void performStalledAction() {
mNumAttachmentsLoading -= 1;
WaitingAction waitingFor = mWaitingForAttachments;
mWaitingForAttachments = WaitingAction.NONE;
if (waitingFor != WaitingAction.NONE) {
dismissWaitingForAttachmentDialog();
}
switch (waitingFor) {
case SEND: {
performSend();
break;
}
case SAVE: {
performSave();
break;
}
case NONE:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if a CryptoSystem activity is returning, then mPreventDraftSaving was set to true
mPreventDraftSaving = false;
// OpenPGP: try again after user interaction
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_SIGN_ENCRYPT_OPENPGP) {
/*
* The data originally given to the pgp method are are again
* returned here to be used when calling again after user
* interaction. They also contain results from the user interaction
* which happened, for example selected key ids.
*/
openPgpMessageCompose.executeOpenPgpMethod(data);
return;
}
if (resultCode != RESULT_OK) {
return;
}
if (data == null) {
return;
}
switch (requestCode) {
case ACTIVITY_REQUEST_PICK_ATTACHMENT:
AttachmentMessageComposeHelper.addAttachmentsFromResultIntent(this, data, mAttachmentInfoLoaderCallback);
mDraftNeedsSaving = true;
break;
case CONTACT_PICKER_TO:
case CONTACT_PICKER_CC:
case CONTACT_PICKER_BCC:
ContactItem contact = mContacts.extractInfoFromContactPickerIntent(data);
if (contact == null) {
Toast.makeText(this, getString(R.string.error_contact_address_not_found), Toast.LENGTH_LONG).show();
return;
}
if (contact.emailAddresses.size() > 1) {
Intent i = new Intent(this, EmailAddressList.class);
i.putExtra(EmailAddressList.EXTRA_CONTACT_ITEM, contact);
if (requestCode == CONTACT_PICKER_TO) {
startActivityForResult(i, CONTACT_PICKER_TO2);
} else if (requestCode == CONTACT_PICKER_CC) {
startActivityForResult(i, CONTACT_PICKER_CC2);
} else if (requestCode == CONTACT_PICKER_BCC) {
startActivityForResult(i, CONTACT_PICKER_BCC2);
}
return;
}
if (K9.DEBUG) {
List<String> emails = contact.emailAddresses;
for (int i = 0; i < emails.size(); i++) {
Log.v(K9.LOG_TAG, "email[" + i + "]: " + emails.get(i));
}
}
String email = contact.emailAddresses.get(0);
if (requestCode == CONTACT_PICKER_TO) {
mToView.addRecipient(new Address(email, ""));
} else if (requestCode == CONTACT_PICKER_CC) {
mCcView.addRecipient(new Address(email, ""));
} else if (requestCode == CONTACT_PICKER_BCC) {
mBccView.addRecipient(new Address(email, ""));
} else {
return;
}
break;
case CONTACT_PICKER_TO2:
case CONTACT_PICKER_CC2:
case CONTACT_PICKER_BCC2:
String emailAddr = data.getStringExtra(EmailAddressList.EXTRA_EMAIL_ADDRESS);
if (requestCode == CONTACT_PICKER_TO2) {
mToView.addRecipient(new Address(emailAddr, ""));
} else if (requestCode == CONTACT_PICKER_CC2) {
mCcView.addRecipient(new Address(emailAddr, ""));
} else if (requestCode == CONTACT_PICKER_BCC2) {
mBccView.addRecipient(new Address(emailAddr, ""));
}
break;
}
}
private void onAccountChosen(Account account, Identity identity) {
if (!mAccount.equals(account)) {
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Switching account from " + mAccount + " to " + account);
}
// on draft edit, make sure we don't keep previous message UID
if (mAction == Action.EDIT_DRAFT) {
mMessageReference = null;
}
// test whether there is something to save
if (mDraftNeedsSaving || (mDraftId != INVALID_DRAFT_ID)) {
final long previousDraftId = mDraftId;
final Account previousAccount = mAccount;
// make current message appear as new
mDraftId = INVALID_DRAFT_ID;
// actual account switch
mAccount = account;
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account");
}
saveMessage();
if (previousDraftId != INVALID_DRAFT_ID) {
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: "
+ previousDraftId);
}
controller.deleteDraft(previousAccount, previousDraftId);
}
} else {
mAccount = account;
}
// Show CC/BCC text input field when switching to an account that always wants them
// displayed.
// Please note that we're not hiding the fields if the user switches back to an account
// that doesn't have this setting checked.
if (mAccount.isAlwaysShowCcBcc()) {
onAddCcBcc();
}
// not sure how to handle mFolder, mSourceMessage?
}
switchToIdentity(identity);
}
private void switchToIdentity(Identity identity) {
mIdentity = identity;
mIdentityChanged = true;
mDraftNeedsSaving = true;
updateFrom();
updateBcc();
updateSignature();
updateMessageFormat();
}
private void updateFrom() {
mChooseIdentityButton.setText(mIdentity.getEmail());
}
private void updateBcc() {
if (mIdentityChanged) {
mBccView.setVisibility(View.VISIBLE);
}
mBccView.clearRecipients();
mBccView.addRecipients(Address.parseUnencoded(mAccount.getAlwaysBcc()));
}
private void updateSignature() {
if (mIdentity.getSignatureUse()) {
mSignatureView.setCharacters(mIdentity.getSignature());
mSignatureView.setVisibility(View.VISIBLE);
} else {
mSignatureView.setVisibility(View.GONE);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.attachment_delete:
/*
* The view is the delete button, and we have previously set the tag of
* the delete button to the view that owns it. We don't use parent because the
* view is very complex and could change in the future.
*/
mAttachments.removeView((View) view.getTag());
mDraftNeedsSaving = true;
break;
case R.id.quoted_text_show:
showOrHideQuotedText(QuotedTextMode.SHOW);
updateMessageFormat();
mDraftNeedsSaving = true;
break;
case R.id.quoted_text_delete:
showOrHideQuotedText(QuotedTextMode.HIDE);
updateMessageFormat();
mDraftNeedsSaving = true;
break;
case R.id.quoted_text_edit:
mForcePlainText = true;
if (mMessageReference != null) { // shouldn't happen...
// TODO - Should we check if mSourceMessageBody is already present and bypass the MessagingController call?
controller.addListener(mListener);
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.getAccountUuid());
final String folderName = mMessageReference.getFolderName();
final String sourceMessageUid = mMessageReference.getUid();
controller.loadMessageForView(account, folderName, sourceMessageUid, null);
}
break;
case R.id.identity:
createChooseIdentityDialog().show();
break;
}
}
/**
* Show or hide the quoted text.
*
* @param mode
* The value to set {@link #mQuotedTextMode} to.
*/
private void showOrHideQuotedText(QuotedTextMode mode) {
mQuotedTextMode = mode;
switch (mode) {
case NONE:
case HIDE: {
if (mode == QuotedTextMode.NONE) {
mQuotedTextShow.setVisibility(View.GONE);
} else {
mQuotedTextShow.setVisibility(View.VISIBLE);
}
mQuotedTextBar.setVisibility(View.GONE);
mQuotedText.setVisibility(View.GONE);
mQuotedHTML.setVisibility(View.GONE);
mQuotedTextEdit.setVisibility(View.GONE);
break;
}
case SHOW: {
mQuotedTextShow.setVisibility(View.GONE);
mQuotedTextBar.setVisibility(View.VISIBLE);
if (mQuotedTextFormat == SimpleMessageFormat.HTML) {
mQuotedText.setVisibility(View.GONE);
mQuotedHTML.setVisibility(View.VISIBLE);
mQuotedTextEdit.setVisibility(View.VISIBLE);
} else {
mQuotedText.setVisibility(View.VISIBLE);
mQuotedHTML.setVisibility(View.GONE);
mQuotedTextEdit.setVisibility(View.GONE);
}
break;
}
}
}
private void askBeforeDiscard(){
if (K9.confirmDiscardMessage()) {
createConfirmDiscardDialog2().show();
} else {
onDiscard();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.send:
sendMenuButton.setEnabled(false);
mPgpData.setEncryptionKeys(null);
onSend();
break;
case R.id.save:
if (shouldEncrypt()) {
createCanNotSaveEncryptedDialog().show();
} else {
onSave();
}
break;
case R.id.discard:
askBeforeDiscard();
break;
case R.id.add_cc_bcc:
onAddCcBcc();
break;
case R.id.add_attachment:
onAddAttachment("*/*");
break;
case R.id.read_receipt:
onReadReceipt();
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.message_compose_option, menu);
mMenu = menu;
// Disable the 'Save' menu option if Drafts folder is set to -NONE-
if (!mAccount.hasDraftsFolder()) {
menu.findItem(R.id.save).setEnabled(false);
}
sendMenuButton = menu.findItem(R.id.send);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
computeAddCcBccVisibility();
return true;
}
@Override
public void onBackPressed() {
if (mDraftNeedsSaving) {
if (shouldEncrypt()) {
createCanNotSaveEncryptedDialog().show();
} else if (!mAccount.hasDraftsFolder()) {
createConfirmDiscardDialog().show();
} else {
createSaveOrDiscardDialog().show();
}
} else {
// Check if editing an existing draft.
if (mDraftId == INVALID_DRAFT_ID) {
onDiscard();
} else {
super.onBackPressed();
}
}
}
private void showWaitingForAttachmentDialog() {
String title;
switch (mWaitingForAttachments) {
case SEND: {
title = getString(R.string.fetching_attachment_dialog_title_send);
break;
}
case SAVE: {
title = getString(R.string.fetching_attachment_dialog_title_save);
break;
}
default: {
return;
}
}
ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(title,
getString(R.string.fetching_attachment_dialog_message));
fragment.show(getSupportFragmentManager(), FRAGMENT_WAITING_FOR_ATTACHMENT);
}
public void onCancel(ProgressDialogFragment fragment) {
attachmentProgressDialogCancelled();
}
void attachmentProgressDialogCancelled() {
mWaitingForAttachments = WaitingAction.NONE;
}
private void dismissWaitingForAttachmentDialog() {
ProgressDialogFragment fragment = (ProgressDialogFragment)
getSupportFragmentManager().findFragmentByTag(FRAGMENT_WAITING_FOR_ATTACHMENT);
if (fragment != null) {
fragment.dismiss();
}
}
private AlertDialog createConfirmDiscardDialog() {
return new AlertDialog.Builder(this)
.setTitle(R.string.confirm_discard_draft_message_title)
.setMessage(R.string.confirm_discard_draft_message)
.setPositiveButton(R.string.cancel_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
Toast.makeText(MessageCompose.this,
getString(R.string.message_discarded_toast),
Toast.LENGTH_LONG).show();
onDiscard();
}
})
.create();
}
private AlertDialog createConfirmDiscardDialog2() {
return new AlertDialog.Builder(this)
.setTitle(R.string.dialog_confirm_delete_title)
.setMessage(R.string.dialog_confirm_delete_message)
.setPositiveButton(R.string.dialog_confirm_delete_confirm_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onDiscard();
}
})
.setNegativeButton(R.string.dialog_confirm_delete_cancel_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
}
private AlertDialog createChooseIdentityDialog() {
Context context = new ContextThemeWrapper(this,
(K9.getK9Theme() == K9.Theme.LIGHT) ?
R.style.Theme_K9_Dialog_Light :
R.style.Theme_K9_Dialog_Dark);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.send_as);
final IdentityAdapter adapter = new IdentityAdapter(context);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
IdentityContainer container = (IdentityContainer) adapter.getItem(which);
onAccountChosen(container.account, container.identity);
}
});
return builder.create();
}
private AlertDialog createCanNotSaveEncryptedDialog() {
return new AlertDialog.Builder(this)
.setTitle(R.string.refuse_to_save_draft_marked_encrypted_dlg_title)
.setMessage(R.string.refuse_to_save_draft_marked_encrypted_instructions_fmt)
.setNeutralButton(R.string.okay_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.create();
}
private AlertDialog createSaveOrDiscardDialog() {
return new AlertDialog.Builder(this)
.setTitle(R.string.save_or_discard_draft_message_dlg_title)
.setMessage(R.string.save_or_discard_draft_message_instructions_fmt)
.setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
onSave();
}
})
.setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
onDiscard();
}
})
.create();
}
/**
* Add all attachments of an existing message as if they were added by hand.
*
* @param part
* The message part to check for being an attachment. This method will recurse if it's
* a multipart part.
* @param depth
* The recursion depth. Currently unused.
*
* @return {@code true} if all attachments were able to be attached, {@code false} otherwise.
*
* @throws MessagingException
* In case of an error
*/
private boolean loadAttachments(Part part, int depth) throws MessagingException {
if (part.getBody() instanceof Multipart) {
Multipart mp = (Multipart) part.getBody();
boolean ret = true;
for (int i = 0, count = mp.getCount(); i < count; i++) {
if (!loadAttachments(mp.getBodyPart(i), depth + 1)) {
ret = false;
}
}
return ret;
}
String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
String name = MimeUtility.getHeaderParameter(contentType, "name");
if (name != null) {
Body body = part.getBody();
//FIXME
// if (body instanceof LocalAttachmentBody) {
// final Uri uri = ((LocalAttachmentBody) body).getContentUri();
// mHandler.post(new Runnable() {
// @Override
// public void run() {
// addAttachment(uri);
// }
// });
// } else {
// return false;
// }
return false;
}
return true;
}
/**
* Pull out the parts of the now loaded source message and apply them to the new message
* depending on the type of message being composed.
*
* @param message
* The source message used to populate the various text fields.
*/
private void processSourceMessage(LocalMessage message) {
try {
switch (mAction) {
case REPLY:
case REPLY_ALL: {
processMessageToReplyTo(message);
break;
}
case FORWARD: {
processMessageToForward(message);
break;
}
case EDIT_DRAFT: {
processDraftMessage(message);
break;
}
default: {
Log.w(K9.LOG_TAG, "processSourceMessage() called with unsupported action");
break;
}
}
} catch (MessagingException me) {
/**
* Let the user continue composing their message even if we have a problem processing
* the source message. Log it as an error, though.
*/
Log.e(K9.LOG_TAG, "Error while processing source message: ", me);
} finally {
mSourceMessageProcessed = true;
mDraftNeedsSaving = false;
}
updateMessageFormat();
}
private void processMessageToReplyTo(Message message) throws MessagingException {
if (message.getSubject() != null) {
final String subject = PREFIX.matcher(message.getSubject()).replaceFirst("");
if (!subject.toLowerCase(Locale.US).startsWith("re:")) {
mSubjectView.setText("Re: " + subject);
} else {
mSubjectView.setText(subject);
}
} else {
mSubjectView.setText("");
}
/*
* If a reply-to was included with the message use that, otherwise use the from
* or sender address.
*/
Address[] replyToAddresses;
if (message.getReplyTo().length > 0) {
replyToAddresses = message.getReplyTo();
} else {
replyToAddresses = message.getFrom();
}
// if we're replying to a message we sent, we probably meant
// to reply to the recipient of that message
if (mAccount.isAnIdentity(replyToAddresses)) {
replyToAddresses = message.getRecipients(RecipientType.TO);
}
mToView.addRecipients(replyToAddresses);
if (message.getMessageId() != null && message.getMessageId().length() > 0) {
mInReplyTo = message.getMessageId();
String[] refs = message.getReferences();
if (refs != null && refs.length > 0) {
mReferences = TextUtils.join("", refs) + " " + mInReplyTo;
} else {
mReferences = mInReplyTo;
}
} else {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "could not get Message-ID.");
}
}
// Quote the message and setup the UI.
populateUIWithQuotedMessage(mAccount.isDefaultQuotedTextShown());
if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) {
Identity useIdentity = IdentityHelper.getRecipientIdentityFromMessage(mAccount, message);
Identity defaultIdentity = mAccount.getIdentity(0);
if (useIdentity != defaultIdentity) {
switchToIdentity(useIdentity);
}
}
if (mAction == Action.REPLY_ALL) {
if (message.getReplyTo().length > 0) {
for (Address address : message.getFrom()) {
if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) {
mToView.addRecipient(address);
}
}
}
for (Address address : message.getRecipients(RecipientType.TO)) {
if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) {
mToView.addRecipient(address);
}
}
if (message.getRecipients(RecipientType.CC).length > 0) {
for (Address address : message.getRecipients(RecipientType.CC)) {
if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) {
mCcView.addRecipient(address);
}
}
mCcView.setVisibility(View.VISIBLE);
}
}
}
private void processMessageToForward(Message message) throws MessagingException {
String subject = message.getSubject();
if (subject != null && !subject.toLowerCase(Locale.US).startsWith("fwd:")) {
mSubjectView.setText("Fwd: " + subject);
} else {
mSubjectView.setText(subject);
}
mQuoteStyle = QuoteStyle.HEADER;
// "Be Like Thunderbird" - on forwarded messages, set the message ID
// of the forwarded message in the references and the reply to. TB
// only includes ID of the message being forwarded in the reference,
// even if there are multiple references.
if (!TextUtils.isEmpty(message.getMessageId())) {
mInReplyTo = message.getMessageId();
mReferences = mInReplyTo;
} else {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "could not get Message-ID.");
}
}
// Quote the message and setup the UI.
populateUIWithQuotedMessage(true);
if (!mSourceMessageProcessed) {
if (!loadAttachments(message, 0)) {
mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS);
}
}
}
private void processDraftMessage(LocalMessage message) throws MessagingException {
String showQuotedTextMode = "NONE";
mDraftId = controller.getId(message);
mSubjectView.setText(message.getSubject());
mToView.addRecipients(message.getRecipients(RecipientType.TO));
if (message.getRecipients(RecipientType.CC).length > 0) {
mCcView.addRecipients(message.getRecipients(RecipientType.CC));
mCcView.setVisibility(View.VISIBLE);
}
Address[] bccRecipients = message.getRecipients(RecipientType.BCC);
if (bccRecipients.length > 0) {
mBccView.addRecipients(bccRecipients);
String bccAddress = mAccount.getAlwaysBcc();
if (bccRecipients.length == 1 && bccAddress != null && bccAddress.equals(bccRecipients[0].toString())) {
// If the auto-bcc is the only entry in the BCC list, don't show the Bcc fields.
mBccView.setVisibility(View.GONE);
} else {
mBccView.setVisibility(View.VISIBLE);
}
}
// Read In-Reply-To header from draft
final String[] inReplyTo = message.getHeader("In-Reply-To");
if (inReplyTo.length >= 1) {
mInReplyTo = inReplyTo[0];
}
// Read References header from draft
final String[] references = message.getHeader("References");
if (references.length >= 1) {
mReferences = references[0];
}
if (!mSourceMessageProcessed) {
loadAttachments(message, 0);
}
// Decode the identity header when loading a draft.
// See buildIdentityHeader(TextBody) for a detailed description of the composition of this blob.
Map<IdentityField, String> k9identity = new HashMap<IdentityField, String>();
String[] identityHeaders = message.getHeader(K9.IDENTITY_HEADER);
if (identityHeaders.length > 0 && identityHeaders[0] != null) {
k9identity = IdentityHeaderParser.parse(identityHeaders[0]);
}
Identity newIdentity = new Identity();
if (k9identity.containsKey(IdentityField.SIGNATURE)) {
newIdentity.setSignatureUse(true);
newIdentity.setSignature(k9identity.get(IdentityField.SIGNATURE));
mSignatureChanged = true;
} else {
newIdentity.setSignatureUse(message.getFolder().getSignatureUse());
newIdentity.setSignature(mIdentity.getSignature());
}
if (k9identity.containsKey(IdentityField.NAME)) {
newIdentity.setName(k9identity.get(IdentityField.NAME));
mIdentityChanged = true;
} else {
newIdentity.setName(mIdentity.getName());
}
if (k9identity.containsKey(IdentityField.EMAIL)) {
newIdentity.setEmail(k9identity.get(IdentityField.EMAIL));
mIdentityChanged = true;
} else {
newIdentity.setEmail(mIdentity.getEmail());
}
if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) {
mMessageReference = null;
try {
String originalMessage = k9identity.get(IdentityField.ORIGINAL_MESSAGE);
MessageReference messageReference = new MessageReference(originalMessage);
// Check if this is a valid account in our database
Preferences prefs = Preferences.getPreferences(getApplicationContext());
Account account = prefs.getAccount(messageReference.getAccountUuid());
if (account != null) {
mMessageReference = messageReference;
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Could not decode message reference in identity.", e);
}
}
int cursorPosition = 0;
if (k9identity.containsKey(IdentityField.CURSOR_POSITION)) {
try {
cursorPosition = Integer.parseInt(k9identity.get(IdentityField.CURSOR_POSITION));
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Could not parse cursor position for MessageCompose; continuing.", e);
}
}
if (k9identity.containsKey(IdentityField.QUOTED_TEXT_MODE)) {
showQuotedTextMode = k9identity.get(IdentityField.QUOTED_TEXT_MODE);
}
mIdentity = newIdentity;
updateSignature();
updateFrom();
Integer bodyLength = k9identity.get(IdentityField.LENGTH) != null
? Integer.valueOf(k9identity.get(IdentityField.LENGTH))
: 0;
Integer bodyOffset = k9identity.get(IdentityField.OFFSET) != null
? Integer.valueOf(k9identity.get(IdentityField.OFFSET))
: 0;
Integer bodyFooterOffset = k9identity.get(IdentityField.FOOTER_OFFSET) != null
? Integer.valueOf(k9identity.get(IdentityField.FOOTER_OFFSET))
: null;
Integer bodyPlainLength = k9identity.get(IdentityField.PLAIN_LENGTH) != null
? Integer.valueOf(k9identity.get(IdentityField.PLAIN_LENGTH))
: null;
Integer bodyPlainOffset = k9identity.get(IdentityField.PLAIN_OFFSET) != null
? Integer.valueOf(k9identity.get(IdentityField.PLAIN_OFFSET))
: null;
mQuoteStyle = k9identity.get(IdentityField.QUOTE_STYLE) != null
? QuoteStyle.valueOf(k9identity.get(IdentityField.QUOTE_STYLE))
: mAccount.getQuoteStyle();
QuotedTextMode quotedMode;
try {
quotedMode = QuotedTextMode.valueOf(showQuotedTextMode);
} catch (Exception e) {
quotedMode = QuotedTextMode.NONE;
}
// Always respect the user's current composition format preference, even if the
// draft was saved in a different format.
// TODO - The current implementation doesn't allow a user in HTML mode to edit a draft that wasn't saved with K9mail.
String messageFormatString = k9identity.get(IdentityField.MESSAGE_FORMAT);
MessageFormat messageFormat = null;
if (messageFormatString != null) {
try {
messageFormat = MessageFormat.valueOf(messageFormatString);
} catch (Exception e) { /* do nothing */ }
}
if (messageFormat == null) {
// This message probably wasn't created by us. The exception is legacy
// drafts created before the advent of HTML composition. In those cases,
// we'll display the whole message (including the quoted part) in the
// composition window. If that's the case, try and convert it to text to
// match the behavior in text mode.
mMessageContentView.setCharacters(getBodyTextFromMessage(message, SimpleMessageFormat.TEXT));
mForcePlainText = true;
showOrHideQuotedText(quotedMode);
return;
}
if (messageFormat == MessageFormat.HTML) {
Part part = MimeUtility.findFirstPartByMimeType(message, "text/html");
if (part != null) { // Shouldn't happen if we were the one who saved it.
mQuotedTextFormat = SimpleMessageFormat.HTML;
String text = MessageExtractor.getTextFromPart(part);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + ".");
}
if (bodyOffset + bodyLength > text.length()) {
// The draft was edited outside of K-9 Mail?
K9.logDebug( "The identity field from the draft contains an invalid LENGTH/OFFSET");
bodyOffset = 0;
bodyLength = 0;
}
// Grab our reply text.
String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength);
mMessageContentView.setCharacters(HtmlConverter.htmlToText(bodyText));
// Regenerate the quoted html without our user content in it.
StringBuilder quotedHTML = new StringBuilder();
quotedHTML.append(text.substring(0, bodyOffset)); // stuff before the reply
quotedHTML.append(text.substring(bodyOffset + bodyLength));
if (quotedHTML.length() > 0) {
mQuotedHtmlContent = new InsertableHtmlContent();
mQuotedHtmlContent.setQuotedContent(quotedHTML);
// We don't know if bodyOffset refers to the header or to the footer
mQuotedHtmlContent.setHeaderInsertionPoint(bodyOffset);
if (bodyFooterOffset != null) {
mQuotedHtmlContent.setFooterInsertionPoint(bodyFooterOffset);
} else {
mQuotedHtmlContent.setFooterInsertionPoint(bodyOffset);
}
mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent());
}
}
if (bodyPlainOffset != null && bodyPlainLength != null) {
processSourceMessageText(message, bodyPlainOffset, bodyPlainLength, false);
}
} else if (messageFormat == MessageFormat.TEXT) {
mQuotedTextFormat = SimpleMessageFormat.TEXT;
processSourceMessageText(message, bodyOffset, bodyLength, true);
} else {
Log.e(K9.LOG_TAG, "Unhandled message format.");
}
// Set the cursor position if we have it.
try {
mMessageContentView.setSelection(cursorPosition);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Could not set cursor position in MessageCompose; ignoring.", e);
}
showOrHideQuotedText(quotedMode);
}
/**
* Pull out the parts of the now loaded source message and apply them to the new message
* depending on the type of message being composed.
* @param message Source message
* @param bodyOffset Insertion point for reply.
* @param bodyLength Length of reply.
* @param viewMessageContent Update mMessageContentView or not.
* @throws MessagingException
*/
private void processSourceMessageText(Message message, Integer bodyOffset, Integer bodyLength,
boolean viewMessageContent) throws MessagingException {
Part textPart = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (textPart != null) {
String text = MessageExtractor.getTextFromPart(textPart);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + ".");
}
// If we had a body length (and it was valid), separate the composition from the quoted text
// and put them in their respective places in the UI.
if (bodyLength > 0) {
try {
String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength);
// Regenerate the quoted text without our user content in it nor added newlines.
StringBuilder quotedText = new StringBuilder();
if (bodyOffset == 0 && text.substring(bodyLength, bodyLength + 4).equals("\r\n\r\n")) {
// top-posting: ignore two newlines at start of quote
quotedText.append(text.substring(bodyLength + 4));
} else if (bodyOffset + bodyLength == text.length() &&
text.substring(bodyOffset - 2, bodyOffset).equals("\r\n")) {
// bottom-posting: ignore newline at end of quote
quotedText.append(text.substring(0, bodyOffset - 2));
} else {
quotedText.append(text.substring(0, bodyOffset)); // stuff before the reply
quotedText.append(text.substring(bodyOffset + bodyLength));
}
if (viewMessageContent) {
mMessageContentView.setCharacters(bodyText);
}
mQuotedText.setCharacters(quotedText);
} catch (IndexOutOfBoundsException e) {
// Invalid bodyOffset or bodyLength. The draft was edited outside of K-9 Mail?
K9.logDebug( "The identity field from the draft contains an invalid bodyOffset/bodyLength");
if (viewMessageContent) {
mMessageContentView.setCharacters(text);
}
}
} else {
if (viewMessageContent) {
mMessageContentView.setCharacters(text);
}
}
}
}
// Regexes to check for signature.
private static final Pattern DASH_SIGNATURE_PLAIN = Pattern.compile("\r\n-- \r\n.*", Pattern.DOTALL);
private static final Pattern DASH_SIGNATURE_HTML = Pattern.compile("(<br( /)?>|\r?\n)-- <br( /)?>", Pattern.CASE_INSENSITIVE);
private static final Pattern BLOCKQUOTE_START = Pattern.compile("<blockquote", Pattern.CASE_INSENSITIVE);
private static final Pattern BLOCKQUOTE_END = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE);
/**
* Build and populate the UI with the quoted message.
*
* @param showQuotedText
* {@code true} if the quoted text should be shown, {@code false} otherwise.
*
* @throws MessagingException
*/
private void populateUIWithQuotedMessage(boolean showQuotedText) throws MessagingException {
MessageFormat origMessageFormat = mAccount.getMessageFormat();
if (mForcePlainText || origMessageFormat == MessageFormat.TEXT) {
// Use plain text for the quoted message
mQuotedTextFormat = SimpleMessageFormat.TEXT;
} else if (origMessageFormat == MessageFormat.AUTO) {
// Figure out which message format to use for the quoted text by looking if the source
// message contains a text/html part. If it does, we use that.
mQuotedTextFormat =
(MimeUtility.findFirstPartByMimeType(mSourceMessage, "text/html") == null) ?
SimpleMessageFormat.TEXT : SimpleMessageFormat.HTML;
} else {
mQuotedTextFormat = SimpleMessageFormat.HTML;
}
// TODO -- I am assuming that mSourceMessageBody will always be a text part. Is this a safe assumption?
// Handle the original message in the reply
// If we already have mSourceMessageBody, use that. It's pre-populated if we've got crypto going on.
String content = (mSourceMessageBody != null) ?
mSourceMessageBody :
getBodyTextFromMessage(mSourceMessage, mQuotedTextFormat);
if (mQuotedTextFormat == SimpleMessageFormat.HTML) {
// Strip signature.
// closing tags such as </div>, </span>, </table>, </pre> will be cut off.
if (mAccount.isStripSignature() &&
(mAction == Action.REPLY || mAction == Action.REPLY_ALL)) {
Matcher dashSignatureHtml = DASH_SIGNATURE_HTML.matcher(content);
if (dashSignatureHtml.find()) {
Matcher blockquoteStart = BLOCKQUOTE_START.matcher(content);
Matcher blockquoteEnd = BLOCKQUOTE_END.matcher(content);
List<Integer> start = new ArrayList<Integer>();
List<Integer> end = new ArrayList<Integer>();
while (blockquoteStart.find()) {
start.add(blockquoteStart.start());
}
while (blockquoteEnd.find()) {
end.add(blockquoteEnd.start());
}
if (start.size() != end.size()) {
Log.d(K9.LOG_TAG, "There are " + start.size() + " <blockquote> tags, but " +
end.size() + " </blockquote> tags. Refusing to strip.");
} else if (start.size() > 0) {
// Ignore quoted signatures in blockquotes.
dashSignatureHtml.region(0, start.get(0));
if (dashSignatureHtml.find()) {
// before first <blockquote>.
content = content.substring(0, dashSignatureHtml.start());
} else {
for (int i = 0; i < start.size() - 1; i++) {
// within blockquotes.
if (end.get(i) < start.get(i + 1)) {
dashSignatureHtml.region(end.get(i), start.get(i + 1));
if (dashSignatureHtml.find()) {
content = content.substring(0, dashSignatureHtml.start());
break;
}
}
}
if (end.get(end.size() - 1) < content.length()) {
// after last </blockquote>.
dashSignatureHtml.region(end.get(end.size() - 1), content.length());
if (dashSignatureHtml.find()) {
content = content.substring(0, dashSignatureHtml.start());
}
}
}
} else {
// No blockquotes found.
content = content.substring(0, dashSignatureHtml.start());
}
}
// Fix the stripping off of closing tags if a signature was stripped,
// as well as clean up the HTML of the quoted message.
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties properties = cleaner.getProperties();
// see http://htmlcleaner.sourceforge.net/parameters.php for descriptions
properties.setNamespacesAware(false);
properties.setAdvancedXmlEscape(false);
properties.setOmitXmlDeclaration(true);
properties.setOmitDoctypeDeclaration(false);
properties.setTranslateSpecialEntities(false);
properties.setRecognizeUnicodeChars(false);
TagNode node = cleaner.clean(content);
SimpleHtmlSerializer htmlSerialized = new SimpleHtmlSerializer(properties);
content = htmlSerialized.getAsString(node, "UTF8");
}
// Add the HTML reply header to the top of the content.
mQuotedHtmlContent = quoteOriginalHtmlMessage(mSourceMessage, content, mQuoteStyle);
// Load the message with the reply header.
mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent());
// TODO: Also strip the signature from the text/plain part
mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage,
getBodyTextFromMessage(mSourceMessage, SimpleMessageFormat.TEXT), mQuoteStyle));
} else if (mQuotedTextFormat == SimpleMessageFormat.TEXT) {
if (mAccount.isStripSignature() &&
(mAction == Action.REPLY || mAction == Action.REPLY_ALL)) {
if (DASH_SIGNATURE_PLAIN.matcher(content).find()) {
content = DASH_SIGNATURE_PLAIN.matcher(content).replaceFirst("\r\n");
}
}
mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage, content, mQuoteStyle));
}
if (showQuotedText) {
showOrHideQuotedText(QuotedTextMode.SHOW);
} else {
showOrHideQuotedText(QuotedTextMode.HIDE);
}
}
/**
* Fetch the body text from a message in the desired message format. This method handles
* conversions between formats (html to text and vice versa) if necessary.
* @param message Message to analyze for body part.
* @param format Desired format.
* @return Text in desired format.
* @throws MessagingException
*/
private String getBodyTextFromMessage(final Message message, final SimpleMessageFormat format)
throws MessagingException {
Part part;
if (format == SimpleMessageFormat.HTML) {
// HTML takes precedence, then text.
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
if (part != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, HTML found.");
}
return MessageExtractor.getTextFromPart(part);
}
part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, text found.");
}
String text = MessageExtractor.getTextFromPart(part);
return HtmlConverter.textToHtml(text);
}
} else if (format == SimpleMessageFormat.TEXT) {
// Text takes precedence, then html.
part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, text found.");
}
return MessageExtractor.getTextFromPart(part);
}
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
if (part != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, HTML found.");
}
String text = MessageExtractor.getTextFromPart(part);
return HtmlConverter.htmlToText(text);
}
}
// If we had nothing interesting, return an empty string.
return "";
}
// Regular expressions to look for various HTML tags. This is no HTML::Parser, but hopefully it's good enough for
// our purposes.
private static final Pattern FIND_INSERTION_POINT_HTML = Pattern.compile("(?si:.*?(<html(?:>|\\s+[^>]*>)).*)");
private static final Pattern FIND_INSERTION_POINT_HEAD = Pattern.compile("(?si:.*?(<head(?:>|\\s+[^>]*>)).*)");
private static final Pattern FIND_INSERTION_POINT_BODY = Pattern.compile("(?si:.*?(<body(?:>|\\s+[^>]*>)).*)");
private static final Pattern FIND_INSERTION_POINT_HTML_END = Pattern.compile("(?si:.*(</html>).*?)");
private static final Pattern FIND_INSERTION_POINT_BODY_END = Pattern.compile("(?si:.*(</body>).*?)");
// The first group in a Matcher contains the first capture group. We capture the tag found in the above REs so that
// we can locate the *end* of that tag.
private static final int FIND_INSERTION_POINT_FIRST_GROUP = 1;
// HTML bits to insert as appropriate
// TODO is it safe to assume utf-8 here?
private static final String FIND_INSERTION_POINT_HTML_CONTENT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>";
private static final String FIND_INSERTION_POINT_HTML_END_CONTENT = "</html>";
private static final String FIND_INSERTION_POINT_HEAD_CONTENT = "<head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head>";
// Index of the start of the beginning of a String.
private static final int FIND_INSERTION_POINT_START_OF_STRING = 0;
/**
* <p>Find the start and end positions of the HTML in the string. This should be the very top
* and bottom of the displayable message. It returns a {@link InsertableHtmlContent}, which
* contains both the insertion points and potentially modified HTML. The modified HTML should be
* used in place of the HTML in the original message.</p>
*
* <p>This method loosely mimics the HTML forward/reply behavior of BlackBerry OS 4.5/BIS 2.5, which in turn mimics
* Outlook 2003 (as best I can tell).</p>
*
* @param content Content to examine for HTML insertion points
* @return Insertion points and HTML to use for insertion.
*/
private InsertableHtmlContent findInsertionPoints(final String content) {
InsertableHtmlContent insertable = new InsertableHtmlContent();
// If there is no content, don't bother doing any of the regex dancing.
if (content == null || content.equals("")) {
return insertable;
}
// Search for opening tags.
boolean hasHtmlTag = false;
boolean hasHeadTag = false;
boolean hasBodyTag = false;
// First see if we have an opening HTML tag. If we don't find one, we'll add one later.
Matcher htmlMatcher = FIND_INSERTION_POINT_HTML.matcher(content);
if (htmlMatcher.matches()) {
hasHtmlTag = true;
}
// Look for a HEAD tag. If we're missing a BODY tag, we'll use the close of the HEAD to start our content.
Matcher headMatcher = FIND_INSERTION_POINT_HEAD.matcher(content);
if (headMatcher.matches()) {
hasHeadTag = true;
}
// Look for a BODY tag. This is the ideal place for us to start our content.
Matcher bodyMatcher = FIND_INSERTION_POINT_BODY.matcher(content);
if (bodyMatcher.matches()) {
hasBodyTag = true;
}
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Open: hasHtmlTag:" + hasHtmlTag + " hasHeadTag:" + hasHeadTag + " hasBodyTag:" + hasBodyTag);
}
// Given our inspections, let's figure out where to start our content.
// This is the ideal case -- there's a BODY tag and we insert ourselves just after it.
if (hasBodyTag) {
insertable.setQuotedContent(new StringBuilder(content));
insertable.setHeaderInsertionPoint(bodyMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP));
} else if (hasHeadTag) {
// Now search for a HEAD tag. We can insert after there.
// If BlackBerry sees a HEAD tag, it inserts right after that, so long as there is no BODY tag. It doesn't
// try to add BODY, either. Right or wrong, it seems to work fine.
insertable.setQuotedContent(new StringBuilder(content));
insertable.setHeaderInsertionPoint(headMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP));
} else if (hasHtmlTag) {
// Lastly, check for an HTML tag.
// In this case, it will add a HEAD, but no BODY.
StringBuilder newContent = new StringBuilder(content);
// Insert the HEAD content just after the HTML tag.
newContent.insert(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP), FIND_INSERTION_POINT_HEAD_CONTENT);
insertable.setQuotedContent(newContent);
// The new insertion point is the end of the HTML tag, plus the length of the HEAD content.
insertable.setHeaderInsertionPoint(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP) + FIND_INSERTION_POINT_HEAD_CONTENT.length());
} else {
// If we have none of the above, we probably have a fragment of HTML. Yahoo! and Gmail both do this.
// Again, we add a HEAD, but not BODY.
StringBuilder newContent = new StringBuilder(content);
// Add the HTML and HEAD tags.
newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HEAD_CONTENT);
newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HTML_CONTENT);
// Append the </HTML> tag.
newContent.append(FIND_INSERTION_POINT_HTML_END_CONTENT);
insertable.setQuotedContent(newContent);
insertable.setHeaderInsertionPoint(FIND_INSERTION_POINT_HTML_CONTENT.length() + FIND_INSERTION_POINT_HEAD_CONTENT.length());
}
// Search for closing tags. We have to do this after we deal with opening tags since it may
// have modified the message.
boolean hasHtmlEndTag = false;
boolean hasBodyEndTag = false;
// First see if we have an opening HTML tag. If we don't find one, we'll add one later.
Matcher htmlEndMatcher = FIND_INSERTION_POINT_HTML_END.matcher(insertable.getQuotedContent());
if (htmlEndMatcher.matches()) {
hasHtmlEndTag = true;
}
// Look for a BODY tag. This is the ideal place for us to place our footer.
Matcher bodyEndMatcher = FIND_INSERTION_POINT_BODY_END.matcher(insertable.getQuotedContent());
if (bodyEndMatcher.matches()) {
hasBodyEndTag = true;
}
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Close: hasHtmlEndTag:" + hasHtmlEndTag + " hasBodyEndTag:" + hasBodyEndTag);
}
// Now figure out where to put our footer.
// This is the ideal case -- there's a BODY tag and we insert ourselves just before it.
if (hasBodyEndTag) {
insertable.setFooterInsertionPoint(bodyEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP));
} else if (hasHtmlEndTag) {
// Check for an HTML tag. Add ourselves just before it.
insertable.setFooterInsertionPoint(htmlEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP));
} else {
// If we have none of the above, we probably have a fragment of HTML.
// Set our footer insertion point as the end of the string.
insertable.setFooterInsertionPoint(insertable.getQuotedContent().length());
}
return insertable;
}
class Listener extends MessagingListener {
@Override
public void loadMessageForViewStarted(Account account, String folder, String uid) {
if ((mMessageReference == null) || !mMessageReference.getUid().equals(uid)) {
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_ON);
}
@Override
public void loadMessageForViewFinished(Account account, String folder, String uid, LocalMessage message) {
if ((mMessageReference == null) || !mMessageReference.getUid().equals(uid)) {
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_OFF);
}
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, final Message message) {
if ((mMessageReference == null) || !mMessageReference.getUid().equals(uid)) {
return;
}
mSourceMessage = message;
runOnUiThread(new Runnable() {
@Override
public void run() {
// We check to see if we've previously processed the source message since this
// could be called when switching from HTML to text replies. If that happens, we
// only want to update the UI with quoted text (which picks the appropriate
// part).
if (mSourceProcessed) {
try {
populateUIWithQuotedMessage(true);
} catch (MessagingException e) {
// Hm, if we couldn't populate the UI after source reprocessing, let's just delete it?
showOrHideQuotedText(QuotedTextMode.HIDE);
Log.e(K9.LOG_TAG, "Could not re-process source message; deleting quoted text to be safe.", e);
}
updateMessageFormat();
} else {
processSourceMessage((LocalMessage) message);
mSourceProcessed = true;
}
}
});
}
@Override
public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) {
if ((mMessageReference == null) || !mMessageReference.getUid().equals(uid)) {
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_OFF);
// TODO show network error
}
@Override
public void messageUidChanged(Account account, String folder, String oldUid, String newUid) {
// Track UID changes of the source message
if (mMessageReference != null) {
final Account sourceAccount = Preferences.getPreferences(MessageCompose.this).getAccount(mMessageReference.getAccountUuid());
final String sourceFolder = mMessageReference.getFolderName();
final String sourceMessageUid = mMessageReference.getUid();
if (account.equals(sourceAccount) && (folder.equals(sourceFolder))) {
if (oldUid.equals(sourceMessageUid)) {
mMessageReference = mMessageReference.withModifiedUid(newUid);
}
if ((mSourceMessage != null) && (oldUid.equals(mSourceMessage.getUid()))) {
mSourceMessage.setUid(newUid);
}
}
}
}
}
/**
* When we are launched with an intent that includes a mailto: URI, we can actually
* gather quite a few of our message fields from it.
*
* @param mailtoUri
* The mailto: URI we use to initialize the message fields.
*/
private void initializeFromMailto(Uri mailtoUri) {
String schemaSpecific = mailtoUri.getSchemeSpecificPart();
int end = schemaSpecific.indexOf('?');
if (end == -1) {
end = schemaSpecific.length();
}
// Extract the recipient's email address from the mailto URI if there's one.
String recipient = Uri.decode(schemaSpecific.substring(0, end));
/*
* mailto URIs are not hierarchical. So calling getQueryParameters()
* will throw an UnsupportedOperationException. We avoid this by
* creating a new hierarchical dummy Uri object with the query
* parameters of the original URI.
*/
CaseInsensitiveParamWrapper uri = new CaseInsensitiveParamWrapper(
Uri.parse("foo://bar?" + mailtoUri.getEncodedQuery()));
// Read additional recipients from the "to" parameter.
List<String> to = uri.getQueryParameters("to");
if (recipient.length() != 0) {
to = new ArrayList<String>(to);
to.add(0, recipient);
}
mToView.addRecipients(to);
// Read carbon copy recipients from the "cc" parameter.
boolean ccOrBcc = mCcView.addRecipients(uri.getQueryParameters("cc"));
// Read blind carbon copy recipients from the "bcc" parameter.
ccOrBcc |= mBccView.addRecipients(uri.getQueryParameters("bcc"));
if (ccOrBcc) {
// Display CC and BCC text fields if CC or BCC recipients were set by the intent.
onAddCcBcc();
}
// Read subject from the "subject" parameter.
List<String> subject = uri.getQueryParameters("subject");
if (!subject.isEmpty()) {
mSubjectView.setText(subject.get(0));
}
// Read message body from the "body" parameter.
List<String> body = uri.getQueryParameters("body");
if (!body.isEmpty()) {
mMessageContentView.setCharacters(body.get(0));
}
}
private static class CaseInsensitiveParamWrapper {
private final Uri uri;
private Set<String> mParamNames;
public CaseInsensitiveParamWrapper(Uri uri) {
this.uri = uri;
}
public List<String> getQueryParameters(String key) {
final List<String> params = new ArrayList<String>();
for (String paramName : uri.getQueryParameterNames()) {
if (paramName.equalsIgnoreCase(key)) {
params.addAll(uri.getQueryParameters(paramName));
}
}
return params;
}
}
private class SendMessageTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
/*
* Create the message from all the data the user has entered.
*/
MimeMessage message;
try {
if(currentMessage == null) {
message = createMessage();
} else {
message = currentMessage;
}
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me);
throw new RuntimeException("Failed to create a new message for send or save.", me);
}
try {
mContacts.markAsContacted(message.getRecipients(RecipientType.TO));
mContacts.markAsContacted(message.getRecipients(RecipientType.CC));
mContacts.markAsContacted(message.getRecipients(RecipientType.BCC));
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e);
}
MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null);
long draftId = mDraftId;
if (draftId != INVALID_DRAFT_ID) {
mDraftId = INVALID_DRAFT_ID;
MessagingController.getInstance(getApplication()).deleteDraft(mAccount, draftId);
}
return null;
}
}
private class SaveMessageTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
/*
* Create the message from all the data the user has entered.
*/
MimeMessage message;
try {
message = createDraftMessage();
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me);
throw new RuntimeException("Failed to create a new message for send or save.", me);
}
/*
* Save a draft
*/
if (mAction == Action.EDIT_DRAFT) {
/*
* We're saving a previously saved draft, so update the new message's uid
* to the old message's uid.
*/
if (mMessageReference != null) {
message.setUid(mMessageReference.getUid());
}
}
final MessagingController messagingController = MessagingController.getInstance(getApplication());
Message draftMessage = messagingController.saveDraft(mAccount, message, mDraftId);
mDraftId = messagingController.getId(draftMessage);
mHandler.sendEmptyMessage(MSG_SAVED_DRAFT);
return null;
}
}
private static final int REPLY_WRAP_LINE_WIDTH = 72;
private static final int QUOTE_BUFFER_LENGTH = 512; // amount of extra buffer to allocate to accommodate quoting headers or prefixes
/**
* Add quoting markup to a text message.
* @param originalMessage Metadata for message being quoted.
* @param messageBody Text of the message to be quoted.
* @param quoteStyle Style of quoting.
* @return Quoted text.
* @throws MessagingException
*/
private String quoteOriginalTextMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException {
String body = messageBody == null ? "" : messageBody;
String sentDate = getSentDateText(originalMessage);
if (quoteStyle == QuoteStyle.PREFIX) {
StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH);
if (sentDate.length() != 0) {
quotedText.append(String.format(
getString(R.string.message_compose_reply_header_fmt_with_date) + "\r\n",
sentDate,
Address.toString(originalMessage.getFrom())));
} else {
quotedText.append(String.format(
getString(R.string.message_compose_reply_header_fmt) + "\r\n",
Address.toString(originalMessage.getFrom()))
);
}
final String prefix = mAccount.getQuotePrefix();
final String wrappedText = Utility.wrap(body, REPLY_WRAP_LINE_WIDTH - prefix.length());
// "$" and "\" in the quote prefix have to be escaped for
// the replaceAll() invocation.
final String escapedPrefix = prefix.replaceAll("(\\\\|\\$)", "\\\\$1");
quotedText.append(wrappedText.replaceAll("(?m)^", escapedPrefix));
return quotedText.toString().replaceAll("\\\r", "");
} else if (quoteStyle == QuoteStyle.HEADER) {
StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH);
quotedText.append("\r\n");
quotedText.append(getString(R.string.message_compose_quote_header_separator)).append("\r\n");
if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) {
quotedText.append(getString(R.string.message_compose_quote_header_from)).append(" ").append(Address.toString(originalMessage.getFrom())).append("\r\n");
}
if (sentDate.length() != 0) {
quotedText.append(getString(R.string.message_compose_quote_header_send_date)).append(" ").append(sentDate).append("\r\n");
}
if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) {
quotedText.append(getString(R.string.message_compose_quote_header_to)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.TO))).append("\r\n");
}
if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) {
quotedText.append(getString(R.string.message_compose_quote_header_cc)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.CC))).append("\r\n");
}
if (originalMessage.getSubject() != null) {
quotedText.append(getString(R.string.message_compose_quote_header_subject)).append(" ").append(originalMessage.getSubject()).append("\r\n");
}
quotedText.append("\r\n");
quotedText.append(body);
return quotedText.toString();
} else {
// Shouldn't ever happen.
return body;
}
}
/**
* Add quoting markup to a HTML message.
* @param originalMessage Metadata for message being quoted.
* @param messageBody Text of the message to be quoted.
* @param quoteStyle Style of quoting.
* @return Modified insertable message.
* @throws MessagingException
*/
private InsertableHtmlContent quoteOriginalHtmlMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException {
InsertableHtmlContent insertable = findInsertionPoints(messageBody);
String sentDate = getSentDateText(originalMessage);
if (quoteStyle == QuoteStyle.PREFIX) {
StringBuilder header = new StringBuilder(QUOTE_BUFFER_LENGTH);
header.append("<div class=\"gmail_quote\">");
if (sentDate.length() != 0) {
header.append(HtmlConverter.textToHtmlFragment(String.format(
getString(R.string.message_compose_reply_header_fmt_with_date),
sentDate,
Address.toString(originalMessage.getFrom()))
));
} else {
header.append(HtmlConverter.textToHtmlFragment(String.format(
getString(R.string.message_compose_reply_header_fmt),
Address.toString(originalMessage.getFrom()))
));
}
header.append("<blockquote class=\"gmail_quote\" " +
"style=\"margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\">\r\n");
String footer = "</blockquote></div>";
insertable.insertIntoQuotedHeader(header.toString());
insertable.insertIntoQuotedFooter(footer);
} else if (quoteStyle == QuoteStyle.HEADER) {
StringBuilder header = new StringBuilder();
header.append("<div style='font-size:10.0pt;font-family:\"Tahoma\",\"sans-serif\";padding:3.0pt 0in 0in 0in'>\r\n");
header.append("<hr style='border:none;border-top:solid #E1E1E1 1.0pt'>\r\n"); // This gets converted into a horizontal line during html to text conversion.
if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_from)).append("</b> ")
.append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getFrom())))
.append("<br>\r\n");
}
if (sentDate.length() != 0) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_send_date)).append("</b> ")
.append(sentDate)
.append("<br>\r\n");
}
if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_to)).append("</b> ")
.append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getRecipients(RecipientType.TO))))
.append("<br>\r\n");
}
if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_cc)).append("</b> ")
.append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getRecipients(RecipientType.CC))))
.append("<br>\r\n");
}
if (originalMessage.getSubject() != null) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_subject)).append("</b> ")
.append(HtmlConverter.textToHtmlFragment(originalMessage.getSubject()))
.append("<br>\r\n");
}
header.append("</div>\r\n");
header.append("<br>\r\n");
insertable.insertIntoQuotedHeader(header.toString());
}
return insertable;
}
private void setMessageFormat(SimpleMessageFormat format) {
// This method will later be used to enable/disable the rich text editing mode.
mMessageFormat = format;
}
private void updateMessageFormat() {
MessageFormat origMessageFormat = mAccount.getMessageFormat();
SimpleMessageFormat messageFormat;
if (origMessageFormat == MessageFormat.TEXT) {
// The user wants to send text/plain messages. We don't override that choice under
// any circumstances.
messageFormat = SimpleMessageFormat.TEXT;
} else if (mForcePlainText && includeQuotedText()) {
// Right now we send a text/plain-only message when the quoted text was edited, no
// matter what the user selected for the message format.
messageFormat = SimpleMessageFormat.TEXT;
} else if (shouldEncrypt() || shouldSign()) {
// Right now we only support PGP inline which doesn't play well with HTML. So force
// plain text in those cases.
messageFormat = SimpleMessageFormat.TEXT;
} else if (origMessageFormat == MessageFormat.AUTO) {
if (mAction == Action.COMPOSE || mQuotedTextFormat == SimpleMessageFormat.TEXT ||
!includeQuotedText()) {
// If the message format is set to "AUTO" we use text/plain whenever possible. That
// is, when composing new messages and replying to or forwarding text/plain
// messages.
messageFormat = SimpleMessageFormat.TEXT;
} else {
messageFormat = SimpleMessageFormat.HTML;
}
} else {
// In all other cases use HTML
messageFormat = SimpleMessageFormat.HTML;
}
setMessageFormat(messageFormat);
}
private boolean includeQuotedText() {
return (mQuotedTextMode == QuotedTextMode.SHOW);
}
/**
* Extract the date from a message and convert it into a locale-specific
* date string suitable for use in a header for a quoted message.
*
* @param message
* @return A string with the formatted date/time
*/
private String getSentDateText(Message message) {
try {
final int dateStyle = DateFormat.LONG;
final int timeStyle = DateFormat.LONG;
Date date = message.getSentDate();
Locale locale = getResources().getConfiguration().locale;
return DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale)
.format(date);
} catch (Exception e) {
return "";
}
}
private boolean isCryptoProviderEnabled() {
return mOpenPgpProvider != null || mSmimeProvider != null;
}
private boolean shouldEncrypt() {
return isCryptoProviderEnabled() && mEncryptCheckbox.isChecked();
}
private boolean shouldSign() {
return isCryptoProviderEnabled() && mCryptoSignatureCheckbox.isChecked();
}
class DoLaunchOnClickListener implements View.OnClickListener {
private final int resultId;
DoLaunchOnClickListener(int resultId) {
this.resultId = resultId;
}
@Override
public void onClick(View v) {
mIgnoreOnPause = true;
startActivityForResult(mContacts.contactPickerIntent(), resultId);
}
}
protected void setMessage(MimeMessage message) {
if(message != null) {
currentMessage = message;
}
}
public LinearLayout getAttachments() {
return mAttachments;
}
}
|
923d54ec320f90ff4d7d0e3c66d98b6ec3983f6e | 2,712 | java | Java | app/src/main/java/com/greatape/avrkbapp/objects/FloorObject.java | SteveGreatApe/AvrKeyboard | 4392bacca3cf332aab8f39865a0671498df8145c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/greatape/avrkbapp/objects/FloorObject.java | SteveGreatApe/AvrKeyboard | 4392bacca3cf332aab8f39865a0671498df8145c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/greatape/avrkbapp/objects/FloorObject.java | SteveGreatApe/AvrKeyboard | 4392bacca3cf332aab8f39865a0671498df8145c | [
"Apache-2.0"
] | null | null | null | 35.220779 | 143 | 0.698009 | 1,000,276 | /* Copyright 2017 Great Ape Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.greatape.avrkbapp.objects;
import android.view.MotionEvent;
import org.gearvrf.GVRAndroidResource;
import org.gearvrf.GVRContext;
import org.gearvrf.GVRMeshCollider;
import org.gearvrf.GVRRenderData;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.GVRTexture;
import org.gearvrf.ITouchEvents;
import java.io.IOException;
/**
* @author Steve Townsend
*/
public class FloorObject extends ObjectBase implements ITouchEvents {
private int mFloorIndex;
private String[] mFloorTextureAssets;
public FloorObject(GVRContext gvrContext, float floorSize, String[] textureAssets) {
super();
mFloorTextureAssets = textureAssets;
mSceneObject = new GVRSceneObject(gvrContext, floorSize, floorSize);
GVRRenderData renderData = mSceneObject.getRenderData();
renderData.setRenderingOrder(GVRRenderData.GVRRenderingOrder.BACKGROUND + 10);
setFloorTexture();
mSceneObject.getEventReceiver().addListener(this);
mSceneObject.attachCollider(new GVRMeshCollider(gvrContext, true));
}
@Override
public void onTouch(GVRSceneObject sceneObject, MotionEvent motionEvent, float[] hitLocation) {
final int action = motionEvent.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
cycleFloor();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_OUTSIDE:
break;
}
}
private void cycleFloor() {
mFloorIndex = (mFloorIndex + 1) % mFloorTextureAssets.length;
setFloorTexture();
}
private void setFloorTexture() {
try {
GVRContext gvrContext = mSceneObject.getGVRContext();
GVRTexture texture = gvrContext.getAssetLoader().loadTexture(new GVRAndroidResource(gvrContext, mFloorTextureAssets[mFloorIndex]));
mSceneObject.getRenderData().getMaterial().setMainTexture(texture);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
923d555d01db029536188334325d45c422e74178 | 7,860 | java | Java | LisandroChichi/Topic5-MongoDB/src/main/java/database/MainHighSchool.java | justomiguel/java-bootcamp-2016 | e84269b40bb46e8d10149256ec0ead2e9a933a93 | [
"Apache-2.0"
] | 1 | 2016-07-11T20:48:03.000Z | 2016-07-11T20:48:03.000Z | LisandroChichi/Topic5-MongoDB/src/main/java/database/MainHighSchool.java | justomiguel/java-bootcamp-2016 | e84269b40bb46e8d10149256ec0ead2e9a933a93 | [
"Apache-2.0"
] | 33 | 2016-02-24T14:38:21.000Z | 2016-03-11T01:27:24.000Z | LisandroChichi/Topic5-MongoDB/src/main/java/database/MainHighSchool.java | justomiguel/java-bootcamp-2016 | e84269b40bb46e8d10149256ec0ead2e9a933a93 | [
"Apache-2.0"
] | 3 | 2016-02-23T11:06:53.000Z | 2016-06-02T00:54:13.000Z | 36.55814 | 75 | 0.693257 | 1,000,277 | package database;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
public class MainHighSchool {
public static void main(String[] args) throws UnknownHostException,
MongoException {
// TODO Auto-generated method stub
String dbName = new String("highSchool");
Morphia morphia = new Morphia();
morphia.mapPackage("org.mongodb.morphia.example");
Datastore data = morphia.createDatastore(new MongoClient(), dbName);
final Teacher teacherJava = new Teacher("Lisandro", "Chichi",
"11/01/1980");
final Teacher teacherPHP = new Teacher("Carlos", "Penzo", "14/02/1981");
final Teacher teacherNET = new Teacher("Seba", "Lopez", "14/05/1986");
// Course Schedule
final CourseSchedule courseSchedule = new CourseSchedule("Monday",
"09:00 - 11:00");
final CourseSchedule courseSchedule1 = new CourseSchedule("Monday",
"15:00 - 17:30");
final CourseSchedule courseSchedule2 = new CourseSchedule("Friday",
"10:00 - 14:00");
final CourseSchedule courseSchedule3 = new CourseSchedule("Tuesday",
"19:00 - 21:00");
final CourseSchedule courseSchedule4 = new CourseSchedule("Wednesday",
"09:00 - 13:00");
final CourseSchedule courseSchedule5 = new CourseSchedule("Friday",
"12:00 - 15:30");
final CourseSchedule courseSchedule6 = new CourseSchedule("Thursday",
"14:00 - 18:00");
final CourseSchedule courseSchedule7 = new CourseSchedule("Friday",
"09:30 - 12:30");
ArrayList<CourseSchedule> scheduleJava = new ArrayList<CourseSchedule>();
ArrayList<CourseSchedule> schedulePHP = new ArrayList<CourseSchedule>();
ArrayList<CourseSchedule> scheduleNET = new ArrayList<CourseSchedule>();
// schedule for the course Java
scheduleJava.add(courseSchedule);
scheduleJava.add(courseSchedule1);
scheduleJava.add(courseSchedule2);
// schedule for the course PHP
schedulePHP.add(courseSchedule3);
schedulePHP.add(courseSchedule4);
schedulePHP.add(courseSchedule5);
// schedule for the course .NET
scheduleNET.add(courseSchedule6);
scheduleNET.add(courseSchedule7);
// COURSES
final Course courseJava = new Course("Java", 12, scheduleJava,
teacherJava);
final Course coursePHP = new Course("PHP", 12, schedulePHP, teacherPHP);
final Course courseNET = new Course(".NET", 12, scheduleNET, teacherNET);
final Student student = new Student("Juan", "Perez", 34564,
"15/03/1990");
final Student student1 = new Student("alberto", "lopez", 43570,
"1991-12-11");
final Student student2 = new Student("julian", "ramirez", 42579,
"1992-01-01");
final Student student3 = new Student("santiago", "gutierrez", 23579,
"1990-07-01");
final Student student4 = new Student("rodolfo", "beron", 43379,
"1990-04-21");
final Student student5 = new Student("antonieto", "cristaldo", 1579,
"1990-06-11");
final Student student6 = new Student("ramiro", "dutti", 4319,
"1990-01-15");
final Student student7 = new Student("sergio", "hermida", 4353,
"1990-03-01");
final Student student8 = new Student("rodrigo", "fages", 43456,
"1990-03-21");
final Student student9 = new Student("jose", "jerez", 43079,
"1990-08-12");
final Student student10 = new Student("carlos", "llano", 41179,
"1990-08-14");
final Student student11 = new Student("juan", "martin", 43569,
"1990-10-03");
final Student student12 = new Student("antonio", "nieves", 44089,
"1990-09-01");
final Student student13 = new Student("pepe", "ortega", 41119,
"1990-02-21");
final Student student14 = new Student("miranda", "palacios", 4279,
"1990-11-11");
final Student student15 = new Student("agostina", "donatto", 43544,
"1990-10-01");
final Student student16 = new Student("agustin", "martinez", 49863,
"1990-12-12");
final Student student17 = new Student("maria", "bou", 54645,
"1990-12-24");
final Student student18 = new Student("antonella", "alario", 34234,
"1990-01-25");
final Student student19 = new Student("luis", "illia", 45679,
"1990-09-01");
final StudentNotes notes1 = new StudentNotes(7, 7, 8, 7, courseJava,
student);
final StudentNotes notes2 = new StudentNotes(8, 8, 8, 8, coursePHP,
student1);
final StudentNotes notes3 = new StudentNotes(6, 7, 8, 7, courseNET,
student2);
final StudentNotes notes4 = new StudentNotes(4, 3, 3, 3, courseJava,
student3);
final StudentNotes notes5 = new StudentNotes(5, 8, 9, 7, coursePHP,
student3);
final StudentNotes notes6 = new StudentNotes(10, 8, 8, 9, courseJava,
student4);
final StudentNotes notes7 = new StudentNotes(7, 10, 9, 9, coursePHP,
student4);
final StudentNotes notes8 = new StudentNotes(9, 9, 9, 9, courseNET,
student5);
final StudentNotes notes9 = new StudentNotes(8, 6, 6, 7, courseJava,
student5);
final StudentNotes notes10 = new StudentNotes(3, 5, 8, 5, coursePHP,
student5);
final StudentNotes notes11 = new StudentNotes(7, 7, 8, 7, courseJava,
student6);
final StudentNotes notes12 = new StudentNotes(8, 8, 8, 8, coursePHP,
student6);
final StudentNotes notes13 = new StudentNotes(6, 7, 8, 7, courseNET,
student7);
final StudentNotes notes14 = new StudentNotes(4, 3, 3, 3, courseJava,
student8);
final StudentNotes notes15 = new StudentNotes(5, 8, 9, 7, coursePHP,
student9);
final StudentNotes notes16 = new StudentNotes(10, 8, 8, 9, courseJava,
student10);
final StudentNotes notes17 = new StudentNotes(7, 10, 9, 9, coursePHP,
student10);
final StudentNotes notes18 = new StudentNotes(9, 9, 9, 9, courseNET,
student11);
final StudentNotes notes19 = new StudentNotes(8, 6, 6, 7, courseJava,
student12);
final StudentNotes notes20 = new StudentNotes(3, 5, 4, 4, coursePHP,
student12);
final StudentNotes notes21 = new StudentNotes(7, 7, 3, 6, courseJava,
student13);
final StudentNotes notes22 = new StudentNotes(8, 8, 8, 8, coursePHP,
student14);
final StudentNotes notes23 = new StudentNotes(6, 7, 8, 7, courseNET,
student14);
final StudentNotes notes24 = new StudentNotes(4, 3, 3, 3, courseJava,
student14);
final StudentNotes notes25 = new StudentNotes(5, 8, 9, 7, coursePHP,
student15);
final StudentNotes notes26 = new StudentNotes(4, 4, 5, 4, courseJava,
student16);
final StudentNotes notes27 = new StudentNotes(3, 3, 3, 3, coursePHP,
student16);
final StudentNotes notes28 = new StudentNotes(9, 9, 9, 9, courseNET,
student17);
final StudentNotes notes29 = new StudentNotes(8, 6, 6, 7, courseJava,
student18);
final StudentNotes notes30 = new StudentNotes(3, 5, 8, 5, coursePHP,
student19);
data.save(notes1);
data.save(notes2);
data.save(notes3);
data.save(notes4);
data.save(notes5);
data.save(notes6);
data.save(notes7);
data.save(notes8);
data.save(notes9);
data.save(notes10);
data.save(notes11);
data.save(notes12);
data.save(notes13);
data.save(notes14);
data.save(notes15);
data.save(notes16);
data.save(notes17);
data.save(notes18);
data.save(notes19);
data.save(notes20);
data.save(notes21);
data.save(notes22);
data.save(notes23);
data.save(notes24);
data.save(notes25);
data.save(notes26);
data.save(notes27);
data.save(notes28);
data.save(notes29);
data.save(notes30);
List<StudentNotes> asList = data.createQuery(StudentNotes.class)
.field("finalNote").greaterThan(4).asList();
System.out.println("Estudiantes que aprobaron su curso: \n");
for (int i = 0; i < asList.size(); i++) {
System.out.println(i + "-" + " "
+ asList.get(i).getStudent().getFirstName() + " Curso: "
+ asList.get(i).getCourse().getCourseName());
}
}
}
|
923d55746621a111742fe957af067207779a03c6 | 26,805 | java | Java | src/test/java/uk/gov/hmcts/reform/sscs/service/DwpAddressLookupServiceTest.java | hmcts/sscs-common | e03bb9ed638e366ca7f37aaa5ed9561ba80d5c7f | [
"MIT"
] | 2 | 2018-08-31T14:00:27.000Z | 2018-08-31T14:00:28.000Z | src/test/java/uk/gov/hmcts/reform/sscs/service/DwpAddressLookupServiceTest.java | hmcts/sscs-common | e03bb9ed638e366ca7f37aaa5ed9561ba80d5c7f | [
"MIT"
] | 230 | 2018-10-26T14:20:58.000Z | 2022-03-31T17:01:59.000Z | src/test/java/uk/gov/hmcts/reform/sscs/service/DwpAddressLookupServiceTest.java | hmcts/sscs-common | e03bb9ed638e366ca7f37aaa5ed9561ba80d5c7f | [
"MIT"
] | 3 | 2019-11-21T14:43:31.000Z | 2021-04-10T22:34:19.000Z | 42.412975 | 237 | 0.718224 | 1,000,278 | package uk.gov.hmcts.reform.sscs.service;
import static java.util.Arrays.stream;
import static org.apache.commons.io.IOUtils.resourceToString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static uk.gov.hmcts.reform.sscs.ccd.util.CaseDataUtils.buildCaseData;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import uk.gov.hmcts.reform.sscs.ccd.domain.*;
import uk.gov.hmcts.reform.sscs.exception.DwpAddressLookupException;
import uk.gov.hmcts.reform.sscs.exception.NoMrnDetailsException;
import uk.gov.hmcts.reform.sscs.model.dwp.OfficeMapping;
@RunWith(JUnitParamsRunner.class)
public class DwpAddressLookupServiceTest {
private final DwpAddressLookupService dwpAddressLookup = new DwpAddressLookupService();
private SscsCaseData caseData;
@Before
public void setup() {
caseData = buildCaseData();
}
@Test
public void dwpLookupAddressShouldBeHandled() {
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertEquals("Mail Handling Site A", address.getLine1());
assertEquals("WOLVERHAMPTON", address.getTown());
assertEquals("WV98 1AA", address.getPostcode());
}
@Test
@Parameters({"1", "2", "3", "4", "5", "6", "7", "8", "9", "(AE)"})
public void pipAddressesExist(final String dwpIssuingOffice) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("PIP").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice(dwpIssuingOffice).build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
}
@Test
@Parameters({"PIP (3)", " PIP 3 ", "PIP 3", "DWP PIP (3)", "(AE)", "AE", "PIP AE", "DWP PIP (AE)", "Recovery from Estates", "PIP Recovery from Estates"})
public void pipFuzzyMatchingAddressesExist(final String dwpIssuingOffice) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("PIP").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice(dwpIssuingOffice).build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
}
@Test
@Parameters({
"PIP, 1", "pip, 1", "PiP, 1", "pIP, 1",
"ESA, Balham DRT", "EsA, Balham DRT", "esa, Balham DRT"
})
public void benefitTypeIsCaseInsensitive(final String benefitType, String dwpIssuingOffice) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code(benefitType).build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice(dwpIssuingOffice).build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
}
@Test
public void dwpOfficeStripsText() {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("PIP").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice("DWP Issuing Office(9)").build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
}
@Test
public void handleCaseInsensitiveAddresses() {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("ESA").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice("BALHAM DRT").build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
}
@Test
@Parameters({
"Balham DRT", "Birkenhead LM DRT", "Lowestoft DRT", "Wellingborough DRT", "Chesterfield DRT",
"Coatbridge Benefit Centre", "Inverness DRT", "Milton Keynes DRT", "Springburn DRT", "Watford DRT",
"Norwich DRT", "Sheffield DRT", "Worthing DRT"
})
public void esaAddressesExist(final String dwpIssuingOffice) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("ESA").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice(dwpIssuingOffice).build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
}
@Test
@Parameters({
"Disability Benefit Centre 4", "The Pension Service 11", "Recovery from Estates"
})
public void dlaAddressesExist(final String dwpIssuingOffice) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("DLA").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice(dwpIssuingOffice).build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
}
@Test
@Parameters({"The Pension Service 11", "Recovery from Estates"})
public void attendanceAllowanceAddressesExist(final String dwpIssuingOffice) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("DLA").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice(dwpIssuingOffice).build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
}
@Test(expected = DwpAddressLookupException.class)
@Parameters({"JOB", "UNK", "PLOP", "BIG", "FIG"})
public void unknownBenefitTypeReturnsNone(final String benefitType) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code(benefitType).build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice("1").build()).build()).build();
dwpAddressLookup.lookupDwpAddress(caseData);
}
@Test(expected = DwpAddressLookupException.class)
@Parameters({"11", "12", "13", "14", "JOB"})
public void unknownPipDwpIssuingOfficeReturnsNone(final String dwpIssuingOffice) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("PIP").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice(dwpIssuingOffice).build()).build()).build();
dwpAddressLookup.lookupDwpAddress(caseData);
}
@Test(expected = DwpAddressLookupException.class)
@Parameters({"JOB", "UNK", "PLOP", "BIG", "11"})
public void unknownEsaDwpIssuingOfficeReturnsNone(final String dwpIssuingOffice) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code("ESA").build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice(dwpIssuingOffice).build()).build()).build();
dwpAddressLookup.lookupDwpAddress(caseData);
}
@Test
@Parameters({"PIP", "ESA", "JOB", "UNK", "PLOP", "BIG", "11"})
public void willAlwaysReturnTestAddressForATestDwpIssuingOffice(final String benefitType) {
SscsCaseData caseData = SscsCaseData.builder().appeal(Appeal.builder().benefitType(BenefitType.builder().code(benefitType).build()).mrnDetails(MrnDetails.builder().dwpIssuingOffice("test-hmcts-address").build()).build()).build();
Address address = dwpAddressLookup.lookupDwpAddress(caseData);
assertNotNull(address);
assertEquals("E1 8FA", address.getPostcode());
}
@Test(expected = NoMrnDetailsException.class)
public void asAppealWithNoMrnDetailsWillNotHaveADwpAddress() {
caseData = buildCaseData();
caseData.setRegionalProcessingCenter(null);
caseData = caseData.toBuilder().appeal(caseData.getAppeal().toBuilder().mrnDetails(null).build()).build();
dwpAddressLookup.lookupDwpAddress(caseData);
}
@Test(expected = NoMrnDetailsException.class)
public void anAppealWithNoDwpIssuingOfficeWillNotHaveADwpAddress() {
caseData = buildCaseData();
caseData.setRegionalProcessingCenter(null);
caseData = caseData.toBuilder().appeal(caseData.getAppeal().toBuilder().mrnDetails(
MrnDetails.builder().mrnLateReason("soz").build()).build()).build();
dwpAddressLookup.lookupDwpAddress(caseData);
}
@Test
public void pipOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.pipOfficeMappings();
assertEquals("DWP PIP (1)", result[0].getMapping().getGaps());
assertEquals(11, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void ucOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.ucOfficeMappings();
assertEquals(2, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void bereavementBenefitOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.bereavementBenefitOfficeMappings();
assertEquals(1, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void childSupportOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.childSupportOfficeMappings();
assertEquals(1, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void carersAllowanceOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.carersAllowanceOfficeMappings();
assertEquals(1, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void maternityAllowanceOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.maternityAllowanceOfficeMappings();
assertEquals(1, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void esaOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.esaOfficeMappings();
assertEquals(14, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void jsaOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.jsaOfficeMappings();
assertEquals(4, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void socialFundOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.socialFundOfficeMappings();
assertEquals(3, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void dlaOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.dlaOfficeMappings();
assertEquals(3, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void attendanceAllowanceOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.attendanceAllowanceOfficeMappings();
assertEquals(2, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void incomeSupportOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.incomeSupportOfficeMappings();
assertEquals(4, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void industrialDeathBenefitOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.industrialDeathBenefitOfficeMappings();
assertEquals(2, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void pensionCreditsOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.pensionCreditsOfficeMappings();
assertEquals(2, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
public void retirementPensionOfficeMappings() {
OfficeMapping[] result = dwpAddressLookup.retirementPensionOfficeMappings();
assertEquals(2, result.length);
assertTrue(stream(result).anyMatch(OfficeMapping::isDefault));
}
@Test
@Parameters({
"PIP, 11",
"UC, 2",
"ESA, 14",
"DLA, 3",
"CARERS_ALLOWANCE, 1",
"BEREAVEMENT_BENEFIT, 1",
"ATTENDANCE_ALLOWANCE, 2",
"MATERNITY_ALLOWANCE, 1",
"JSA, 4",
"IIDB, 2",
"SOCIAL_FUND, 3",
"INCOME_SUPPORT, 4",
"BEREAVEMENT_SUPPORT_PAYMENT_SCHEME, 1",
"INDUSTRIAL_DEATH_BENEFIT, 2",
"PENSION_CREDIT, 2",
"RETIREMENT_PENSION, 2",
})
public void getDwpOfficeMappings(Benefit benefit, int expectedNumberOfOffices) {
OfficeMapping[] officeMappings = dwpAddressLookup.getDwpOfficeMappings(benefit.getShortName());
assertEquals(officeMappings.length, expectedNumberOfOffices);
assertTrue(stream(officeMappings).anyMatch(OfficeMapping::isDefault));
}
@Test
@Parameters({"3, 3", "PIP Recovery from Estates, Recovery from Estates"})
public void givenAPipBenefitTypeAndDwpOffice_thenReturnAPipOffice(String office, String expectedResult) {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("pip", office);
assertTrue(result.isPresent());
assertEquals(expectedResult, result.get().getCode());
}
@Test
public void givenAEsaBenefitTypeAndInvalidOffice_thenReturnEmpty() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("esa", "3");
assertEquals(Optional.empty(), result);
}
@Test
@Parameters({"(AE)", "AE", "DWP PIP (AE)"})
public void givenAPipBenefitTypeAndAeOffice_thenFuzzyMatch(String pipAe) {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("pip", pipAe);
assertTrue(result.isPresent());
assertEquals("AE", result.get().getCode());
}
@Test
@Parameters({"Balham DRT, Balham DRT", "ESA Recovery from Estates, Recovery from Estates"})
public void givenAEsaBenefitTypeAndDwpOffice_thenReturnEsaOffice(String office, String expectedResult) {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("esa", office);
assertTrue(result.isPresent());
assertEquals(expectedResult, result.get().getCode());
}
@Test
public void givenAPipBenefitTypeAndInvalidOffice_thenReturnEmpty() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("pip", "Balham DRT");
assertEquals(Optional.empty(), result);
}
@Test
public void givenAUcBenefitType_thenReturnTheUcOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("uc", null);
assertTrue(result.isPresent());
assertEquals("Universal Credit", result.get().getCode());
}
@Test
public void givenAUcBenefitTypeAndDwpOffice_thenCorrectDwpRegionalCenter() {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("uc", null);
assertEquals("Universal Credit", result);
}
@Test
public void givenAUcBenefitTypeAndOffice_thenReturnTheUcOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("uc", "UC Recovery from Estates");
assertEquals("Recovery from Estates", result.get().getCode());
}
@Test
public void givenAnIncomeSupportBenefitTypeAndSheffieldOffice_thenReturnTheRfeOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("incomeSupport", "Recovery from Estates");
assertEquals("Recovery from Estates", result.get().getCode());
}
@Test
public void givenAPipBenefitTypeAndDwpOffice_thenCorrectDwpRegionalCenter() {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("pip", "3");
assertEquals("Bellevale", result);
}
@Test
public void givenAEsaBenefitTypeAndDwpOffice_thenCorrectDwpRegionalCenter() {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("esa", "Balham DRT");
assertEquals("Balham DRT", result);
}
@Test
public void givenAAttendanceAllowanceBenefitTypeAndRfeDwpOffice_thenCorrectDwpRegionalCenter() {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("attendanceAllowance", "Recovery from Estates");
assertEquals("RfE", result);
}
@Test
public void givenAAttendanceAllowanceBenefitTypeAndAaDwpOffice_thenCorrectDwpRegionalCenter() {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("attendanceAllowance", "The Pension Service 11");
assertEquals("Attendance Allowance", result);
}
@Test
public void givenACarersAllowanceBenefitTypeAndDwpOffice_thenCorrectDwpRegionalCenter() {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("carersAllowance", null);
assertEquals("Carers Allowance", result);
}
@Test
public void givenACarersAllowanceBenefitType_thenReturnTheOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("carersAllowance", null);
assertTrue(result.isPresent());
assertEquals("Carer’s Allowance Dispute Resolution Team", result.get().getCode());
}
@Test
public void givenAnAttendanceAllowanceBenefitType_thenReturnTheOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("attendanceAllowance", "Recovery from Estates");
assertTrue(result.isPresent());
assertEquals("Recovery from Estates", result.get().getCode());
}
@Test
public void givenABereavementBenefitTypeAndDwpOffice_thenCorrectDwpRegionalCenter() {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("bereavementBenefit", null);
assertEquals("Bereavement Benefit", result);
}
@Test
public void givenABereavementBenefitType_thenReturnTheOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("bereavementBenefit", null);
assertTrue(result.isPresent());
assertEquals("Pensions Dispute Resolution Team", result.get().getCode());
}
@Test
public void givenAChildSupportTypeAndDwpOffice_thenCorrectDwpRegionalCenter() {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("childSupport", null);
assertEquals("Child Support", result);
}
@Test
public void givenAChildSupportType_thenReturnTheOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("childSupport", null);
assertTrue(result.isPresent());
assertEquals("Child Maintenance Service Group", result.get().getCode());
}
@Test
@Parameters({
"Disability Benefit Centre 4, DLA Child/Adult", "The Pension Service 11, DLA 65", "Recovery from Estates, RfE"
})
public void givenADlaBenefitType_thenReturnTheCorrectDwpRegionalCentre(String office, String dwpRegionalCentre) {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("dla", office);
assertEquals(dwpRegionalCentre, result);
}
@Test
public void givenAMaternityAllowance_thenReturnTheOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("maternityAllowance", null);
assertTrue(result.isPresent());
assertEquals("Walsall Benefit Centre", result.get().getCode());
}
@Test
public void givenABereavementSupportPaymentScheme_thenReturnTheOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("bereavementSupportPaymentScheme", null);
assertTrue(result.isPresent());
assertEquals("Pensions Dispute Resolution Team", result.get().getCode());
}
@Test
public void givenAChildSupport_thenReturnTheOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("childSupport", null);
assertTrue(result.isPresent());
assertEquals("Child Maintenance Service Group", result.get().getCode());
}
@Test
@Parameters({
"Barrow IIDB Centre, IIDB Barrow", "Barnsley Benefit Centre, IIDB Barnsley"
})
public void givenAIidbBenefitType_thenReturnTheCorrectDwpRegionalCentre(String office, String dwpRegionalCentre) {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("industrialInjuriesDisablement", office);
assertEquals(dwpRegionalCentre, result);
}
@Test
@Parameters({
"Barrow IIDB Centre, IDB Barrow", "Barnsley Benefit Centre, IDB Barnsley"
})
public void givenAIndustrialDeathBenefitType_thenReturnTheCorrectDwpRegionalCentre(String office, String dwpRegionalCentre) {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("industrialDeathBenefit", office);
assertEquals(dwpRegionalCentre, result);
}
@Test
@Parameters({
"Pensions Dispute Resolution Team, Pension Credit", "Recovery from Estates, RfE"
})
public void givenAPensionCreditsBenefitType_thenReturnTheCorrectDwpRegionalCentre(String office, String dwpRegionalCentre) {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("pensionCredit", office);
assertEquals(dwpRegionalCentre, result);
}
@Test
@Parameters({
"Pensions Dispute Resolution Team, Retirement Pension", "Recovery from Estates, RfE"
})
public void givenARetirementPensionBenefitType_thenReturnTheCorrectDwpRegionalCentre(String office, String dwpRegionalCentre) {
String result = dwpAddressLookup.getDwpRegionalCenterByBenefitTypeAndOffice("retirementPension", office);
assertEquals(dwpRegionalCentre, result);
}
@Test
public void givenABenefitTypeNotMapped_thenReturnEmptyOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDwpMappingByOffice("hb", null);
assertTrue(result.isEmpty());
}
@Test
public void givenAPipBenefitType_thenReturnTheDefaultPipOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("pip");
assertTrue(result.isPresent());
assertEquals("3", result.get().getCode());
}
@Test
public void givenAEsaBenefitType_thenReturnTheDefaultEsaOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("esa");
assertTrue(result.isPresent());
assertEquals("Sheffield DRT", result.get().getCode());
}
@Test
public void givenAUcBenefitType_thenReturnTheDefaultUcOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("uc");
assertTrue(result.isPresent());
assertEquals("Universal Credit", result.get().getCode());
}
@Test
public void givenAIidbBenefitType_thenReturnTheDefaultIidbOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("industrialInjuriesDisablement");
assertTrue(result.isPresent());
assertEquals("Barrow IIDB Centre", result.get().getCode());
}
@Test
public void givenAMaternityAllowanceBenefitType_thenReturnTheDefaultMaternityAllowanceOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("maternityAllowance");
assertTrue(result.isPresent());
assertEquals("Walsall Benefit Centre", result.get().getCode());
}
@Test
public void givenAnIncomeSupportBenefitType_thenReturnTheDefaultIncomeSupprtOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("incomeSupport");
assertTrue(result.isPresent());
assertEquals("Worthing DRT", result.get().getCode());
}
@Test
public void givenAMaternityAllowanceBenefitType_thenReturnTheDefaultBereavementSupportPaymentSchemeOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("bereavementSupportPaymentScheme");
assertTrue(result.isPresent());
assertEquals("Pensions Dispute Resolution Team", result.get().getCode());
}
@Test
public void givenAMaternityAllowanceBenefitType_thenReturnTheDefaultIndustrialDeathBenefitOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("industrialDeathBenefit");
assertTrue(result.isPresent());
assertEquals("Barrow IIDB Centre", result.get().getCode());
}
@Test
public void givenAMaternityAllowanceBenefitType_thenReturnTheDefaultPensionCreditsOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("pensionCredit");
assertTrue(result.isPresent());
assertEquals("Pensions Dispute Resolution Team", result.get().getCode());
}
@Test
public void givenAMaternityAllowanceBenefitType_thenReturnTheDefaultRetirementPensionOffice() {
Optional<OfficeMapping> result = dwpAddressLookup.getDefaultDwpMappingByBenefitType("retirementPension");
assertTrue(result.isPresent());
assertEquals("Pensions Dispute Resolution Team", result.get().getCode());
}
@Test
public void allDwpMappingsHaveADwpRegionCentre() {
stream(Benefit.values())
.flatMap(benefit -> stream(benefit.getOfficeMappings().apply(dwpAddressLookup)))
.forEach(f -> assertNotNull(f.getMapping().getDwpRegionCentre()));
}
@Test
public void isValidJsonWithNoDuplicateValues() throws Exception {
String json = resourceToString("reference-data/dwpAddresses.json",
StandardCharsets.UTF_8, Thread.currentThread().getContextClassLoader());
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
final JsonNode tree = mapper.readTree(json);
assertThat(tree, is(notNullValue()));
}
}
|
923d55cd3791ce404506adeeb348f8325ad4729d | 1,493 | java | Java | src/main/java/com/example/orders/models/Order.java | nchen0/java-orders | 785c820f69fd5db5f70dfd079d308caf645e9f47 | [
"MIT"
] | null | null | null | src/main/java/com/example/orders/models/Order.java | nchen0/java-orders | 785c820f69fd5db5f70dfd079d308caf645e9f47 | [
"MIT"
] | null | null | null | src/main/java/com/example/orders/models/Order.java | nchen0/java-orders | 785c820f69fd5db5f70dfd079d308caf645e9f47 | [
"MIT"
] | null | null | null | 19.141026 | 58 | 0.650368 | 1,000,279 | package com.example.orders.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
@Entity
@Table(name="orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private long ordnum;
private double ordamount;
private double advanceamount;
@ManyToOne
@JoinColumn(name="custcode")
@JsonIgnore
private Customer customer;
@ManyToOne
@JoinColumn(name="agentcode")
@JsonIgnore
private Agent agent;
private String orddescription;
public Order() {
}
public double getOrdamount() {
return ordamount;
}
public void setOrdamount(double ordamount) {
this.ordamount = ordamount;
}
public double getAdvanceamount() {
return advanceamount;
}
public void setAdvanceamount(double advanceamount) {
this.advanceamount = advanceamount;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Agent getAgent() {
return agent;
}
public void setAgent(Agent agent) {
this.agent = agent;
}
public String getOrddescription() {
return orddescription;
}
public void setOrddescription(String orddescription) {
this.orddescription = orddescription;
}
public long getOrdnum() {
return ordnum;
}
}
|
923d567448b546006c6cf889fd0f78c85c631ab6 | 3,189 | java | Java | src/main/java/net/cartola/emissorfiscal/security/config/JwtTokenUtil.java | robsonhenriq/emissor-fiscal | d0a8d0da1ca91ad7b0016ef8bb19bcbe1dd30818 | [
"MIT"
] | 4 | 2021-08-25T00:39:24.000Z | 2022-02-28T19:46:24.000Z | src/main/java/net/cartola/emissorfiscal/security/config/JwtTokenUtil.java | robsonhenriq/emissor-fiscal | d0a8d0da1ca91ad7b0016ef8bb19bcbe1dd30818 | [
"MIT"
] | null | null | null | src/main/java/net/cartola/emissorfiscal/security/config/JwtTokenUtil.java | robsonhenriq/emissor-fiscal | d0a8d0da1ca91ad7b0016ef8bb19bcbe1dd30818 | [
"MIT"
] | 2 | 2022-02-22T01:00:36.000Z | 2022-02-25T13:49:48.000Z | 34.663043 | 108 | 0.680151 | 1,000,280 | package net.cartola.emissorfiscal.security.config;
import java.io.Serializable;
import java.util.Date;
import java.util.function.Function;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
//import br.com.autogeral.erpj.ws.model.Usuario;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.cartola.emissorfiscal.usuario.Usuario;
/**
* 24 de dez de 2019
* @author robson.costa
*/
@Component
public class JwtTokenUtil implements Serializable {
public static final long ACCESS_TOKEN_VALIDITY_SECONDS = 5*60*60;
public static final String SIGNING_KEY = "devglan123r";
private static final long serialVersionUID = 8078268260082937752L;
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(SIGNING_KEY)
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String generateToken(Usuario user, UserDetails userDetails) {
return doGenerateToken(user.getLogin(), userDetails);
}
// private String doGenerateToken(String subject) {
// Claims claims = Jwts.claims().setSubject(subject);
// claims.put("scopes", Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
//
// return Jwts.builder()
// .setClaims(claims)
// .setIssuer("http://devglan.com")
// .setIssuedAt(new Date(System.currentTimeMillis()))
// .setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_VALIDITY_SECONDS*1000))
// .signWith(SignatureAlgorithm.HS256, SIGNING_KEY)
// .compact();
// }
private String doGenerateToken(String subject, UserDetails userDetails) {
Claims claims = Jwts.claims().setSubject(subject);
claims.put("scopes", userDetails.getAuthorities());
return Jwts.builder()
.setClaims(claims)
.setIssuer("http://devglan.com")
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_VALIDITY_SECONDS*1000))
.signWith(SignatureAlgorithm.HS256, SIGNING_KEY)
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
|
923d5765f4a42b4a8225255e5eabb7e74120f008 | 531 | java | Java | ARDataFramework/src/to/augmented/reality/android/ardb/sourcefacade/annotations/maps/POIs.java | donaldmunro/ARData | 750a737af52e63ce5dc1b57f7b64fa2f757965f3 | [
"Apache-2.0"
] | 1 | 2016-12-13T07:01:26.000Z | 2016-12-13T07:01:26.000Z | ARDataFramework/src/to/augmented/reality/android/ardb/sourcefacade/annotations/maps/POIs.java | donaldmunro/ARData | 750a737af52e63ce5dc1b57f7b64fa2f757965f3 | [
"Apache-2.0"
] | null | null | null | ARDataFramework/src/to/augmented/reality/android/ardb/sourcefacade/annotations/maps/POIs.java | donaldmunro/ARData | 750a737af52e63ce5dc1b57f7b64fa2f757965f3 | [
"Apache-2.0"
] | null | null | null | 35.4 | 91 | 0.774011 | 1,000,281 | package to.augmented.reality.android.ardb.sourcefacade.annotations.maps;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specify a field as containing marked Points of Interest (POIs). The annotated field must
* be a list of POI's (List{@literal <}POI{@literal>}) or array of POIs (POI[]).
*/
@Retention(RetentionPolicy.RUNTIME)
@Target( {ElementType.METHOD, ElementType.FIELD} )
public @interface POIs { }
|
923d5795cdc4d005abf79c3648bc82a6a1d18dad | 67 | java | Java | app/src/main/java/arch/line/base/baseline/utility/Utility.java | thevipin/android-java-baseline | 6aedfd3c9369afeba598fe77f8a7f00c9eec5338 | [
"Apache-2.0"
] | 1 | 2018-07-04T18:33:58.000Z | 2018-07-04T18:33:58.000Z | app/src/main/java/arch/line/base/baseline/utility/Utility.java | thevipin/android-java-baseline | 6aedfd3c9369afeba598fe77f8a7f00c9eec5338 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/arch/line/base/baseline/utility/Utility.java | thevipin/android-java-baseline | 6aedfd3c9369afeba598fe77f8a7f00c9eec5338 | [
"Apache-2.0"
] | null | null | null | 13.4 | 40 | 0.776119 | 1,000,282 | package arch.line.base.baseline.utility;
public class Utility {
}
|
923d580fa631661b5a4bd5438790b4ccd29030f6 | 6,423 | java | Java | src/main/java/com/shenjiahuan/node/MasterClient.java | ShenJiahuan/Sharded-KV | b77d493581ccbb1ed0826b9a146e1be56cdf6448 | [
"Apache-2.0"
] | 9 | 2020-07-03T14:05:01.000Z | 2020-08-01T03:25:34.000Z | src/main/java/com/shenjiahuan/node/MasterClient.java | ShenJiahuan/Sharded-KV | b77d493581ccbb1ed0826b9a146e1be56cdf6448 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/shenjiahuan/node/MasterClient.java | ShenJiahuan/Sharded-KV | b77d493581ccbb1ed0826b9a146e1be56cdf6448 | [
"Apache-2.0"
] | null | null | null | 31.79703 | 100 | 0.592247 | 1,000,283 | package com.shenjiahuan.node;
import com.shenjiahuan.*;
import com.shenjiahuan.util.Pair;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
public class MasterClient {
private final Logger logger = Logger.getLogger(getClass());
private final List<Pair<String, Integer>> masters;
private int leader;
private final long clientId;
private long seqId;
public MasterClient(List<Pair<String, Integer>> masters) {
this.masters = masters;
this.leader = 0;
this.clientId = new Random().nextLong();
this.seqId = 0;
}
public void join(long gid, List<Pair<String, Integer>> slaves) {
while (true) {
final String masterHost = masters.get(leader).getKey();
final Integer masterPort = masters.get(leader).getValue();
ManagedChannel channel =
ManagedChannelBuilder.forAddress(masterHost, masterPort).usePlaintext().build();
MasterServiceGrpc.MasterServiceBlockingStub stub = MasterServiceGrpc.newBlockingStub(channel);
ServerList.Builder builder = ServerList.newBuilder();
for (Pair<String, Integer> slave : slaves) {
final String slaveHost = slave.getKey();
final Integer slavePort = slave.getValue();
builder.addServer(Server.newBuilder().setHost(slaveHost).setPort(slavePort).build());
}
JoinResponse joinResponse;
try {
joinResponse =
stub.join(
JoinRequest.newBuilder()
.setGid(gid)
.setServer(builder.build())
.setClientId(clientId)
.setSeqId(seqId)
.build());
// logger.info("Response received from server:\n" + joinResponse);
} catch (StatusRuntimeException e) {
logger.info("Fail to get response from server");
this.leader = (this.leader + 1) % masters.size();
continue;
} finally {
try {
channel.shutdown().awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (joinResponse.getStatus() == 0) {
seqId++;
return;
} else {
this.leader = (this.leader + 1) % masters.size();
}
}
}
public void leave(long gid) {
while (true) {
final String masterHost = masters.get(leader).getKey();
final Integer masterPort = masters.get(leader).getValue();
ManagedChannel channel =
ManagedChannelBuilder.forAddress(masterHost, masterPort).usePlaintext().build();
MasterServiceGrpc.MasterServiceBlockingStub stub = MasterServiceGrpc.newBlockingStub(channel);
LeaveResponse leaveResponse;
try {
leaveResponse =
stub.leave(
LeaveRequest.newBuilder()
.setGid(gid)
.setClientId(clientId)
.setSeqId(seqId)
.build());
// logger.info("Response received from server:\n" + leaveResponse);
} catch (StatusRuntimeException e) {
logger.info("Fail to get response from server");
this.leader = (this.leader + 1) % masters.size();
continue;
} finally {
try {
channel.shutdown().awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (leaveResponse.getStatus() == 0) {
seqId++;
return;
} else {
this.leader = (this.leader + 1) % masters.size();
}
}
}
public String query(int version) {
while (true) {
final String masterHost = masters.get(leader).getKey();
final Integer masterPort = masters.get(leader).getValue();
ManagedChannel channel =
ManagedChannelBuilder.forAddress(masterHost, masterPort).usePlaintext().build();
MasterServiceGrpc.MasterServiceBlockingStub stub = MasterServiceGrpc.newBlockingStub(channel);
QueryResponse queryResponse;
try {
queryResponse =
stub.query(
QueryRequest.newBuilder()
.setVersion(version)
.setClientId(clientId)
.setSeqId(seqId)
.build());
// logger.info("Response received from server:\n" + queryResponse);
} catch (StatusRuntimeException e) {
logger.info("Fail to get response from server");
this.leader = (this.leader + 1) % masters.size();
continue;
} finally {
try {
channel.shutdown().awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (queryResponse.getStatus() == 0) {
seqId++;
return queryResponse.getData();
} else {
this.leader = (this.leader + 1) % masters.size();
}
}
}
public void move(long shardId, long gid) {
while (true) {
final String masterHost = masters.get(leader).getKey();
final Integer masterPort = masters.get(leader).getValue();
ManagedChannel channel =
ManagedChannelBuilder.forAddress(masterHost, masterPort).usePlaintext().build();
MasterServiceGrpc.MasterServiceBlockingStub stub = MasterServiceGrpc.newBlockingStub(channel);
MoveResponse moveResponse;
try {
moveResponse =
stub.move(
MoveRequest.newBuilder()
.setShardId(shardId)
.setGid(gid)
.setClientId(clientId)
.setSeqId(seqId)
.build());
// logger.info("Response received from server:\n" + moveResponse);
} catch (StatusRuntimeException e) {
logger.info("Fail to get response from server");
this.leader = (this.leader + 1) % masters.size();
continue;
} finally {
try {
channel.shutdown().awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (moveResponse.getStatus() == 0) {
seqId++;
return;
} else {
this.leader = (this.leader + 1) % masters.size();
}
}
}
}
|
923d5824c393f661c5695dcdda3eb104fa8a83ee | 5,177 | java | Java | src/com/jbirdvegas/mgerrit/objects/CommitInfo.java | p4r4n01d/external_jbirdvegas_mGerrit | de8fbae4c365be74436dc5f46c8b4dc2a72b298b | [
"Apache-2.0"
] | 2 | 2015-01-04T17:50:19.000Z | 2015-01-18T14:35:44.000Z | src/com/jbirdvegas/mgerrit/objects/CommitInfo.java | p4r4n01d/external_jbirdvegas_mGerrit | de8fbae4c365be74436dc5f46c8b4dc2a72b298b | [
"Apache-2.0"
] | null | null | null | src/com/jbirdvegas/mgerrit/objects/CommitInfo.java | p4r4n01d/external_jbirdvegas_mGerrit | de8fbae4c365be74436dc5f46c8b4dc2a72b298b | [
"Apache-2.0"
] | null | null | null | 34.284768 | 98 | 0.664477 | 1,000,284 | package com.jbirdvegas.mgerrit.objects;
/*
* Copyright (C) 2013 Android Open Kang Project (AOKP)
* Author: Evan Conway (P4R4N01D), 2013
*
* 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 android.content.Context;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.jbirdvegas.mgerrit.R;
import java.util.List;
/**
* Contains information about a revision or patch set. This condenses both
* the RevisionInfo and CommitInfo objects together into the one level
*/
public class CommitInfo {
/** The Change-Id of the change. */
private String mChangeId;
private static final String KEY_COMMIT = "commit";
/**The commit ID of the current patch set of this change.
* Don't set the @SerialisedName as there is a name conflict here */
private String mCommit;
public static final String KEY_AUTHOR = "author";
@SerializedName(CommitInfo.KEY_AUTHOR)
private CommitterObject mAuthorObject;
private static final String KEY_COMMITTER = "committer";
@SerializedName(CommitInfo.KEY_COMMITTER)
private CommitterObject mCommitterObject;
public static final String KEY_MESSAGE = "message";
@SerializedName(CommitInfo.KEY_MESSAGE)
private String mMessage;
@SerializedName(JSONCommit.KEY_SUBJECT)
private String mSubject;
@SerializedName("_number")
private String mPatchSetNumber;
public static final String KEY_CHANGED_FILES = "files";
// Information about the files in this patch set.
@SerializedName(CommitInfo.KEY_CHANGED_FILES)
private FileInfoList mFileInfos;
@SerializedName("draft")
private boolean mIsDraft;
public static CommitInfo deserialise(JsonObject object, String changeId) {
CommitInfo revision = new Gson().fromJson(object, CommitInfo.class);
revision.mChangeId = changeId;
// Add the changed files
if (object.has(CommitInfo.KEY_CHANGED_FILES)) {
JsonObject filesObj = object.get(CommitInfo.KEY_CHANGED_FILES).getAsJsonObject();
revision.mFileInfos = FileInfoList.deserialize(filesObj);
}
// Some objects are nested here
if (object.has(CommitInfo.KEY_COMMIT)) {
JsonObject commitObj = object.get(KEY_COMMIT).getAsJsonObject();
CommitInfo r2 = new Gson().fromJson(commitObj, CommitInfo.class);
merge(revision, r2);
if (commitObj.has(KEY_COMMIT)) {
revision.mCommit = commitObj.get(KEY_COMMIT).getAsString();
}
}
return revision;
}
/**
* Merge two CommitInfo objects together, modifying the first
* @param a The commitInfo object to be modified
* @param b Secondary commitInfo object to be merged into a
*/
private static void merge(CommitInfo a, final CommitInfo b) {
a.mAuthorObject = b.mAuthorObject == null ? a.mAuthorObject : b.mAuthorObject;
a.mCommitterObject = b.mCommitterObject == null ? a.mCommitterObject : b.mCommitterObject;
a.mMessage = b.mMessage == null ? a.mMessage : b.mMessage;
a.mSubject = b.mSubject == null ? a.mSubject : b.mSubject;
}
public CommitterObject getAuthorObject() {
return mAuthorObject;
}
public CommitterObject getCommitterObject() {
return mCommitterObject;
}
public String getMessage() {
return mMessage;
}
protected void setMessage(Context context) {
if (mMessage == null) {
this.mMessage = context.getString(R.string.current_revision_is_draft_message);
}
}
public String getChangeId() { return mChangeId; }
public String getCommit() { return mCommit; }
public String getSubject() { return mSubject; }
public String getPatchSetNumber() { return mPatchSetNumber; }
public boolean isIsDraft() { return mIsDraft; }
public List<FileInfo> getChangedFiles() { return mFileInfos.getFiles(); }
public void setChangedFiles(FileInfoList fileInfos) { this.mFileInfos = fileInfos; }
@Override
public String toString() {
return "CommitInfo{" +
"mChangeId='" + mChangeId + '\'' +
", mCommit='" + mCommit + '\'' +
", mAuthorObject=" + mAuthorObject +
", mCommitterObject=" + mCommitterObject +
", mMessage='" + mMessage + '\'' +
", mSubject='" + mSubject + '\'' +
", mPatchSetNumber='" + mPatchSetNumber + '\'' +
", mFileInfos=" + mFileInfos +
", mIsDraft=" + mIsDraft +
'}';
}
}
|
923d59ee91060812fb5f22a7e36459ab73f61c3c | 2,266 | java | Java | ContactManagerModule/src/m1/pi/Contact.java | JUX84/ContactManager | 022dcdc9dbdd598fe38d50c67342e1d04dd20cd3 | [
"MIT"
] | null | null | null | ContactManagerModule/src/m1/pi/Contact.java | JUX84/ContactManager | 022dcdc9dbdd598fe38d50c67342e1d04dd20cd3 | [
"MIT"
] | null | null | null | ContactManagerModule/src/m1/pi/Contact.java | JUX84/ContactManager | 022dcdc9dbdd598fe38d50c67342e1d04dd20cd3 | [
"MIT"
] | null | null | null | 25.460674 | 80 | 0.610327 | 1,000,285 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package m1.pi;
import java.beans.*;
import java.io.Serializable;
/**
*
* @author JUX
*/
public class Contact implements Serializable {
private String firstName;
private String lastName;
private int age;
private boolean sex; // male = false, female = true
private String mail;
private PropertyChangeSupport propertySupport;
public Contact() {
propertySupport = new PropertyChangeSupport(this);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String value) {
String oldValue = firstName;
firstName = value;
propertySupport.firePropertyChange("firstName", oldValue, firstName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String value) {
String oldValue = lastName;
lastName = value;
propertySupport.firePropertyChange("lastName", oldValue, lastName);
}
public int getAge() {
return age;
}
public void setAge(int value) {
int oldValue = age;
age = value;
propertySupport.firePropertyChange("age", oldValue, age);
}
public boolean getSex() {
return sex;
}
public void setSex(boolean value) {
boolean oldValue = sex;
sex = value;
propertySupport.firePropertyChange("sex", oldValue, sex);
}
public String getMail() {
return mail;
}
public void setMail(String value) {
String oldValue = mail;
mail = value;
propertySupport.firePropertyChange("sex", oldValue, mail);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener(listener);
}
}
|
923d5a3d2dac31374df3a5db9c56809506e6ea15 | 1,038 | java | Java | src/main/java/io/github/doocs/im/model/callback/BeforeSendGroupMsgResponse.java | doocs/qcloud-im-server-sdk-java | 584e0567d52444dd32e72d309bd7df0e8c2e68ef | [
"Apache-2.0"
] | 30 | 2021-07-29T06:46:21.000Z | 2022-03-28T06:16:05.000Z | src/main/java/io/github/doocs/im/model/callback/BeforeSendGroupMsgResponse.java | doocs/qcloud-im-server-sdk-java | 584e0567d52444dd32e72d309bd7df0e8c2e68ef | [
"Apache-2.0"
] | 9 | 2021-11-07T01:12:56.000Z | 2022-02-10T02:25:32.000Z | src/main/java/io/github/doocs/im/model/callback/BeforeSendGroupMsgResponse.java | doocs/qcloud-im-server-sdk-java | 584e0567d52444dd32e72d309bd7df0e8c2e68ef | [
"Apache-2.0"
] | 14 | 2021-07-29T06:50:15.000Z | 2022-03-15T12:00:23.000Z | 25.95 | 126 | 0.72158 | 1,000,286 | package io.github.doocs.im.model.callback;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.github.doocs.im.model.message.TIMMsgElement;
import java.util.List;
/**
* 群内发言之前回调响应
*
* @author bingo
* @since 2021/11/16 21:00
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BeforeSendGroupMsgResponse extends CallbackResponse {
/**
* 经过App修改之后的消息体,云通讯后台将把修改后的消息发送到群组中
*/
@JsonProperty("MsgBody")
private List<TIMMsgElement> msgBody;
public BeforeSendGroupMsgResponse(List<TIMMsgElement> msgBody) {
this.msgBody = msgBody;
}
public BeforeSendGroupMsgResponse(String actionStatus, Integer errorCode, String errorInfo, List<TIMMsgElement> msgBody) {
super(actionStatus, errorCode, errorInfo);
this.msgBody = msgBody;
}
public List<TIMMsgElement> getMsgBody() {
return msgBody;
}
public void setMsgBody(List<TIMMsgElement> msgBody) {
this.msgBody = msgBody;
}
}
|
923d5a573c10f8a4f021a1277bc353858a7bab0e | 2,438 | java | Java | sql/catalyst/target/java/org/apache/spark/sql/catalyst/expressions/GetMapValue.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | sql/catalyst/target/java/org/apache/spark/sql/catalyst/expressions/GetMapValue.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | sql/catalyst/target/java/org/apache/spark/sql/catalyst/expressions/GetMapValue.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | 76.1875 | 312 | 0.753486 | 1,000,287 | package org.apache.spark.sql.catalyst.expressions;
/**
* Returns the value of key <code>key</code> in Map <code>child</code>.
* <p>
* We need to do type checking here as <code>key</code> expression maybe unresolved.
*/
public class GetMapValue extends org.apache.spark.sql.catalyst.expressions.BinaryExpression implements org.apache.spark.sql.catalyst.expressions.GetMapValueUtil, org.apache.spark.sql.catalyst.expressions.ExtractValue, org.apache.spark.sql.catalyst.expressions.NullIntolerant, scala.Product, scala.Serializable {
static public abstract R apply (T1 v1, T2 v2) ;
public org.apache.spark.sql.catalyst.expressions.Expression child () { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.expressions.Expression key () { throw new RuntimeException(); }
// not preceding
public GetMapValue (org.apache.spark.sql.catalyst.expressions.Expression child, org.apache.spark.sql.catalyst.expressions.Expression key) { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.analysis.TypeCheckResult checkInputDataTypes () { throw new RuntimeException(); }
public scala.collection.Seq<org.apache.spark.sql.types.AbstractDataType> inputTypes () { throw new RuntimeException(); }
public java.lang.String toString () { throw new RuntimeException(); }
public java.lang.String sql () { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.expressions.Expression left () { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.expressions.Expression right () { throw new RuntimeException(); }
/**
* <code>Null</code> is returned for invalid ordinals.
* <p>
* TODO: We could make nullability more precise in foldable cases (e.g., literal input).
* But, since the key search is O(n), it takes much time to compute nullability.
* If we find efficient key searches, revisit this.
* @return (undocumented)
*/
public boolean nullable () { throw new RuntimeException(); }
public org.apache.spark.sql.types.DataType dataType () { throw new RuntimeException(); }
public Object nullSafeEval (Object value, Object ordinal) { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.expressions.codegen.ExprCode doGenCode (org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext ctx, org.apache.spark.sql.catalyst.expressions.codegen.ExprCode ev) { throw new RuntimeException(); }
}
|
923d5a6af626e92feb85e19504781518b28cf05a | 5,349 | java | Java | trader-services/src/main/java/trader/simulator/trade/SimTradeService.java | harryzzp/java-trader | 263955d5b4e7fdd4e2b1c52ade439e6ad2fd5942 | [
"Apache-2.0"
] | 68 | 2018-11-21T07:11:51.000Z | 2022-03-28T02:19:11.000Z | trader-services/src/main/java/trader/simulator/trade/SimTradeService.java | harryzzp/java-trader | 263955d5b4e7fdd4e2b1c52ade439e6ad2fd5942 | [
"Apache-2.0"
] | 7 | 2018-12-24T11:49:24.000Z | 2021-08-15T05:37:55.000Z | trader-services/src/main/java/trader/simulator/trade/SimTradeService.java | harryzzp/java-trader | 263955d5b4e7fdd4e2b1c52ade439e6ad2fd5942 | [
"Apache-2.0"
] | 42 | 2018-11-21T07:14:18.000Z | 2021-12-22T11:30:59.000Z | 30.392045 | 110 | 0.676201 | 1,000,288 | package trader.simulator.trade;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import trader.common.beans.BeansContainer;
import trader.common.config.ConfigUtil;
import trader.common.util.ConversionUtil;
import trader.common.util.TimestampSeqGen;
import trader.service.md.MarketData;
import trader.service.md.MarketDataService;
import trader.service.trade.Account;
import trader.service.trade.AccountImpl;
import trader.service.trade.MarketTimeService;
import trader.service.trade.OrderRefGen;
import trader.service.trade.OrderRefGenImpl;
import trader.service.trade.TradeService;
import trader.service.trade.TradeServiceListener;
import trader.service.trade.TxnSession;
import trader.service.trade.TxnSessionFactory;
import trader.service.trade.spi.AbsTxnSession;
/**
* 模拟成交服务
*/
public class SimTradeService implements TradeService {
private final static Logger logger = LoggerFactory.getLogger(SimTradeService.class);
static final String ITEM_ACCOUNT = "/TradeService/account";
static final String ITEM_ACCOUNTS = ITEM_ACCOUNT+"[]";
private BeansContainer beansContainer;
private Map<String, TxnSessionFactory> txnSessionFactories = new HashMap<>();
private TimestampSeqGen orderIdGen;
private OrderRefGen orderRefGen;
private List<AccountImpl> accounts = new ArrayList<>();
private AccountImpl primaryAccount = null;
@Override
public void init(BeansContainer beansContainer) throws Exception {
this.beansContainer = beansContainer;
MarketTimeService mtService = beansContainer.getBean(MarketTimeService.class);
if ( orderRefGen==null ) {
orderRefGen = new OrderRefGenImpl(this, mtService.getTradingDay(), beansContainer);
}
orderIdGen = new TimestampSeqGen(mtService);
MarketDataService mdService = beansContainer.getBean(MarketDataService.class);
//接收行情, 异步更新账户的持仓盈亏
mdService.addListener((MarketData md)->{
accountOnMarketData(md);
});
//自动发现交易接口API
txnSessionFactories = discoverTxnSessionProviders(beansContainer);
loadAccounts();
connectTxnSessions(accounts);
}
@Override
public void destroy() {
for(AccountImpl account:accounts) {
account.destroy();
}
}
public TradeServiceType getType() {
return TradeServiceType.Simulator;
}
@Override
public Map<String, TxnSessionFactory> getTxnSessionFactories(){
return Collections.unmodifiableMap(txnSessionFactories);
}
public OrderRefGen getOrderRefGen() {
return orderRefGen;
}
public TimestampSeqGen getOrderIdGen() {
return orderIdGen;
}
@Override
public Account getPrimaryAccount() {
return primaryAccount;
}
@Override
public Account getAccount(String id) {
for(AccountImpl account:accounts) {
if ( account.getId().equals(id)) {
return account;
}
}
return null;
}
@Override
public List<Account> getAccounts() {
return Collections.unmodifiableList(accounts);
}
public void addListener(TradeServiceListener listener) {
//do nothing
}
public void setOrderRefMgr(OrderRefGen orderRefGen) {
this.orderRefGen = orderRefGen;
}
private void loadAccounts() {
List<Map> accountElems = (List<Map>)ConfigUtil.getObject(ITEM_ACCOUNTS);
List<AccountImpl> allAccounts = new ArrayList<>();
if ( accountElems!=null ) {
for (Map accountElem:accountElems) {
accountElem.put("provider", TxnSession.PROVIDER_SIM);
String id = ConversionUtil.toString(accountElem.get("id"));
AccountImpl currAccount = createAccount(accountElem);
allAccounts.add(currAccount);
}
}
this.accounts = allAccounts;
if ( primaryAccount==null && !accounts.isEmpty()) {
primaryAccount = accounts.get(0);
}
}
/**
* 启动完毕后, 连接交易通道
*/
private void connectTxnSessions(List<AccountImpl> accountsToConnect) {
for(AccountImpl account:accountsToConnect) {
AbsTxnSession txnSession = (AbsTxnSession)account.getSession();
txnSession.connect(account.getConnectionProps());
}
}
private static Map<String, TxnSessionFactory> discoverTxnSessionProviders(BeansContainer beansContainer ){
Map<String, TxnSessionFactory> result = new TreeMap<>();
result.put(TxnSession.PROVIDER_SIM, new SimTxnSessionFactory());
return result;
}
private AccountImpl createAccount(Map accountElem)
{
AccountImpl account = new AccountImpl(this, beansContainer, accountElem);
return account;
}
/**
* 重新计算持仓利润
*/
private void accountOnMarketData(MarketData md) {
for(int i=0; i<accounts.size();i++) {
try{
accounts.get(i).onMarketData(md);
}catch(Throwable t) {
logger.error("Async market event process failed on data "+md);
}
}
}
}
|
923d5b2f9363b6a4c0726371fee496789fa69cef | 2,100 | java | Java | app/src/main/java/br/com/infinitytechnology/filmex/activities/AcknowledgmentsActivity.java | RogerSilva2/Filmex | 95950505fcea88dac92a5ee72bf142580df2da17 | [
"MIT"
] | null | null | null | app/src/main/java/br/com/infinitytechnology/filmex/activities/AcknowledgmentsActivity.java | RogerSilva2/Filmex | 95950505fcea88dac92a5ee72bf142580df2da17 | [
"MIT"
] | null | null | null | app/src/main/java/br/com/infinitytechnology/filmex/activities/AcknowledgmentsActivity.java | RogerSilva2/Filmex | 95950505fcea88dac92a5ee72bf142580df2da17 | [
"MIT"
] | null | null | null | 36.842105 | 95 | 0.68 | 1,000,289 | package br.com.infinitytechnology.filmex.activities;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import br.com.infinitytechnology.filmex.R;
import br.com.infinitytechnology.filmex.utils.PropertyUtil;
public class AcknowledgmentsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acknowledgments);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
ImageView imageViewTmdb = findViewById(R.id.image_view_tmdb);
String tmdbPrimaryLightGreen =
PropertyUtil.property(this, "tmdb.primary.light.green");
Picasso.with(this)
.load(tmdbPrimaryLightGreen)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(imageViewTmdb);
}
} |
923d5b7a79bd4eba5d8201b8033d888300dff50d | 3,800 | java | Java | cohort/week09/DiningPhilFixed1.java | jamestiotio/esc | 971d9018e389b5ac374438792a417c74541898e2 | [
"MIT"
] | null | null | null | cohort/week09/DiningPhilFixed1.java | jamestiotio/esc | 971d9018e389b5ac374438792a417c74541898e2 | [
"MIT"
] | 1 | 2021-11-04T15:56:26.000Z | 2021-11-04T15:56:26.000Z | cohort/week09/DiningPhilFixed1.java | jamestiotio/esc | 971d9018e389b5ac374438792a417c74541898e2 | [
"MIT"
] | null | null | null | 34.545455 | 103 | 0.515263 | 1,000,290 | import java.util.Random;
// Impose and apply a global ordering of picking up forks: N-1, ..., 2, 1, 0 to ensure that none of the
// philosophers will try to grab the same forks with the same hands
public class DiningPhilFixed1 {
private static int N = 5;
public static void main(String[] args) throws Exception {
Philosopher1[] phils = new Philosopher1[N];
Fork1[] forks = new Fork1[N];
for (int i = 0; i < N; i++) {
forks[i] = new Fork1(i);
}
for (int i = 0; i < N; i++) {
phils[i] = new Philosopher1(i, forks[i], forks[(i + N - 1) % N]);
phils[i].start();
}
}
}
class Philosopher1 extends Thread {
private final int index;
private final Fork1 left;
private final Fork1 right;
public Philosopher1(int index, Fork1 left, Fork1 right) {
this.index = index;
this.left = left;
this.right = right;
}
public void run() {
Random randomGenerator = new Random();
try {
while (true) {
if (index == 0) {
// First philosopher grabs right then left
Thread.sleep(randomGenerator.nextInt(100)); // not sleeping but thinking
System.out.println("Phil " + index + " finishes thinking.");
right.pickup();
System.out.println("Phil " + index + " picks up right fork.");
left.pickup();
System.out.println("Phil " + index + " picks up left fork.");
Thread.sleep(randomGenerator.nextInt(100)); // eating
System.out.println("Phil " + index + " finishes eating.");
right.putdown();
System.out.println("Phil " + index + " puts down right fork.");
left.putdown();
System.out.println("Phil " + index + " puts down left fork.");
} else {
// Other philosophers follow the same old rule of grabbing left first then right
Thread.sleep(randomGenerator.nextInt(100)); // not sleeping but thinking
System.out.println("Phil " + index + " finishes thinking.");
left.pickup();
System.out.println("Phil " + index + " picks up left fork.");
right.pickup();
System.out.println("Phil " + index + " picks up right fork.");
Thread.sleep(randomGenerator.nextInt(100)); // eating
System.out.println("Phil " + index + " finishes eating.");
left.putdown();
System.out.println("Phil " + index + " puts down left fork.");
right.putdown();
System.out.println("Phil " + index + " puts down right fork.");
}
}
} catch (InterruptedException e) {
System.out.println("Don't disturb me while I am sleeping, well, thinking.");
}
}
}
class Fork1 {
private final int index;
private boolean isAvailable = true;
public Fork1(int index) {
this.index = index;
}
public synchronized void pickup() throws InterruptedException {
while (!isAvailable) {
wait();
}
isAvailable = false;
notifyAll();
}
public synchronized void putdown() throws InterruptedException {
while (isAvailable) {
wait();
}
isAvailable = true;
notifyAll();
}
public String toString() {
if (isAvailable) {
return "Fork1 " + index + " is available.";
} else {
return "Fork1 " + index + " is NOT available.";
}
}
}
|
923d5bcac1000b500178b580ed7de88f040606a8 | 4,587 | java | Java | examples/java/insert-loadgen/src/main/java/org/apache/kudu/examples/InsertLoadgen.java | SuckShit/kudu | ec5d1e29e019d4e5274231ae57cc14e7a4d52a72 | [
"Apache-2.0"
] | 1,538 | 2016-08-08T22:34:30.000Z | 2022-03-29T05:23:36.000Z | examples/java/insert-loadgen/src/main/java/org/apache/kudu/examples/InsertLoadgen.java | SuckShit/kudu | ec5d1e29e019d4e5274231ae57cc14e7a4d52a72 | [
"Apache-2.0"
] | 29 | 2019-07-01T13:40:51.000Z | 2021-06-30T19:15:03.000Z | examples/java/insert-loadgen/src/main/java/org/apache/kudu/examples/InsertLoadgen.java | SuckShit/kudu | ec5d1e29e019d4e5274231ae57cc14e7a4d52a72 | [
"Apache-2.0"
] | 612 | 2016-08-12T04:09:37.000Z | 2022-03-29T16:57:46.000Z | 34.488722 | 94 | 0.65424 | 1,000,291 | // 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.kudu.examples;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.Insert;
import org.apache.kudu.client.KuduClient;
import org.apache.kudu.client.KuduSession;
import org.apache.kudu.client.KuduTable;
import org.apache.kudu.client.PartialRow;
import org.apache.kudu.client.SessionConfiguration;
public class InsertLoadgen {
private static class RandomDataGenerator {
private final Random rng;
private final int index;
private final Type type;
/**
* Instantiate a random data generator for a specific field.
* @param index The numerical index of the column in the row schema
* @param type The type of the data at index {@code index}
*/
public RandomDataGenerator(int index, Type type) {
this.rng = new Random();
this.index = index;
this.type = type;
}
/**
* Add random data to the given row for the column at index {@code index}
* of type {@code type}
* @param row The row to add the field to
*/
void generateColumnData(PartialRow row) {
switch (type) {
case INT8:
row.addByte(index, (byte) rng.nextInt(Byte.MAX_VALUE));
return;
case INT16:
row.addShort(index, (short)rng.nextInt(Short.MAX_VALUE));
return;
case INT32:
row.addInt(index, rng.nextInt(Integer.MAX_VALUE));
return;
case INT64:
case UNIXTIME_MICROS:
row.addLong(index, rng.nextLong());
return;
case BINARY:
byte bytes[] = new byte[16];
rng.nextBytes(bytes);
row.addBinary(index, bytes);
return;
case STRING:
row.addString(index, UUID.randomUUID().toString());
return;
case BOOL:
row.addBoolean(index, rng.nextBoolean());
return;
case FLOAT:
row.addFloat(index, rng.nextFloat());
return;
case DOUBLE:
row.addDouble(index, rng.nextDouble());
return;
case DECIMAL:
row.addDecimal(index, new BigDecimal(rng.nextDouble()));
return;
default:
throw new UnsupportedOperationException("Unknown type " + type);
}
}
}
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: InsertLoadgen master_addresses table_name");
System.exit(1);
}
String masterAddrs = args[0];
String tableName = args[1];
try (KuduClient client = new KuduClient.KuduClientBuilder(masterAddrs).build()) {
KuduTable table = client.openTable(tableName);
Schema schema = table.getSchema();
List<RandomDataGenerator> generators = new ArrayList<>(schema.getColumnCount());
for (int i = 0; i < schema.getColumnCount(); i++) {
generators.add(new RandomDataGenerator(i, schema.getColumnByIndex(i).getType()));
}
KuduSession session = client.newSession();
session.setFlushMode(SessionConfiguration.FlushMode.AUTO_FLUSH_BACKGROUND);
for (int insertCount = 0; ; insertCount++) {
Insert insert = table.newInsert();
PartialRow row = insert.getRow();
for (int i = 0; i < schema.getColumnCount(); i++) {
generators.get(i).generateColumnData(row);
}
session.apply(insert);
// Check for errors. This is done periodically since inserts are batched.
if (insertCount % 1000 == 0 && session.countPendingErrors() > 0) {
throw new RuntimeException(session.getPendingErrors().getRowErrors()[0].toString());
}
}
}
}
}
|
923d5c0e264259e40570d9cf4f5d83e1378d8e14 | 4,458 | java | Java | swing/src/com/wangzh/unit/HttpClient.java | WangZh999/xiaoxin | 041efd1326cd2895f993a79b6c44d28ac69c65bd | [
"Apache-2.0"
] | null | null | null | swing/src/com/wangzh/unit/HttpClient.java | WangZh999/xiaoxin | 041efd1326cd2895f993a79b6c44d28ac69c65bd | [
"Apache-2.0"
] | null | null | null | swing/src/com/wangzh/unit/HttpClient.java | WangZh999/xiaoxin | 041efd1326cd2895f993a79b6c44d28ac69c65bd | [
"Apache-2.0"
] | null | null | null | 36.540984 | 170 | 0.580305 | 1,000,292 | package com.wangzh.unit;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpClient {
public static String doGet(String httpUrl) {
HttpURLConnection connection = null;
URL url = null;
String result = "";
try {
url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("GET");
setHeader(connection);
} catch (Exception exp) {
exp.printStackTrace();
return result;
}
try (InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
connection.connect();
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() != 200) {
return result;
}
StringBuilder sbf = new StringBuilder();
String temp = null;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
} catch (IOException exp) {
exp.printStackTrace();
}
connection.disconnect();
return result;
}
public static String doPost(String httpUrl, String param) {
HttpURLConnection connection = null;
URL url = null;
String result = "";
try {
url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
connection.setDoOutput(true);
setHeader(connection);
} catch (Exception exp) {
exp.printStackTrace();
return result;
}
try (OutputStream os = connection.getOutputStream()) {
os.write(param.getBytes(StandardCharsets.UTF_8));
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() != 200) {
// return result;
}
} catch (IOException exp) {
exp.printStackTrace();
}
try (InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
StringBuilder sbf = new StringBuilder();
String temp = null;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
} catch (IOException exp) {
exp.printStackTrace();
}
connection.disconnect();
System.out.println(httpUrl + " " + param + " " + result);
return result;
}
private static void setHeader(HttpURLConnection connection) {
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
connection.setRequestProperty("authority", "zuoyenew.xinkaoyun.com:30001");
connection.setRequestProperty("sec-ch-ua", "\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"97\", \"Chromium\";v=\"97\"");
connection.setRequestProperty("accept", "application/json, text/javascript, */*; q=0.01");
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
connection.setRequestProperty("sec-ch-ua-mobile", "?0");
connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36");
connection.setRequestProperty("sec-ch-ua-platform", "\"Windows\"");
connection.setRequestProperty("origin", "https://homework.xinkaoyun.com");
connection.setRequestProperty("sec-fetch-site", "same-site");
connection.setRequestProperty("sec-fetch-mode", "cors");
connection.setRequestProperty("sec-fetch-dest", "empty");
connection.setRequestProperty("referer", "https://homework.xinkaoyun.com/");
connection.setRequestProperty("accept-language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
}
} |
923d5c2ef78cf332cd30bc87025447a50d0e69c9 | 3,312 | java | Java | src/main/java/br/com/ernanilima/jmercado/controller/menus/BCadProdutos.java | ernanilima/jmercado-desktop | 93c3b333e314efd15b96607576c70935a6ad9964 | [
"MIT"
] | 5 | 2021-05-21T21:09:55.000Z | 2022-03-14T00:25:51.000Z | src/main/java/br/com/ernanilima/jmercado/controller/menus/BCadProdutos.java | ernanilima/jmercado-desktop | 93c3b333e314efd15b96607576c70935a6ad9964 | [
"MIT"
] | null | null | null | src/main/java/br/com/ernanilima/jmercado/controller/menus/BCadProdutos.java | ernanilima/jmercado-desktop | 93c3b333e314efd15b96607576c70935a6ad9964 | [
"MIT"
] | null | null | null | 33.12 | 95 | 0.680254 | 1,000,293 | package br.com.ernanilima.jmercado.controller.menus;
import br.com.ernanilima.jmercado.controller.MenuController;
import br.com.ernanilima.jmercado.liberacao.Liberacoes;
import br.com.ernanilima.jmercado.liberacao.validacao.ValidarLiberacao;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.layout.VBox;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class BCadProdutos {
@Autowired private MenuController cMenu;
@Autowired private CCadDepartamentos cCadDepartamentos;
@Autowired private CCadGrupos cCadGrupos;
@Autowired private CCadSubgrupos cCadSubgrupos;
@Autowired private CCadProdutos cCadProdutos;
@Autowired private ValidarLiberacao vLiberacao;
// botao que abre o box com outros botoes relacionados
private Button btnBCadProdutos = new Button();
// box com botoes relacionados
private VBox boxCCadProdutos = new VBox();
private VBox boxDoMenu = new VBox(btnBCadProdutos, boxCCadProdutos);
/** Configura o botao,
* @return VBox - botao, box com botoes relacionados */
public VBox getMenuB() {
liberacaoParaBotao();
listener();
configurarBotao();
configurarBox();
return boxDoMenu;
}
/** Acao ao pressionar botao */
private void listener() {
btnBCadProdutos.setOnAction(e -> minimizaMaximiza());
}
/** Constroi o botao */
private void configurarBotao() {
btnBCadProdutos.getStyleClass().add("btnB");
btnBCadProdutos.setId("btn_mais");
btnBCadProdutos.setMinSize(cMenu.getLarguraX(), cMenu.getAlturaY());
btnBCadProdutos.setMaxSize(cMenu.getLarguraX(), cMenu.getAlturaY());
btnBCadProdutos.setText("Cadastro De Produtos");
}
/** Configura o box com os botoes relacionados */
private void configurarBox() {
boxCCadProdutos.setPrefHeight(0);
boxCCadProdutos.setVisible(false);
}
/** Verifica se o box com botoes relacionados esta visivil ou nao */
private void minimizaMaximiza() {
if (boxCCadProdutos.isVisible()) {
minimizarBox();
} else {
maximizarBox();
}
}
/** Apaga tudo do box com botoes relacionados */
public void minimizarBox() {
boxCCadProdutos.setPrefHeight(0);
boxCCadProdutos.setVisible(false);
boxCCadProdutos.getChildren().removeAll(getMenusC());
}
/** Adiciona todos os botoes relacionados ao box */
private void maximizarBox() {
boxCCadProdutos.setPrefHeight(Control.USE_COMPUTED_SIZE);
boxCCadProdutos.setVisible(true);
boxCCadProdutos.getChildren().addAll(getMenusC());
}
/** Todos os botoes secundarios
* @return VBox[] - menus C */
private VBox[] getMenusC() {
return new VBox[] {
cCadDepartamentos.getMenuC(),
cCadGrupos.getMenuC(),
cCadSubgrupos.getMenuC(),
cCadProdutos.getMenuC()
};
}
/** Liberacao para o menu */
private void liberacaoParaBotao() {
// VALIDACAO DE LIBERACOES DE USUARIO
vLiberacao.liberacaoUsuario(btnBCadProdutos, Liberacoes.CADASTROS_PRODUTOS, boxDoMenu);
}
}
|
923d5ce4a72c75c855e2957dc20d4596b951be88 | 4,701 | java | Java | support-common/src/main/java/com/fox/one/support/common/utils/MimeTypes.java | fox-one/foxone-opensdk-android | ebfb2e21a5c204b02c44a02625cf2a40eaca69fd | [
"Apache-2.0"
] | 2 | 2019-03-28T12:16:40.000Z | 2019-11-20T03:16:41.000Z | support-common/src/main/java/com/fox/one/support/common/utils/MimeTypes.java | fox-one/foxone-opensdk-android | ebfb2e21a5c204b02c44a02625cf2a40eaca69fd | [
"Apache-2.0"
] | null | null | null | support-common/src/main/java/com/fox/one/support/common/utils/MimeTypes.java | fox-one/foxone-opensdk-android | ebfb2e21a5c204b02c44a02625cf2a40eaca69fd | [
"Apache-2.0"
] | null | null | null | 41.973214 | 87 | 0.650287 | 1,000,294 | package com.fox.one.support.common.utils;
/**
* Created by zhangyinghao on 2018/7/19.
*/
public final class MimeTypes
{
public static final class Application
{
public static final String ATOM_XML = "application/atom+xml";
public static final String ATOMCAT_XML = "application/atomcat+xml";
public static final String ECMASCRIPT = "application/ecmascript";
public static final String JAVA_ARCHIVE = "application/java-archive";
public static final String JAVASCRIPT = "application/javascript";
public static final String JSON = "application/json";
public static final String MP4 = "application/mp4";
public static final String OCTET_STREAM = "application/octet-stream";
public static final String PDF = "application/pdf";
public static final String PKCS_10 = "application/pkcs10";
public static final String PKCS_7_MIME = "application/pkcs7-mime";
public static final String PKCS_7_SIGNATURE = "application/pkcs7-signature";
public static final String PKCS_8 = "application/pkcs8";
public static final String POSTSCRIPT = "application/postscript";
public static final String RDF_XML = "application/rdf+xml";
public static final String RSS_XML = "application/rss+xml";
public static final String RTF = "application/rtf";
public static final String SMIL_XML = "application/smil+xml";
public static final String X_FONT_OTF = "application/x-font-otf";
public static final String X_FONT_TTF = "application/x-font-ttf";
public static final String X_FONT_WOFF = "application/x-font-woff";
public static final String X_PKCS_12 = "application/x-pkcs12";
public static final String X_SHOCKWAVE_FLASH = "application/x-shockwave-flash";
public static final String X_SILVERLIGHT_APP = "application/x-silverlight-app";
public static final String XHTML_XML = "application/xhtml+xml";
public static final String XML = "application/xml";
public static final String XML_DTD = "application/xml-dtd";
public static final String XSLT_XML = "application/xslt+xml";
public static final String ZIP = "application/zip";
public static final String ALL = "application/*";
private Application()
{
}
}
public static final class Audio
{
public static final String MIDI = "audio/midi";
public static final String MP4 = "audio/mp4";
public static final String MPEG = "audio/mpeg";
public static final String OGG = "audio/ogg";
public static final String WEBM = "audio/webm";
public static final String X_AAC = "audio/x-aac";
public static final String X_AIFF = "audio/x-aiff";
public static final String X_MPEGURL = "audio/x-mpegurl";
public static final String X_MS_WMA = "audio/x-ms-wma";
public static final String X_WAV = "audio/x-wav";
public static final String ALL = "audio/*";
private Audio()
{
}
}
public static final class Image
{
public static final String BMP = "image/bmp";
public static final String GIF = "image/gif";
public static final String JPEG = "image/jpeg";
public static final String PNG = "image/png";
public static final String SVG_XML = "image/svg+xml";
public static final String TIFF = "image/tiff";
public static final String WEBP = "image/webp";
public static final String ALL = "image/*";
private Image()
{
}
}
public static final class Text
{
public static final String CSS = "text/css";
public static final String CSV = "text/csv";
public static final String HTML = "text/html";
public static final String PLAIN = "text/plain";
public static final String RICH_TEXT = "text/richtext";
public static final String SGML = "text/sgml";
public static final String YAML = "text/yaml";
public static final String ALL = "text/*";
private Text()
{
}
}
public static final class Video
{
public static final String THREEGPP = "video/3gpp";
public static final String H264 = "video/h264";
public static final String MP4 = "video/mp4";
public static final String MPEG = "video/mpeg";
public static final String OGG = "video/ogg";
public static final String QUICKTIME = "video/quicktime";
public static final String WEBM = "video/webm";
public static final String ALL = "video/*";
private Video()
{
}
}
} |
923d5ce4d809a7e297ac39ea511b7ca7a0fb0c96 | 1,434 | java | Java | impc_prod_tracker/core/src/test/java/org/gentar/biology/plan/engine/PlanStateMachineResolverTest.java | ogunes-ebi/impc-production-tracker | 3be90edc8bc45d610c36c5d2011eb4254607129e | [
"Apache-2.0"
] | 1 | 2022-01-10T14:35:36.000Z | 2022-01-10T14:35:36.000Z | impc_prod_tracker/core/src/test/java/org/gentar/biology/plan/engine/PlanStateMachineResolverTest.java | ogunes-ebi/impc-production-tracker | 3be90edc8bc45d610c36c5d2011eb4254607129e | [
"Apache-2.0"
] | 185 | 2019-02-19T10:03:45.000Z | 2022-03-28T07:40:28.000Z | impc_prod_tracker/core/src/test/java/org/gentar/biology/plan/engine/PlanStateMachineResolverTest.java | ogunes-ebi/impc-production-tracker | 3be90edc8bc45d610c36c5d2011eb4254607129e | [
"Apache-2.0"
] | 7 | 2019-02-18T08:54:01.000Z | 2022-02-07T10:46:28.000Z | 32.590909 | 78 | 0.707113 | 1,000,295 | package org.gentar.biology.plan.engine;
import org.gentar.biology.plan.Plan;
import org.gentar.biology.plan.attempt.AttemptTypesName;
import org.gentar.biology.plan.engine.crispr.CrisprProductionPlanEvent;
import org.gentar.biology.plan.type.PlanTypeName;
import org.gentar.statemachine.ProcessEvent;
import org.gentar.test_util.PlanBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class PlanStateMachineResolverTest
{
private PlanStateMachineResolver testInstance;
@BeforeEach
public void setup()
{
testInstance = new PlanStateMachineResolver();
}
@Test
public void testWhenCrispr()
{
Plan plan = PlanBuilder.getInstance()
.withPlanType(PlanTypeName.PRODUCTION.getLabel())
.withAttemptType(AttemptTypesName.CRISPR.getLabel())
.build();
ProcessEvent processEvent =
testInstance.getProcessEventByActionName(
plan, CrisprProductionPlanEvent.abandonWhenCreated.getName());
assertThat(
"Invalid state machine",
(processEvent instanceof CrisprProductionPlanEvent),
is(true));
assertThat(
"Invalid event",
processEvent.getName(),
is(CrisprProductionPlanEvent.abandonWhenCreated.getName()));
}
} |
923d5ef2934fc9513f6da7f5719c84bbf23e71b3 | 706 | java | Java | autoparams/src/test/java/org/javaunit/autoparams/test/SpecsForZoneId.java | daejoon/AutoParams | 7d90f991bb290a2ced34f617d8bfe66a63de9bab | [
"MIT"
] | null | null | null | autoparams/src/test/java/org/javaunit/autoparams/test/SpecsForZoneId.java | daejoon/AutoParams | 7d90f991bb290a2ced34f617d8bfe66a63de9bab | [
"MIT"
] | null | null | null | autoparams/src/test/java/org/javaunit/autoparams/test/SpecsForZoneId.java | daejoon/AutoParams | 7d90f991bb290a2ced34f617d8bfe66a63de9bab | [
"MIT"
] | null | null | null | 27.153846 | 90 | 0.756374 | 1,000,296 | package org.javaunit.autoparams.test;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.time.ZoneId;
import org.javaunit.autoparams.AutoSource;
import org.junit.jupiter.params.ParameterizedTest;
public class SpecsForZoneId {
@ParameterizedTest
@AutoSource
void sut_creates_ZoneId_value(ZoneId zoneId) {
assertNotNull(zoneId);
}
@ParameterizedTest
@AutoSource
void sut_creates_anonymous_ZoneId_value(ZoneId value1, ZoneId value2, ZoneId value3) {
assertNotEquals(value1, value2);
assertNotEquals(value2, value3);
assertNotEquals(value3, value1);
}
}
|
923d5f630a1cfdb67a6b95228353ed6b7276de14 | 919 | java | Java | src/main/java/top/fastsql/mapper/PartialBeanPropertyRowMapper.java | fast-sql/FastSQL | 443c383aa25b70ba4afedb2127bde08486a9d99e | [
"Apache-2.0"
] | 119 | 2017-11-13T13:51:17.000Z | 2022-02-21T12:17:14.000Z | src/main/java/top/fastsql/mapper/PartialBeanPropertyRowMapper.java | cd-javaer/fast-sql | 443c383aa25b70ba4afedb2127bde08486a9d99e | [
"Apache-2.0"
] | 1 | 2018-05-26T06:03:02.000Z | 2018-07-25T05:41:11.000Z | src/main/java/top/fastsql/mapper/PartialBeanPropertyRowMapper.java | cd-javaer/fast-sql | 443c383aa25b70ba4afedb2127bde08486a9d99e | [
"Apache-2.0"
] | 26 | 2017-11-10T15:15:51.000Z | 2021-08-02T08:50:34.000Z | 20.422222 | 89 | 0.635473 | 1,000,297 | package top.fastsql.mapper;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 部分匹配
*
* @author Chenjiazhi
* 2018-08-01
*/
public class PartialBeanPropertyRowMapper<T> extends BeanPropertyRowMapper<T> {
public PartialBeanPropertyRowMapper() {
}
public PartialBeanPropertyRowMapper(Class<T> mappedClass) {
initialize(mappedClass);
}
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
T t = super.mapRow(rs, rowNumber);
try {
remainingMap(t, rs, rowNumber);
} catch (SQLException e) {
logger.error("", e);
}
return t;
}
/**
* 子类需要重写这个方法
*
* @throws SQLException ex
*/
public void remainingMap(T object, ResultSet rs, int rowNumber) throws SQLException {
//Override
}
}
|
923d60604ddde4d9dfbd80417f6c747ff571e5cf | 410 | java | Java | blog-springboot/hua_blog/src/main/java/com/hua/pojo/vo/UserRoleVO.java | LycorisradiataH/personal-blog | 3849e62d1def22aee113910812232df959421f9f | [
"Apache-2.0"
] | 2 | 2021-11-13T14:21:25.000Z | 2022-01-07T03:27:38.000Z | blog-springboot/hua_blog/src/main/java/com/hua/pojo/vo/UserRoleVO.java | LycorisradiataH/personal-blog | 3849e62d1def22aee113910812232df959421f9f | [
"Apache-2.0"
] | null | null | null | blog-springboot/hua_blog/src/main/java/com/hua/pojo/vo/UserRoleVO.java | LycorisradiataH/personal-blog | 3849e62d1def22aee113910812232df959421f9f | [
"Apache-2.0"
] | null | null | null | 13.225806 | 33 | 0.65122 | 1,000,298 | package com.hua.pojo.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 用户角色 vo
* @author Lin Hua
* @version 1.0
* @date 2021/10/18 18:03
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserRoleVO {
/**
* 角色id
*/
private Integer id;
/**
* 角色名
*/
private String roleName;
}
|
923d607887ca2e86a891413474a532e65dff585f | 7,389 | java | Java | intermine/web/main/src/org/intermine/webservice/server/core/JSONService.java | chenyian-nibio/intermine | d8a5403a02b853df42f1b9f0faf2b002ade7568f | [
"PostgreSQL",
"MIT"
] | 4 | 2017-12-22T06:04:46.000Z | 2020-10-05T02:39:07.000Z | intermine/web/main/src/org/intermine/webservice/server/core/JSONService.java | mgijax/intermine | 1caa1cff2df438c4062e2112ac64d627fc98192c | [
"PostgreSQL"
] | 1 | 2019-07-02T01:21:22.000Z | 2019-07-02T01:21:22.000Z | intermine/web/main/src/org/intermine/webservice/server/core/JSONService.java | mgijax/intermine | 1caa1cff2df438c4062e2112ac64d627fc98192c | [
"PostgreSQL"
] | 5 | 2016-08-01T18:54:24.000Z | 2021-04-15T12:43:53.000Z | 31.576923 | 90 | 0.62593 | 1,000,299 | package org.intermine.webservice.server.core;
/*
* Copyright (C) 2002-2017 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringEscapeUtils;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.metadata.Model;
import org.intermine.webservice.server.Format;
import org.intermine.webservice.server.WebService;
import org.intermine.webservice.server.output.JSONFormatter;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* A Service that has specialisations for supplying JSON.
* @author Alex Kalderimis
*
*/
public abstract class JSONService extends WebService
{
protected final BagManager bagManager;
protected final Model model;
private final Map<String, String> kvPairs = new HashMap<String, String>();
/**
* Constructor
* @param im The InterMine configuration object.
*/
public JSONService(InterMineAPI im) {
super(im);
bagManager = im.getBagManager();
model = im.getObjectStore().getModel();
}
@Override
protected void postInit() {
output.setHeaderAttributes(getHeaderAttributes());
}
/**
* @return The key for the results property.
*/
protected String getResultsKey() {
return null;
}
/**
* @return Whether to treat this as a lazy list.
*/
protected boolean lazyList() {
return false;
}
/**
* Get the header attributes to apply to the formatter.
* @return A map from string to object.
*/
protected Map<String, Object> getHeaderAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
String resultsKey = getResultsKey();
if (resultsKey != null) {
String intro = "\"" + resultsKey + "\":";
if (lazyList()) {
intro += "[";
attributes.put(JSONFormatter.KEY_OUTRO, "]");
}
attributes.put(JSONFormatter.KEY_INTRO, intro);
}
if (formatIsJSONP()) {
attributes.put(JSONFormatter.KEY_CALLBACK, getCallback());
}
attributes.put(JSONFormatter.KEY_KV_PAIRS, kvPairs);
return attributes;
}
/**
* Add a key value pair to put in the header of json results.
* @param key An identifier.
* @param value Some piece of data.
*/
protected void addOutputInfo(String key, String value) {
kvPairs.put(key, value);
}
/**
* Output a map of names and values as a JSON object.
* @param mapping the mapping of things to output.
* @param hasMore Whether there is more to come, and thus a comma is required.
*/
protected void addResultItem(Map<String, ? extends Object> mapping, boolean hasMore) {
JSONObject jo = new JSONObject(mapping);
addResultItemInternal(jo, hasMore);
}
/**
* Output a char-sequence as a JSON value.
* @param str The character sequence.
* @param hasMore Whether there are more to come.
*/
protected void addResultValue(CharSequence str, boolean hasMore) {
addResultItemInternal("\"" + String.valueOf(str) + "\"", hasMore);
}
/**
* Output a number as a JSON value.
* @param num The number.
* @param hasMore Whether there are more to come.
*/
protected void addResultValue(Number num, boolean hasMore) {
addResultValueInternal(String.valueOf(num), hasMore);
}
/**
* Output a bool as a JSON value.
* @param bool The boolean.
* @param hasMore Whether there are more.
*/
protected void addResultValue(Boolean bool, boolean hasMore) {
addResultValueInternal(String.valueOf(bool), hasMore);
}
private void addResultValueInternal(String val, boolean hasMore) {
List<String> outputStrings = new ArrayList<String>();
outputStrings.add(val);
if (hasMore) {
outputStrings.add("");
}
output.addResultItem(outputStrings);
}
/**
* @param entries The entries to output
*/
protected void addResultEntries(
Collection<Map.Entry<String, Object>> entries) {
addResultEntries(entries, false);
}
/**
* Output a single entry.
* @param key The key
* @param value The value
* @param hasMore Whether there are more to come.
*/
protected void addResultEntry(String key, Object value, boolean hasMore) {
addResultEntry(new Pair<String, Object>(key, value), hasMore);
}
/**
* Output a single entry.
* @param entry The entry
* @param hasMore Whether there are more to come.
*/
protected void addResultEntry(Map.Entry<String, Object> entry, boolean hasMore) {
addResultEntries(Collections.singleton(entry), hasMore);
}
/**
* Output a bunch of entries.
* @param entries The entries
* @param hasMore Whether there are more of them to come.
*/
@SuppressWarnings("rawtypes")
protected void addResultEntries(
Collection<Map.Entry<String, Object>> entries, boolean hasMore) {
List<String> outputStrings = new ArrayList<String>();
for (Map.Entry<String, Object> entry: entries) {
String key = entry.getKey();
Object value = entry.getValue();
String valStr = null;
if (value == null) {
valStr = "null";
} else if (value instanceof Map) {
valStr = new JSONObject((Map) value).toString();
} else if (value instanceof List) {
valStr = new JSONArray((List) value).toString();
} else if (value instanceof CharSequence) {
valStr = String.format("\"%s\"",
StringEscapeUtils.escapeJava(String.valueOf(value)));
} else if (value instanceof Number || value instanceof Boolean) {
valStr = String.valueOf(value);
}
outputStrings.add(String.format("\"%s\":%s", key, valStr));
}
if (hasMore) {
outputStrings.add("");
}
output.addResultItem(outputStrings);
}
/**
* Output a list of objects as a JSON array.
* @param listing The list of things to output.
* @param hasMore Whether there is more to come, and thus a comma is required.
*/
protected void addResultItem(List<? extends Object> listing, boolean hasMore) {
JSONArray ja = new JSONArray(listing);
addResultItemInternal(ja, hasMore);
}
private void addResultItemInternal(Object obj, boolean hasMore) {
List<String> outputStrings = new ArrayList<String>();
outputStrings.add(String.valueOf(obj));
if (hasMore) {
outputStrings.add(""); // Dummy value used to get a comma printed.
}
output.addResultItem(outputStrings);
}
@Override
protected Format getDefaultFormat() {
return Format.JSON;
}
}
|
923d609322d5a9922df8a61711f4aaa439c8c9da | 5,825 | java | Java | core/src/main/java/com/github/xpenatan/gdx/frame/viewport/EmuEventQueue.java | xpenatan/gdx-frame-viewport | ee6e2b675987fc8a063145dd5c11022b006570e9 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/com/github/xpenatan/gdx/frame/viewport/EmuEventQueue.java | xpenatan/gdx-frame-viewport | ee6e2b675987fc8a063145dd5c11022b006570e9 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/com/github/xpenatan/gdx/frame/viewport/EmuEventQueue.java | xpenatan/gdx-frame-viewport | ee6e2b675987fc8a063145dd5c11022b006570e9 | [
"Apache-2.0"
] | null | null | null | 24.578059 | 92 | 0.647725 | 1,000,300 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.github.xpenatan.gdx.frame.viewport;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.TimeUtils;
/** Queues events that are later passed to the wrapped {@link InputProcessor}.
*
* EDIT - Cloned from original to change private variables to protected
*
* @author Nathan Sweet */
public class EmuEventQueue implements InputProcessor {
static protected final int SKIP = -1;
static protected final int KEY_DOWN = 0;
static protected final int KEY_UP = 1;
static protected final int KEY_TYPED = 2;
static protected final int TOUCH_DOWN = 3;
static protected final int TOUCH_UP = 4;
static protected final int TOUCH_DRAGGED = 5;
static protected final int MOUSE_MOVED = 6;
static protected final int SCROLLED = 7;
private InputProcessor processor;
protected final IntArray queue = new IntArray();
private final IntArray processingQueue = new IntArray();
private long currentEventTime;
public EmuEventQueue () {
}
public EmuEventQueue (InputProcessor processor) {
this.processor = processor;
}
public void setProcessor (InputProcessor processor) {
this.processor = processor;
}
public InputProcessor getProcessor () {
return processor;
}
public void drain () {
synchronized (this) {
if (processor == null) {
queue.clear();
return;
}
processingQueue.addAll(queue);
queue.clear();
}
int[] q = processingQueue.items;
InputProcessor localProcessor = processor;
for (int i = 0, n = processingQueue.size; i < n;) {
int type = q[i++];
currentEventTime = (long)q[i++] << 32 | q[i++] & 0xFFFFFFFFL;
switch (type) {
case SKIP:
i += q[i];
break;
case KEY_DOWN:
localProcessor.keyDown(q[i++]);
break;
case KEY_UP:
localProcessor.keyUp(q[i++]);
break;
case KEY_TYPED:
localProcessor.keyTyped((char)q[i++]);
break;
case TOUCH_DOWN:
localProcessor.touchDown(q[i++], q[i++], q[i++], q[i++]);
break;
case TOUCH_UP:
localProcessor.touchUp(q[i++], q[i++], q[i++], q[i++]);
break;
case TOUCH_DRAGGED:
localProcessor.touchDragged(q[i++], q[i++], q[i++]);
break;
case MOUSE_MOVED:
localProcessor.mouseMoved(q[i++], q[i++]);
break;
case SCROLLED:
localProcessor.scrolled(0, q[i++]);
break;
default:
throw new RuntimeException();
}
}
processingQueue.clear();
}
private synchronized int next (int nextType, int i) {
int[] q = queue.items;
for (int n = queue.size; i < n;) {
int type = q[i];
if (type == nextType) return i;
i += 3;
switch (type) {
case SKIP:
i += q[i];
break;
case KEY_DOWN:
i++;
break;
case KEY_UP:
i++;
break;
case KEY_TYPED:
i++;
break;
case TOUCH_DOWN:
i += 4;
break;
case TOUCH_UP:
i += 4;
break;
case TOUCH_DRAGGED:
i += 3;
break;
case MOUSE_MOVED:
i += 2;
break;
case SCROLLED:
i++;
break;
default:
throw new RuntimeException();
}
}
return -1;
}
private void queueTime () {
long time = TimeUtils.nanoTime();
queue.add((int)(time >> 32));
queue.add((int)time);
}
public synchronized boolean keyDown (int keycode) {
queue.add(KEY_DOWN);
queueTime();
queue.add(keycode);
return false;
}
public synchronized boolean keyUp (int keycode) {
queue.add(KEY_UP);
queueTime();
queue.add(keycode);
return false;
}
public synchronized boolean keyTyped (char character) {
queue.add(KEY_TYPED);
queueTime();
queue.add(character);
return false;
}
public synchronized boolean touchDown (int screenX, int screenY, int pointer, int button) {
queue.add(TOUCH_DOWN);
queueTime();
queue.add(screenX);
queue.add(screenY);
queue.add(pointer);
queue.add(button);
return false;
}
public synchronized boolean touchUp (int screenX, int screenY, int pointer, int button) {
queue.add(TOUCH_UP);
queueTime();
queue.add(screenX);
queue.add(screenY);
queue.add(pointer);
queue.add(button);
return false;
}
public synchronized boolean touchDragged (int screenX, int screenY, int pointer) {
// Skip any queued touch dragged events for the same pointer.
for (int i = next(TOUCH_DRAGGED, 0); i >= 0; i = next(TOUCH_DRAGGED, i + 6)) {
if (queue.get(i + 5) == pointer) {
queue.set(i, SKIP);
queue.set(i + 3, 3);
}
}
queue.add(TOUCH_DRAGGED);
queueTime();
queue.add(screenX);
queue.add(screenY);
queue.add(pointer);
return false;
}
public synchronized boolean mouseMoved (int screenX, int screenY) {
// Skip any queued mouse moved events.
for (int i = next(MOUSE_MOVED, 0); i >= 0; i = next(MOUSE_MOVED, i + 5)) {
queue.set(i, SKIP);
queue.set(i + 3, 2);
}
queue.add(MOUSE_MOVED);
queueTime();
queue.add(screenX);
queue.add(screenY);
return false;
}
@Override
public synchronized boolean scrolled(float amountX, float amountY) {
queue.add(SCROLLED);
queueTime();
queue.add((int)amountY);
return false;
}
public long getCurrentEventTime () {
return currentEventTime;
}
}
|
923d60cc753b625d6525d8616e6c0657287aed04 | 2,036 | java | Java | Assist/app/src/main/java/cn/com/jinke/assist/booter/ProjectPagerAdapter.java | jinke1984/assist | 51c5265d9ba3717821400ad7e304b5ed3fafc4bf | [
"Apache-2.0"
] | null | null | null | Assist/app/src/main/java/cn/com/jinke/assist/booter/ProjectPagerAdapter.java | jinke1984/assist | 51c5265d9ba3717821400ad7e304b5ed3fafc4bf | [
"Apache-2.0"
] | null | null | null | Assist/app/src/main/java/cn/com/jinke/assist/booter/ProjectPagerAdapter.java | jinke1984/assist | 51c5265d9ba3717821400ad7e304b5ed3fafc4bf | [
"Apache-2.0"
] | null | null | null | 21.208333 | 112 | 0.738212 | 1,000,301 | package cn.com.jinke.assist.booter;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import java.util.ArrayList;
/**
* @author zhaojian
* @time 下午5:26:13
* @date 2014-10-28
* @class_name QDWPagerAdapter.java
*/
public abstract class ProjectPagerAdapter<T> extends PagerAdapter
{
protected ArrayList<T> allItem = new ArrayList<T>();
protected LayoutInflater inflater;
protected Context mContext;
protected int mChildCount = 0;
public void setData(ArrayList<T> list)
{
allItem = list;
}
public ArrayList<T> getData()
{
return allItem;
}
public ProjectPagerAdapter(Context context)
{
mContext = context;
inflater = (LayoutInflater) ProjectApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public ProjectPagerAdapter(Context context, ArrayList<T> list)
{
mContext = context;
inflater = (LayoutInflater) ProjectApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
allItem = list;
}
@Override
public void destroyItem(View container, int position, Object object)
{
((ViewPager) container).removeView((View) object);
if (allItem.size() != 0 && position < allItem.size())
{
destoryView(container, position, allItem.get(position));
}
}
@Override
public Object instantiateItem(View container, int position)
{
View view = getView(container, position, allItem.get(position));
((ViewPager) container).addView(view);
return view;
}
@Override
public int getItemPosition(Object object)
{
if (mChildCount > 0)
{
mChildCount--;
return POSITION_NONE;
}
return POSITION_NONE;
}
@Override
public int getCount()
{
return allItem.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1)
{
return arg0 == arg1;
}
abstract public View getView(View container, int position, T t);
abstract public void destoryView(View container, int position, T t);
}
|
923d6138588250254737befc98d9727b15508bd4 | 2,854 | java | Java | app/integration/runtime-springboot/src/test/java/io/syndesis/integration/component/proxy/ComponentProxySplitCollectionTest.java | dlabaj/syndesis-react-poc | 80a9d17c636b9be326ba694f0df17c02b84af342 | [
"Apache-2.0"
] | 4 | 2018-11-19T20:48:52.000Z | 2018-12-04T09:53:45.000Z | app/integration/runtime-springboot/src/test/java/io/syndesis/integration/component/proxy/ComponentProxySplitCollectionTest.java | dlabaj/syndesis-react-poc | 80a9d17c636b9be326ba694f0df17c02b84af342 | [
"Apache-2.0"
] | 359 | 2019-04-10T15:44:34.000Z | 2019-06-14T07:47:44.000Z | app/integration/runtime-springboot/src/test/java/io/syndesis/integration/component/proxy/ComponentProxySplitCollectionTest.java | dlabaj/syndesis-react-poc | 80a9d17c636b9be326ba694f0df17c02b84af342 | [
"Apache-2.0"
] | 14 | 2018-11-01T14:18:46.000Z | 2019-03-05T14:52:54.000Z | 35.234568 | 150 | 0.715487 | 1,000,302 | /*
* Copyright (C) 2016 Red Hat, 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 io.syndesis.integration.component.proxy;
import java.util.Arrays;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spring.boot.CamelAutoConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import io.syndesis.integration.runtime.sb.IntegrationRuntimeAutoConfiguration;
@DirtiesContext
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = {
CamelAutoConfiguration.class,
IntegrationRuntimeAutoConfiguration.class,
ComponentProxySplitCollectionTest.TestConfiguration.class
},
properties = {
"spring.main.banner-mode = off",
"logging.level.io.syndesis.integration.runtime = DEBUG",
"syndesis.integration.runtime.capture.enabled = false",
"syndesis.integration.runtime.enabled = true",
"syndesis.integration.runtime.configuration-location = classpath:/syndesis/integration/component/proxy/ComponentProxySplitCollectionTest.json"
}
)
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public class ComponentProxySplitCollectionTest {
@Autowired
private CamelContext camelContext;
// ***************************
// Test
// ***************************
@Test
public void testSplit() throws InterruptedException {
final ProducerTemplate template = camelContext.createProducerTemplate();
final MockEndpoint mock = camelContext.getEndpoint("mock:result", MockEndpoint.class);
final String[] values = { "a","b","c" };
mock.expectedMessageCount(values.length);
mock.expectedBodiesReceived((Object[])values);
template.sendBody("direct:start", Arrays.asList(values));
mock.assertIsSatisfied();
}
// ***************************
//
// ***************************
@Configuration
public static class TestConfiguration {
}
}
|
923d63505adf0fc173fb2e574bba8cb5d87cb260 | 314 | java | Java | RiskMeter/src/main/java/InvalidIDException.java | Shane-Toma/ENSE375-GroupD | c71d7d9f3224c5ab9f1e38698673861a9d1b2f3f | [
"MIT"
] | 1 | 2021-02-17T05:15:02.000Z | 2021-02-17T05:15:02.000Z | RiskMeter/src/main/java/InvalidIDException.java | Shane-Toma/ENSE375-GroupD | c71d7d9f3224c5ab9f1e38698673861a9d1b2f3f | [
"MIT"
] | null | null | null | RiskMeter/src/main/java/InvalidIDException.java | Shane-Toma/ENSE375-GroupD | c71d7d9f3224c5ab9f1e38698673861a9d1b2f3f | [
"MIT"
] | 2 | 2021-03-11T21:35:46.000Z | 2021-03-29T16:44:03.000Z | 17.444444 | 64 | 0.697452 | 1,000,303 |
import java.io.*;
/**
* This exception is thrown when an invalid patient ID is entered
*
*/
public class InvalidIDException extends Exception{
private String ID;
public InvalidIDException(String ID){
super("\""+ID+"\" is an invalid ID");
this.ID=ID;
}
public String getTheInvalidID(){
return ID;
}
}
|
923d6449ac185b8bb32af5adaf3c574115331b84 | 2,260 | java | Java | 2.JavaCore/src/com/javarush/task/task16/task1632/Solution.java | Ponser2000/JavaRushTasks | e6eb2e8ee2eb7df77273f2f0f860f524400f72a2 | [
"Apache-2.0"
] | null | null | null | 2.JavaCore/src/com/javarush/task/task16/task1632/Solution.java | Ponser2000/JavaRushTasks | e6eb2e8ee2eb7df77273f2f0f860f524400f72a2 | [
"Apache-2.0"
] | null | null | null | 2.JavaCore/src/com/javarush/task/task16/task1632/Solution.java | Ponser2000/JavaRushTasks | e6eb2e8ee2eb7df77273f2f0f860f524400f72a2 | [
"Apache-2.0"
] | null | null | null | 24.565217 | 89 | 0.504867 | 1,000,304 | package com.javarush.task.task16.task1632;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/*
Клубок
*/
public class Solution {
public static List<Thread> threads = new ArrayList<>(5);
static {
threads.add(new ThreadOne());
threads.add(new ThreadTwo());
threads.add(new ThreadThree());
threads.add(new ThreadFour());
threads.add(new ThreadFive());
}
public static void main(String[] args) {
for (Thread thread : threads) {
thread.start();
}
}
public static class ThreadOne extends Thread {
@Override
public void run() {
while (true) {
}
}
}
public static class ThreadTwo extends Thread {
@Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
}
}
public static class ThreadThree extends Thread {
@Override
public void run() {
while (true) {
try {
System.out.println("Ура");
sleep(500);
} catch (InterruptedException e) {
System.out.println("Ура");
}
}
}
}
public static class ThreadFour extends Thread implements Message {
@Override
public void showWarning() {
interrupt();
}
@Override
public void run() {
while (!isInterrupted() ) {
}
}
}
public static class ThreadFive extends Thread {
@Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = "";
int sum = 0;
while (!s.equals("N")) {
try {
s = reader.readLine();
sum += Integer.parseInt(s);
} catch (IOException e) {} catch (NumberFormatException e) {}
}
System.out.println(sum);
}
}
} |
923d64d36ec1a8f292bfd1d03f8015ef515a385c | 613 | java | Java | src/main/java/com/cristph/template/utils/StringUtils.java | cristph/SpringBootTemplate | 22c92e139afb3f5827bac405ea5db0671ab8e901 | [
"Apache-2.0"
] | 1 | 2021-06-19T16:50:52.000Z | 2021-06-19T16:50:52.000Z | src/main/java/com/cristph/template/utils/StringUtils.java | cristph/SpringBootTemplate | 22c92e139afb3f5827bac405ea5db0671ab8e901 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cristph/template/utils/StringUtils.java | cristph/SpringBootTemplate | 22c92e139afb3f5827bac405ea5db0671ab8e901 | [
"Apache-2.0"
] | 1 | 2019-02-13T07:41:24.000Z | 2019-02-13T07:41:24.000Z | 20.433333 | 63 | 0.487765 | 1,000,305 | package com.cristph.template.utils;
import static java.lang.Character.isWhitespace;
public class StringUtils {
/**
* 判断字符串是否为null或者是只包含空格
*
* @param str 待判断字符串
* @return 布尔值
*/
public static boolean isEmptyOrWhitespaceOnly(String str) {
if (str != null && str.length() != 0) {
int length = str.length();
for (int i = 0; i < length; ++i) {
if (!isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
}
|
923d65272db524ab8d8656047cc9289f32420e33 | 2,556 | java | Java | src/net/pbrennan/Lander_2009/RungeKutta4thVecN.java | pmbrennan/lander-2009 | 50157280e4310e358f582f4df303508d41f23046 | [
"MIT"
] | 2 | 2016-09-07T16:41:46.000Z | 2016-11-30T01:29:51.000Z | src/net/pbrennan/Lander_2009/RungeKutta4thVecN.java | pmbrennan/lander-2009 | 50157280e4310e358f582f4df303508d41f23046 | [
"MIT"
] | null | null | null | src/net/pbrennan/Lander_2009/RungeKutta4thVecN.java | pmbrennan/lander-2009 | 50157280e4310e358f582f4df303508d41f23046 | [
"MIT"
] | null | null | null | 29.72093 | 108 | 0.541471 | 1,000,306 | package net.pbrennan.Lander_2009;
/**
* Provides a static method to calculate the 4th order
* Runge-Kutta integration calculation with a vector-valued
* function.
* See http://en.wikipedia.org/wiki/Runge-Kutta_methods#The_common_fourth-order_Runge.E2.80.93Kutta_method
**/
public class RungeKutta4thVecN
{
RungeKutta4thVecN(int size)
{
// Allocate working storage, so we're not doing it
// at every time step
// (therefore avoiding lots of churn on the heap!)
k1 = new HVecN(size);
k2 = new HVecN(size);
k3 = new HVecN(size);
k4 = new HVecN(size);
OneHalfHK1 = new HVecN(size);
OneHalfHK2 = new HVecN(size);
HK3 = new HVecN(size);
YPlusOffset = new HVecN(size);
}
// Given y=f(t), compute f(t+h)
public void step (double t, // Time
double h, // Time Step
HVecN y, // Value of f(t)
IDerivableVec func ) // function
{
double halfH = 0.5 * h;
k1 = func.deriv(t, 0.0, y, k1);
OneHalfHK1.copy(k1);
OneHalfHK1.scale(halfH);
YPlusOffset.copy(y);
YPlusOffset.sum(OneHalfHK1);
//k2 = func.deriv(t, halfH, y.add(OneHalfHK1), k2);
k2 = func.deriv(t, halfH, YPlusOffset, k2);
OneHalfHK2.copy(k2);
OneHalfHK2.scale(halfH);
YPlusOffset.copy(y);
YPlusOffset.sum(OneHalfHK2);
//k3 = func.deriv(t, halfH, y.add(OneHalfHK2), k3);
k3 = func.deriv(t, halfH, YPlusOffset, k3);
HK3.copy(k3);
HK3.scale(h);
YPlusOffset.copy(y);
YPlusOffset.sum(HK3);
//k4 = func.deriv(t, h, y.add(HK3), k4);
k4 = func.deriv(t, h, YPlusOffset, k4);
// compute (1/6)h * (k1 + 2*k2 + 2*k3 + k4)
int size = y.size;
double oneSixthH = h / 6.0;
double nextY;
for (int i=0 ; i<size ; ++i)
{
nextY = y.vec[i]
+ (k1.vec[i]
+ 2.0 * (k2.vec[i] + k3.vec[i])
+ k4.vec[i])
* oneSixthH;
y.vec[i] = nextY;
}
}
// Values of the derivative at four key sampling intervals.
private HVecN k1;
private HVecN k2;
private HVecN k3;
private HVecN k4;
// trial offsets of the function value.
private HVecN OneHalfHK1;
private HVecN OneHalfHK2;
private HVecN HK3;
// trial functionvalue
private HVecN YPlusOffset;
} // RungeKutta4thVecN |
923d653536e6377c06168fabbd7917b6aba8f43f | 275 | java | Java | src/main/java/com/sowell/tools/imp/utils/Row.java | cosmicparticle/cpf-tools | 32524615f35ff19798ce2d2200ef0c294bedcfb5 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/sowell/tools/imp/utils/Row.java | cosmicparticle/cpf-tools | 32524615f35ff19798ce2d2200ef0c294bedcfb5 | [
"Apache-2.0"
] | 3 | 2021-02-03T19:38:07.000Z | 2021-08-02T17:06:47.000Z | src/main/java/com/sowell/tools/imp/utils/Row.java | cosmicparticle/cpf-tools | 32524615f35ff19798ce2d2200ef0c294bedcfb5 | [
"Apache-2.0"
] | null | null | null | 16.176471 | 52 | 0.698182 | 1,000,307 | package com.sowell.tools.imp.utils;
import java.util.ArrayList;
import java.util.List;
public class Row {
private List<String> tds = new ArrayList<String>();
public List<String> getTds() {
return tds;
}
public void setTds(List<String> tds) {
this.tds = tds;
}
}
|
923d653945549e6d6e909992e243066b49233124 | 1,380 | java | Java | plugins/de.fraunhofer.ipa.ros.tests/src/ros/tests/ParameterDateTest.java | erogleva/ros-model | 4b36b490cc065f2c857a59a7d379aabc78fdaa1c | [
"BSD-3-Clause"
] | 28 | 2019-02-05T15:47:26.000Z | 2022-02-21T16:30:36.000Z | plugins/de.fraunhofer.ipa.ros.tests/src/ros/tests/ParameterDateTest.java | erogleva/ros-model | 4b36b490cc065f2c857a59a7d379aabc78fdaa1c | [
"BSD-3-Clause"
] | 101 | 2019-01-29T10:03:39.000Z | 2022-03-21T15:37:16.000Z | plugins/de.fraunhofer.ipa.ros.tests/src/ros/tests/ParameterDateTest.java | erogleva/ros-model | 4b36b490cc065f2c857a59a7d379aabc78fdaa1c | [
"BSD-3-Clause"
] | 11 | 2019-02-06T15:17:23.000Z | 2021-06-10T08:42:39.000Z | 19.43662 | 69 | 0.625362 | 1,000,308 | /**
*/
package ros.tests;
import junit.textui.TestRunner;
import ros.ParameterDate;
import ros.RosFactory;
/**
* <!-- begin-user-doc -->
* A test case for the model object '<em><b>Parameter Date</b></em>'.
* <!-- end-user-doc -->
* @generated
*/
public class ParameterDateTest extends ParameterValueTest {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(ParameterDateTest.class);
}
/**
* Constructs a new Parameter Date test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ParameterDateTest(String name) {
super(name);
}
/**
* Returns the fixture for this Parameter Date test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected ParameterDate getFixture() {
return (ParameterDate)fixture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#setUp()
* @generated
*/
@Override
protected void setUp() throws Exception {
setFixture(RosFactory.eINSTANCE.createParameterDate());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#tearDown()
* @generated
*/
@Override
protected void tearDown() throws Exception {
setFixture(null);
}
} //ParameterDateTest
|
923d65532c8a106450b472fe1cdae8ee6497e476 | 2,715 | java | Java | sources/com/google/android/gms/internal/ads/zzbzt.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | 1 | 2019-10-01T11:34:10.000Z | 2019-10-01T11:34:10.000Z | sources/com/google/android/gms/internal/ads/zzbzt.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | null | null | null | sources/com/google/android/gms/internal/ads/zzbzt.java | tusharchoudhary0003/Custom-Football-Game | 47283462b2066ad5c53b3c901182e7ae62a34fc8 | [
"MIT"
] | 1 | 2020-05-26T05:10:33.000Z | 2020-05-26T05:10:33.000Z | 33.109756 | 103 | 0.627256 | 1,000,309 | package com.google.android.gms.internal.ads;
import android.content.Context;
import android.view.View;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public final class zzbzt {
/* renamed from: a */
private final Context f26219a;
/* renamed from: b */
private final zzcdn f26220b;
/* renamed from: c */
private final zzccj f26221c;
/* renamed from: d */
private final zzbmy f26222d;
/* renamed from: e */
private final zzbzb f26223e;
public zzbzt(Context context, zzcdn zzcdn, zzccj zzccj, zzbmy zzbmy, zzbzb zzbzb) {
this.f26219a = context;
this.f26220b = zzcdn;
this.f26221c = zzccj;
this.f26222d = zzbmy;
this.f26223e = zzbzb;
}
/* renamed from: a */
public final View mo31077a() throws zzbhj {
zzbgz a = this.f26220b.mo31124a(zzyd.m31511a(this.f26219a));
a.getView().setVisibility(8);
a.mo28726a("/sendMessageToSdk", (zzaho<? super zzbgz>) new C9814xh<Object>(this));
a.mo28726a("/adMuted", (zzaho<? super zzbgz>) new C9835yh<Object>(this));
this.f26221c.mo31116a(new WeakReference<>(a), "/loadHtml", (zzaho<T>) new C9856zh<T>(this));
this.f26221c.mo31116a(new WeakReference<>(a), "/showOverlay", (zzaho<T>) new C8747Ah<T>(this));
this.f26221c.mo31116a(new WeakReference<>(a), "/hideOverlay", (zzaho<T>) new C8768Bh<T>(this));
return a.getView();
}
/* access modifiers changed from: 0000 */
/* renamed from: a */
public final /* synthetic */ void mo31078a(zzbgz zzbgz, Map map) {
zzbgz.getView().setVisibility(8);
this.f26222d.mo30748f(false);
}
/* access modifiers changed from: 0000 */
/* renamed from: b */
public final /* synthetic */ void mo31080b(zzbgz zzbgz, Map map) {
zzbgz.getView().setVisibility(0);
this.f26222d.mo30748f(true);
}
/* access modifiers changed from: 0000 */
/* renamed from: a */
public final /* synthetic */ void mo31079a(Map map, boolean z) {
HashMap hashMap = new HashMap();
hashMap.put("messageType", "htmlLoaded");
String str = "id";
hashMap.put(str, (String) map.get(str));
this.f26221c.mo31115a("sendMessageToNativeJs", (Map<String, ?>) hashMap);
}
/* access modifiers changed from: 0000 */
/* renamed from: c */
public final /* synthetic */ void mo31081c(zzbgz zzbgz, Map map) {
this.f26223e.mo30956c();
}
/* access modifiers changed from: 0000 */
/* renamed from: d */
public final /* synthetic */ void mo31082d(zzbgz zzbgz, Map map) {
this.f26221c.mo31115a("sendMessageToNativeJs", map);
}
}
|
923d6669c075712936b61c53cf7461dd8fa9b947 | 3,926 | java | Java | src/main/java/org/rhofman/jpa/unittest/DBUnitBasedTest.java | hofmanr/jpa-unittest | a8ee4b83d4719e871b3562f810ccbbb71a42b3db | [
"Apache-2.0"
] | null | null | null | src/main/java/org/rhofman/jpa/unittest/DBUnitBasedTest.java | hofmanr/jpa-unittest | a8ee4b83d4719e871b3562f810ccbbb71a42b3db | [
"Apache-2.0"
] | null | null | null | src/main/java/org/rhofman/jpa/unittest/DBUnitBasedTest.java | hofmanr/jpa-unittest | a8ee4b83d4719e871b3562f810ccbbb71a42b3db | [
"Apache-2.0"
] | null | null | null | 33.844828 | 113 | 0.633724 | 1,000,310 | package org.rhofman.jpa.unittest;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.hibernate.Session;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.dbunit.database.IDatabaseConnection;
import javax.persistence.EntityManager;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class DBUnitBasedTest extends JpaBasedTest {
private IDatabaseConnection connection;
@BeforeEach
public void setupDBTest() {
createDatabaseProperties();
createDatabase();
initialiseRepository();
beginTransaction();
createTables();
loadData();
commitTransaction();
clearEntityManager();
beginTransaction();
}
@AfterEach
public void teardownDBTest() {
rollback();
close();
}
@Override
protected void createDatabase() {
super.createDatabase();
try {
EntityManager em = getEntityManager();
Connection sqlConnection;
if ("org.eclipse.persistence.internal.jpa.EntityManagerImpl".equals(em.getClass().getName())) {
em.getTransaction().begin();
sqlConnection = em.unwrap(java.sql.Connection.class);
connection = new DatabaseConnection(sqlConnection);
em.getTransaction().commit();
return;
}
if ("org.hibernate.internal.SessionImpl".equals(em.getClass().getName())) {
Session session = em.unwrap(Session.class);
session.doWork(c -> {
try {
connection = new DatabaseConnection(c);
} catch (DatabaseUnitException e) {
// ignore
}
});
return;
}
OpenJPAEntityManager oem = OpenJPAPersistence.cast(getEntityManager());
sqlConnection = (Connection) oem.getConnection();
connection = new DatabaseConnection(sqlConnection);
} catch (DatabaseUnitException e) {
throw new JpaUnitTestException("Error getting database connection for DBUnit: " + e.getMessage(), e);
}
}
@Override
void loadData() {
if (getDatasetFile() == null) {
throw new JpaUnitTestException("No data set present for DBUnit test!");
}
try {
DatabaseOperation.CLEAN_INSERT.execute(connection, getXmlDataSet(getDatasetFile()));
} catch (DatabaseUnitException e) {
throw new JpaUnitTestException("Can not insert data set: " + e.getMessage(), e);
} catch (SQLException throwables) {
throw new JpaUnitTestException("SQL exception occurred.", throwables);
}
}
private IDataSet getXmlDataSet(String dataSource) {
try (InputStream dataSetStream = getClass().getClassLoader().getResourceAsStream(dataSource)) {
FlatXmlDataSetBuilder dataSetBuilder = new FlatXmlDataSetBuilder();
return dataSetBuilder.build(dataSetStream);
} catch (IOException | DataSetException e) {
throw new JpaUnitTestException("Error loading data set " + dataSource, e);
}
}
@Override
protected void close() {
try {
connection.close();
} catch (SQLException throwables) {
throw new IllegalStateException("Can not close connection DBUnit.", throwables);
}
super.close();
}
}
|
923d66bc2ca738a874da1fc5b2d8d356cb97f7ce | 12,350 | java | Java | tesseract/src/main/java/com/baidu/rigel/biplatform/tesseract/isservice/startup/IndexAndSearchStartupListener.java | lxqfirst/bi-platform | 803eda1875796743d335e167b9068d578bd75b0b | [
"Apache-2.0"
] | 3 | 2015-09-29T09:18:58.000Z | 2015-11-24T11:03:03.000Z | tesseract/src/main/java/com/baidu/rigel/biplatform/tesseract/isservice/startup/IndexAndSearchStartupListener.java | lxqfirst/bi-platform | 803eda1875796743d335e167b9068d578bd75b0b | [
"Apache-2.0"
] | null | null | null | tesseract/src/main/java/com/baidu/rigel/biplatform/tesseract/isservice/startup/IndexAndSearchStartupListener.java | lxqfirst/bi-platform | 803eda1875796743d335e167b9068d578bd75b0b | [
"Apache-2.0"
] | null | null | null | 41.442953 | 115 | 0.554089 | 1,000,311 | /**
* Copyright (c) 2014 Baidu, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package com.baidu.rigel.biplatform.tesseract.isservice.startup;
import java.io.File;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import com.baidu.rigel.biplatform.tesseract.isservice.index.service.IndexMetaService;
import com.baidu.rigel.biplatform.tesseract.isservice.meta.IndexMeta;
import com.baidu.rigel.biplatform.tesseract.isservice.meta.IndexShard;
import com.baidu.rigel.biplatform.tesseract.node.meta.Node;
import com.baidu.rigel.biplatform.tesseract.node.meta.NodeState;
import com.baidu.rigel.biplatform.tesseract.node.service.IndexAndSearchServer;
import com.baidu.rigel.biplatform.tesseract.node.service.IsNodeService;
import com.baidu.rigel.biplatform.tesseract.store.service.LocalEventListenerThread;
import com.baidu.rigel.biplatform.tesseract.util.isservice.LogInfoConstants;
/**
* IndexAndSearchStartupListener
*
* @author lijin
*
*/
@Service
public class IndexAndSearchStartupListener implements ApplicationContextAware,
ApplicationListener<ContextRefreshedEvent> {
/**
* LOGGER
*/
private static final Logger LOGGER = LoggerFactory
.getLogger(IndexAndSearchStartupListener.class);
/**
* context
*/
private ApplicationContext context;
/**
* isNodeService
*/
@Resource(name = "isNodeService")
private IsNodeService isNodeService;
@Resource
private IndexMetaService idxMetaService;
/*
* (non-Javadoc)
*
* @see
* org.springframework.context.ApplicationListener#onApplicationEvent(org
* .springframework.context.ApplicationEvent)
*/
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_ON_LISTENER_BEGIN,
"IndexAndSearchStartupListener.onApplicationEvent", event));
if (event == null) {
LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION,
"IndexAndSearchStartupListener.onApplicationEvent", event));
throw new IllegalArgumentException();
}
// 程序初始化结束后
// 启动索引查询服务
IndexAndSearchServer isServer = this.context.getBean(IndexAndSearchServer.class);
isServer.start();
int count = 0;
try {
while (!isServer.isRunning()) {
Thread.sleep(500);
count++;
if (count > 10) {
throw new Exception();
}
}
} catch (Exception e) {
LOGGER.error(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_ERROR,
"IndexAndSearchStartupListener.onApplicationEvent-Server startup failed "), e);
}
if (isServer.isRunning()) {
// 注册信息
if (isServer.getNode() != null) {
isServer.getNode().setNodeState(NodeState.NODE_AVAILABLE);
isServer.getNode().setLastStateUpdateTime(System.currentTimeMillis());
this.isNodeService.saveOrUpdateNodeInfo(isServer.getNode());
}
// 恢复本地镜像
Node currNode = isServer.getNode();
if (currNode != null) {
// 如果本地镜像存在
File localImage = new File(currNode.getImageFilePath());
if (localImage.exists()) {
// 恢复本地元数据
loadLocalInfo(currNode);
}
}
// 启动状态更新&检查线程
ClusterNodeCheckThread clusterNodeCheckThread = this.context
.getBean(ClusterNodeCheckThread.class);
clusterNodeCheckThread.start();
// 启动hz中的queue事件监听
LocalEventListenerThread localListenerThread = this.context
.getBean(LocalEventListenerThread.class);
localListenerThread.start();
} else {
LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_ERROR,
"IndexAndSearchStartupListener.onApplicationEvent-Server is not running ", event));
}
LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_ON_LISTENER_END,
"IndexAndSearchStartupListener.onApplicationEvent", event));
return;
}
/*
* (non-Javadoc)
*
* @see
* org.springframework.context.ApplicationContextAware#setApplicationContext
* (org.springframework.context.ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
private void loadLocalInfo(Node node) {
LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "loadLocalInfo",
"[Node:" + node + "]"));
Node currNode = node;
currNode = this.isNodeService.loadLocalNodeImage(currNode);
// 当前节点不是一个空节点
if (currNode != null && currNode.getUsedIndexShardList() != null) {
for (IndexShard idxShard : currNode.getUsedIndexShardList()) {
IndexMeta idxMeta = idxShard.getIndexMeta();
String cubeId = null;
IndexMeta remoteIndexMeta = null;
if (idxMeta != null && idxMeta.getCubeIdSet() != null
&& idxMeta.getCubeIdSet().size() > 0) {
cubeId = idxMeta.getCubeIdSet().toArray(new String[0])[0];
remoteIndexMeta = this.idxMetaService.getIndexMetaByCubeId(cubeId,
IndexMeta.getDataStoreName());
}
// 由于现有的本地镜像都是在存完后再写的,所以remote的版本一定是最新的
// 两种情况:
// 1、集群中的索引元数据中存在node信息,只不过是node独立的状态被标记为不可用,只需要同步node的信息就可以,不需要fix索引元数据信息
// 2、整个集群都宕掉了,需要重建
if (remoteIndexMeta != null) {
idxMeta = remoteIndexMeta;
// 集群中有一部分数据
IndexShard remoteIdxShard = null;
for (IndexShard iShard : remoteIndexMeta.getIdxShardList()) {
if (iShard.equals(idxShard)) {
remoteIdxShard = iShard;
break;
}
}
remoteIdxShard = updateNodeInfoOfIndexShard(remoteIdxShard, currNode);
// if (remoteIdxShard != null) {
// boolean nodeExist = false;
// if (!CollectionUtils.isEmpty(remoteIdxShard.getReplicaNodeList())) {
// for (Node reNode : remoteIdxShard.getReplicaNodeList()) {
// if (reNode.equals(currNode)) {
// nodeExist = true;
// break;
//
// }
// }
// }
// if (!nodeExist
// && (remoteIdxShard.getNode() != null && !remoteIdxShard.getNode()
// .equals(currNode))) {
// // node在复本中不存在,并且主NODE也不是当前节点;
// remoteIdxShard.getReplicaNodeList().add(currNode);
// } else if (!nodeExist && (remoteIdxShard.getNode() == null)) {
// // node在复本中不存在,并且主NODE为空
// remoteIdxShard.setNode(currNode);
// } else if (nodeExist && (remoteIdxShard.getNode() == null)) {
// // node在复本中存在,且主NODE为空
// remoteIdxShard.setNode(currNode);
// remoteIdxShard.getReplicaNodeList().remove(currNode);
// // node在复本中存在,且主NODE不为当前节点,不用处理
// }
// }
idxMeta = remoteIndexMeta;
} else {
idxShard = updateNodeInfoOfIndexShard(idxShard, currNode);
}
this.idxMetaService.saveOrUpdateIndexMeta(idxMeta);
}
}
LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "loadLocalInfo",
"[Node:" + node + "]"));
}
/**
*
* updateNodeInfoOfIndexShard
*
* @param remoteIdxShard
* remoteIdxShard
* @param currNode
* currNode
* @return IndexShard
*/
private IndexShard updateNodeInfoOfIndexShard(IndexShard remoteIdxShard, Node currNode) {
List<Node> currAvailableNodeList = isNodeService.getAvailableNodeListByClusterName(currNode
.getClusterName());
if (remoteIdxShard != null) {
boolean nodeExist = false;
if (!CollectionUtils.isEmpty(currAvailableNodeList)) {
if (!CollectionUtils.isEmpty(remoteIdxShard.getReplicaNodeList())) {
remoteIdxShard.getReplicaNodeList().retainAll(currAvailableNodeList);
}
if (!currAvailableNodeList.contains(remoteIdxShard.getNode())) {
remoteIdxShard.setNode(null);
}
} else {
remoteIdxShard.getReplicaNodeList().clear();
remoteIdxShard.setNode(null);
}
// 判断是否在复本节点中
if (!CollectionUtils.isEmpty(remoteIdxShard.getReplicaNodeList())) {
for (Node reNode : remoteIdxShard.getReplicaNodeList()) {
if (reNode.equals(currNode)) {
nodeExist = true;
break;
}
}
}
if (!nodeExist
&& (remoteIdxShard.getNode() != null
&& remoteIdxShard.getNode().getNodeState().equals(NodeState.NODE_AVAILABLE) && !remoteIdxShard
.getNode().equals(currNode))) {
// node在复本中不存在,并且主NODE也不是当前节点;
remoteIdxShard.getReplicaNodeList().add(currNode);
} else if (!nodeExist
&& (remoteIdxShard.getNode() == null || !remoteIdxShard.getNode().getNodeState()
.equals(NodeState.NODE_AVAILABLE))) {
// node在复本中不存在,并且主NODE为空
remoteIdxShard.setNode(currNode);
} else if (nodeExist && (remoteIdxShard.getNode() == null)) {
// node在复本中存在,且主NODE为空
remoteIdxShard.setNode(currNode);
remoteIdxShard.getReplicaNodeList().remove(currNode);
// node在复本中存在,且主NODE不为当前节点,不用处理
}
}
return remoteIdxShard;
}
}
|
923d66d57a3560a767b05b756d8faf797162eae8 | 1,075 | java | Java | org/apache/xmlgraphics/xmp/schemas/pdf/AdobePDFAdapter.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | 1 | 2022-02-24T01:32:41.000Z | 2022-02-24T01:32:41.000Z | org/apache/xmlgraphics/xmp/schemas/pdf/AdobePDFAdapter.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | org/apache/xmlgraphics/xmp/schemas/pdf/AdobePDFAdapter.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | 26.875 | 72 | 0.716279 | 1,000,312 | package org.apache.xmlgraphics.xmp.schemas.pdf;
import org.apache.xmlgraphics.xmp.Metadata;
import org.apache.xmlgraphics.xmp.XMPSchemaAdapter;
import org.apache.xmlgraphics.xmp.XMPSchemaRegistry;
public class AdobePDFAdapter extends XMPSchemaAdapter {
private static final String KEYWORDS = "Keywords";
private static final String PDFVERSION = "PDFVersion";
private static final String PRODUCER = "Producer";
public AdobePDFAdapter(Metadata meta, String namespace) {
super(meta, XMPSchemaRegistry.getInstance().getSchema(namespace));
}
public String getKeywords() {
return this.getValue("Keywords");
}
public void setKeywords(String value) {
this.setValue("Keywords", value);
}
public String getPDFVersion() {
return this.getValue("PDFVersion");
}
public void setPDFVersion(String value) {
this.setValue("PDFVersion", value);
}
public String getProducer() {
return this.getValue("Producer");
}
public void setProducer(String value) {
this.setValue("Producer", value);
}
}
|
923d6757310923561f4dc33e7d18b79a8fa5c85a | 4,656 | java | Java | projects/OG-Integration/src/main/java/com/opengamma/integration/marketdata/manipulator/dsl/YieldCurveDataSelectorFudgeBuilder.java | emcleod/OG-Platform | dbd4e1c64907f6a2dd27a62d252e9c61e609f779 | [
"Apache-2.0"
] | 12 | 2017-03-10T13:56:52.000Z | 2021-10-03T01:21:20.000Z | projects/OG-Integration/src/main/java/com/opengamma/integration/marketdata/manipulator/dsl/YieldCurveDataSelectorFudgeBuilder.java | emcleod/OG-Platform | dbd4e1c64907f6a2dd27a62d252e9c61e609f779 | [
"Apache-2.0"
] | 1 | 2021-08-02T17:20:43.000Z | 2021-08-02T17:20:43.000Z | projects/OG-Integration/src/main/java/com/opengamma/integration/marketdata/manipulator/dsl/YieldCurveDataSelectorFudgeBuilder.java | emcleod/OG-Platform | dbd4e1c64907f6a2dd27a62d252e9c61e609f779 | [
"Apache-2.0"
] | 16 | 2017-01-12T10:31:58.000Z | 2019-04-19T08:17:33.000Z | 37.548387 | 109 | 0.719716 | 1,000,313 | /**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.integration.marketdata.manipulator.dsl;
import java.util.Set;
import java.util.regex.Pattern;
import org.fudgemsg.FudgeField;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.MutableFudgeMsg;
import org.fudgemsg.mapping.FudgeBuilder;
import org.fudgemsg.mapping.FudgeBuilderFor;
import org.fudgemsg.mapping.FudgeDeserializer;
import org.fudgemsg.mapping.FudgeSerializer;
import com.google.common.collect.Sets;
import com.opengamma.util.money.Currency;
/**
*
*/
@FudgeBuilderFor(YieldCurveDataSelector.class)
public class YieldCurveDataSelectorFudgeBuilder implements FudgeBuilder<YieldCurveDataSelector> {
private static final String CALC_CONFIGS = "calculationConfigurationNames";
private static final String NAMES = "names";
private static final String CURRENCIES = "currencies";
private static final String NAME_MATCH_PATTERN = "nameMatchPattern";
private static final String NAME_LIKE_PATTERN = "nameLikePattern";
@Override
public MutableFudgeMsg buildMessage(FudgeSerializer serializer, YieldCurveDataSelector selector) {
MutableFudgeMsg msg = serializer.newMessage();
Set<String> calcConfigNames = selector.getCalcConfigNames();
if (calcConfigNames != null) {
MutableFudgeMsg calcConfigsMsg = serializer.newMessage();
for (String calcConfigName : calcConfigNames) {
serializer.addToMessage(calcConfigsMsg, null, null, calcConfigName);
}
serializer.addToMessage(msg, CALC_CONFIGS, null, calcConfigsMsg);
}
if (selector.getNames() != null && !selector.getNames().isEmpty()) {
MutableFudgeMsg namesMsg = serializer.newMessage();
for (String name : selector.getNames()) {
serializer.addToMessage(namesMsg, null, null, name);
}
serializer.addToMessage(msg, NAMES, null, namesMsg);
}
if (selector.getCurrencies() != null && !selector.getCurrencies().isEmpty()) {
MutableFudgeMsg currenciesMsg = serializer.newMessage();
for (Currency currency : selector.getCurrencies()) {
serializer.addToMessage(currenciesMsg, null, null, currency.getCode());
}
serializer.addToMessage(msg, CURRENCIES, null, currenciesMsg);
}
if (selector.getNameMatchPattern() != null) {
serializer.addToMessage(msg, NAME_MATCH_PATTERN, null, selector.getNameMatchPattern().pattern());
}
if (selector.getNameLikePattern() != null) {
serializer.addToMessage(msg, NAME_LIKE_PATTERN, null, selector.getNameLikePattern().pattern());
}
return msg;
}
@Override
public YieldCurveDataSelector buildObject(FudgeDeserializer deserializer, FudgeMsg msg) {
Set<String> calcConfigNames;
if (msg.hasField(CALC_CONFIGS)) {
calcConfigNames = Sets.newHashSet();
FudgeMsg calcConfigsMsg = msg.getMessage(CALC_CONFIGS);
for (FudgeField field : calcConfigsMsg) {
calcConfigNames.add(deserializer.fieldValueToObject(String.class, field));
}
} else {
calcConfigNames = null;
}
FudgeField namesField = msg.getByName(NAMES);
Set<String> names;
if (namesField != null) {
FudgeMsg namesMsg = (FudgeMsg) namesField.getValue();
names = Sets.newHashSet();
for (FudgeField field : namesMsg) {
names.add(deserializer.fieldValueToObject(String.class, field));
}
} else {
names = null;
}
FudgeField currenciesField = msg.getByName(CURRENCIES);
Set<Currency> currencies;
if (currenciesField != null) {
FudgeMsg currenciesMsg = (FudgeMsg) currenciesField.getValue();
currencies = Sets.newHashSet();
for (FudgeField field : currenciesMsg) {
currencies.add(Currency.of(deserializer.fieldValueToObject(String.class, field)));
}
} else {
currencies = null;
}
Pattern nameMatchPattern;
FudgeField namePatternField = msg.getByName(NAME_MATCH_PATTERN);
if (namePatternField != null) {
String regex = deserializer.fieldValueToObject(String.class, namePatternField);
nameMatchPattern = Pattern.compile(regex);
} else {
nameMatchPattern = null;
}
Pattern nameLikePattern;
FudgeField nameLikeField = msg.getByName(NAME_LIKE_PATTERN);
if (nameLikeField != null) {
String regex = deserializer.fieldValueToObject(String.class, nameLikeField);
nameLikePattern = Pattern.compile(regex);
} else {
nameLikePattern = null;
}
return new YieldCurveDataSelector(calcConfigNames, names, currencies, nameMatchPattern, nameLikePattern);
}
}
|
923d68f607984275fd13948f9a192fce959be621 | 1,518 | java | Java | eLMaze-Desktop/core/src/com/mygdx/elmaze/model/levels/LevelModel.java | FilipaDurao/LPOO-eLMaze | b4ed7e2ebe98a6e496f2154dd73f79014b2fa992 | [
"MIT"
] | null | null | null | eLMaze-Desktop/core/src/com/mygdx/elmaze/model/levels/LevelModel.java | FilipaDurao/LPOO-eLMaze | b4ed7e2ebe98a6e496f2154dd73f79014b2fa992 | [
"MIT"
] | null | null | null | eLMaze-Desktop/core/src/com/mygdx/elmaze/model/levels/LevelModel.java | FilipaDurao/LPOO-eLMaze | b4ed7e2ebe98a6e496f2154dd73f79014b2fa992 | [
"MIT"
] | null | null | null | 20.794521 | 73 | 0.710145 | 1,000,314 | package com.mygdx.elmaze.model.levels;
import java.util.ArrayList;
import com.mygdx.elmaze.model.entities.ButtonModel;
import com.mygdx.elmaze.model.entities.DoorModel;
import com.mygdx.elmaze.model.entities.ExitModel;
import com.mygdx.elmaze.model.entities.WallModel;
/**
* Represents a LevelModel
*/
public abstract class LevelModel {
/** Standard Level Width */
public static final int LEVEL_WIDTH = 20;
/** Standard Level Height */
public static final int LEVEL_HEIGHT = LEVEL_WIDTH * 3/4;
protected ArrayList<DoorModel> doors = new ArrayList<DoorModel>();
protected ArrayList<ButtonModel> buttons = new ArrayList<ButtonModel>();
protected ArrayList<WallModel> walls = new ArrayList<WallModel>();
protected ExitModel exit;
public LevelModel() {}
/**
* @return Returns the Level's Door Models
*/
public ArrayList<DoorModel> getDoors() {
return doors;
}
/**
* @return Returns the Level's Button Models
*/
public ArrayList<ButtonModel> getButtons() {
return buttons;
}
/**
* @return Returns the Level's Wall Models
*/
public ArrayList<WallModel> getWalls() {
return walls;
}
/**
* @return Returns the Level's Exit Model
*/
public ExitModel getExit() {
return exit;
}
/**
* Creates the Doors and the Buttons of the Level
*/
protected abstract void createButtonsDoors();
/**
* Creates the Walls of the Level
*/
protected abstract void createWalls();
/**
* Creates the Exit of the Level
*/
protected abstract void createExit();
}
|
923d696a830b3fe45bdfeca28616177eeec7f6d1 | 532 | java | Java | src/com/hourglassapps/cpi_ii/web_search/HttpQuery.java | kieranjwhite/CPI-II | 4d4ac78afefd77c583990b3df558b4e973da454d | [
"Apache-2.0"
] | null | null | null | src/com/hourglassapps/cpi_ii/web_search/HttpQuery.java | kieranjwhite/CPI-II | 4d4ac78afefd77c583990b3df558b4e973da454d | [
"Apache-2.0"
] | null | null | null | src/com/hourglassapps/cpi_ii/web_search/HttpQuery.java | kieranjwhite/CPI-II | 4d4ac78afefd77c583990b3df558b4e973da454d | [
"Apache-2.0"
] | null | null | null | 14.378378 | 51 | 0.693609 | 1,000,315 | package com.hourglassapps.cpi_ii.web_search;
import java.net.URL;
import java.util.List;
import com.hourglassapps.util.Ii;
public class HttpQuery<K> implements Query<K,URL> {
private final K mName;
private final URL mUrl;
public HttpQuery(K pName) {
mName=pName;
mUrl=null;
}
public HttpQuery(K pName, URL pUrl) {
mName=pName;
mUrl=pUrl;
}
@Override
public boolean empty() {
return mUrl==null;
}
@Override
public URL raw() {
return mUrl;
}
@Override
public K uniqueName() {
return mName;
}
} |
923d6a800094a763fc8408f075db940638bbd8f3 | 6,901 | java | Java | benchmark/src/za/co/twyst/tweetnacl/benchmark/ui/crypto/CryptoStreamFragment.java | headuck/tweetnacl-android | 8109d79378ee83d60df013a0fcf1de7af7ac0e6b | [
"Unlicense"
] | 5 | 2015-01-08T16:49:32.000Z | 2020-05-26T05:53:11.000Z | benchmark/src/za/co/twyst/tweetnacl/benchmark/ui/crypto/CryptoStreamFragment.java | headuck/tweetnacl-android | 8109d79378ee83d60df013a0fcf1de7af7ac0e6b | [
"Unlicense"
] | 3 | 2016-12-14T07:02:58.000Z | 2019-01-12T04:44:15.000Z | benchmark/src/za/co/twyst/tweetnacl/benchmark/ui/crypto/CryptoStreamFragment.java | headuck/tweetnacl-android | 8109d79378ee83d60df013a0fcf1de7af7ac0e6b | [
"Unlicense"
] | 2 | 2016-03-25T16:44:48.000Z | 2019-01-11T00:05:04.000Z | 36.707447 | 109 | 0.500797 | 1,000,316 | package za.co.twyst.tweetnacl.benchmark.ui.crypto;
import java.util.Random;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import za.co.twyst.tweetnacl.TweetNaCl;
import za.co.twyst.tweetnacl.benchmark.R;
import za.co.twyst.tweetnacl.benchmark.entity.Measured;
import za.co.twyst.tweetnacl.benchmark.entity.Benchmark.TYPE;
import za.co.twyst.tweetnacl.benchmark.ui.widgets.Grid;
public class CryptoStreamFragment extends CryptoFragment {
// CONSTANTS
@SuppressWarnings("unused")
private static final String TAG = CryptoStreamFragment.class.getSimpleName();
private static final int MESSAGE_SIZE = 16384;
private static final int LOOPS = 1024;
private static final int[] ROWS = { R.string.results_measured,
R.string.results_average,
R.string.results_min,
R.string.results_max
};
private static final int[] COLUMNS = { R.string.column_stream_xor,
R.string.column_stream_salsa20_xor
};
// CLASS METHODS
/** Factory constructor for CryptoBoxFragment that ensures correct fragment
* initialisation.
*
* @return Initialised CryptoBoxFragment or <code>null</code>.
*/
public static Fragment newFragment() {
return new CryptoStreamFragment();
}
// CONSTRUCTOR
public CryptoStreamFragment() {
super(R.layout.fragment_stream,
new Measured(TYPE.CRYPTO_STREAM_XOR),new Measured(TYPE.CRYPTO_STREAM_SALSA20_XOR));
}
// *** Fragment ***
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
final View root = super.onCreateView(inflater,container,state);
final EditText size = (EditText) root.findViewById(R.id.size);
final EditText loops = (EditText) root.findViewById(R.id.loops);
final Button run = (Button) root.findViewById(R.id.run);
final Grid grid = (Grid) root.findViewById(R.id.grid);
final ProgressBar bar = (ProgressBar) root.findViewById(R.id.progressbar);
// ... initialise default setup
size.setText (Integer.toString(MESSAGE_SIZE));
loops.setText(Integer.toString(LOOPS));
// ... initialise grid
grid.setRowLabels (ROWS, inflater,R.layout.label,R.id.textview);
grid.setColumnLabels(COLUMNS,inflater,R.layout.value,R.id.textview);
grid.setValues (ROWS.length,COLUMNS.length,inflater,R.layout.value,R.id.textview);
// ... attach handlers
run.setOnClickListener(new OnClickListener()
{ @Override
public void onClick(View view)
{ try
{ int _size = Integer.parseInt(size.getText ().toString());
int _loops = Integer.parseInt(loops.getText().toString());
hideKeyboard(size,loops);
run (_size,_loops,bar);
}
catch(Throwable x)
{ // IGNORE
}
}
});
return root;
}
// INTERNAL
private void run(int bytes,int loops,ProgressBar bar) {
new CryptoSecretBoxTask(this,bar,bytes,loops).execute();
}
// INNER CLASSES
private static class CryptoSecretBoxTask extends CryptoTask {
private final int bytes;
private final int loops;
private final TweetNaCl tweetnacl;
private CryptoSecretBoxTask(CryptoStreamFragment fragment,ProgressBar bar,int bytes,int loops) {
super(fragment,bar);
this.bytes = bytes;
this.loops = loops;
this.tweetnacl = new TweetNaCl();
}
@Override
protected Result[] doInBackground(Void... params) {
try {
// ... initialise
Random random = new Random();
Result[] results = new Result[2];
byte[] message = new byte[bytes];
byte[] crypttext;
byte[] key;
byte[] nonce;
long start;
long total;
int progress;
// ... crypto_stream_xor
key = new byte[TweetNaCl.STREAM_KEYBYTES];
nonce= new byte[TweetNaCl.STREAM_NONCEBYTES];
random.nextBytes(key);
random.nextBytes(message);
start = System.currentTimeMillis();
total = 0;
progress = 0;
for (int i=0; i<loops; i++)
{ crypttext = tweetnacl.cryptoStreamXor(message,nonce,key);
total += crypttext.length;
progress(++progress,2*loops);
}
results[0] = new Result(total,System.currentTimeMillis() - start);
// ... crypto_stream_salsa20
key = new byte[TweetNaCl.STREAM_SALSA20_KEYBYTES];
nonce = new byte[TweetNaCl.STREAM_SALSA20_NONCEBYTES];
random.nextBytes(key);
random.nextBytes(message);
start = System.currentTimeMillis();
total = 0;
for (int i=0; i<loops; i++)
{ crypttext = tweetnacl.cryptoStreamSalsa20Xor(message, nonce, key);
total += crypttext.length;
progress(++progress,2*loops);
}
results[1] = new Result(total,System.currentTimeMillis() - start);
// ... done
return results;
} catch(Throwable x) {
}
return null;
}
}
}
|
923d6b2b773d220f4473d5a7524d56e26c41e031 | 1,776 | java | Java | core/src/test/java/org/infinispan/atomic/LocalDeltaAwarePassivationTest.java | xiaodong-xie/infinispan | 13d7f252e1f332c7aa178e665f6fd79ce5a1ab64 | [
"Apache-2.0"
] | 1 | 2020-06-01T21:20:47.000Z | 2020-06-01T21:20:47.000Z | core/src/test/java/org/infinispan/atomic/LocalDeltaAwarePassivationTest.java | gustavolira/infinispan | ea7c44e210b9366ef832d80c462cd80899e85446 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/infinispan/atomic/LocalDeltaAwarePassivationTest.java | gustavolira/infinispan | ea7c44e210b9366ef832d80c462cd80899e85446 | [
"Apache-2.0"
] | null | null | null | 43.341463 | 111 | 0.792909 | 1,000,317 | package org.infinispan.atomic;
import static org.testng.AssertJUnit.assertEquals;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.container.DataContainer;
import org.infinispan.persistence.PersistenceUtil;
import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder;
import org.infinispan.persistence.spi.AdvancedCacheLoader;
import org.infinispan.test.TestingUtil;
import org.infinispan.test.fwk.CleanupAfterMethod;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
/**
* @author envkt@example.com
* @since 5.3
*/
@Test(groups = "functional", testName = "atomic.LocalDeltaAwarePassivationTest")
@CleanupAfterMethod
public class LocalDeltaAwarePassivationTest extends LocalDeltaAwareEvictionTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder configBuilder = TestCacheManagerFactory.getDefaultCacheConfiguration(true);
configBuilder.memory().size(1)
.persistence().passivation(true).addStore(DummyInMemoryStoreConfigurationBuilder.class);
configBuilder.clustering().hash().groups().enabled();
addClusterEnabledCacheManager(configBuilder);
}
@Override
protected void assertNumberOfEntries(int cacheIndex, DeltaAwareAccessor daa) throws Exception {
AdvancedCacheLoader cacheStore = (AdvancedCacheLoader) TestingUtil.getCacheLoader(cache(cacheIndex));
assertEquals(daa.isFineGrained() ? 5 : 1, PersistenceUtil.count(cacheStore, null)); // one entry in store
DataContainer dataContainer = cache(cacheIndex).getAdvancedCache().getDataContainer();
assertEquals(1, dataContainer.size()); // only one entry in memory (the other one was evicted)
}
}
|
923d6ccfb8268c5187bca9fe965b4ee7e599ce32 | 2,551 | java | Java | ng-portfolio-core/src/main/java/com/bindstone/portfolio/service/impl/AbstractServiceImpl.java | bindstone/ng-portfolio | cff94d88cbded5e4af9a64dab889d63ae9b93e23 | [
"MIT"
] | null | null | null | ng-portfolio-core/src/main/java/com/bindstone/portfolio/service/impl/AbstractServiceImpl.java | bindstone/ng-portfolio | cff94d88cbded5e4af9a64dab889d63ae9b93e23 | [
"MIT"
] | null | null | null | ng-portfolio-core/src/main/java/com/bindstone/portfolio/service/impl/AbstractServiceImpl.java | bindstone/ng-portfolio | cff94d88cbded5e4af9a64dab889d63ae9b93e23 | [
"MIT"
] | null | null | null | 26.572917 | 111 | 0.658565 | 1,000,318 | package com.bindstone.portfolio.service.impl;
import com.bindstone.portfolio.exceptions.Messages;
import com.bindstone.portfolio.service.AbstractService;
import com.bindstone.portfolio.validator.DefaultObjectServiceValidator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.Validate;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* General Abstract CRUD Service
*
* @param <T> Generic Object
*/
@Slf4j
public abstract class AbstractServiceImpl<T> implements AbstractService<T> {
private CrudRepository crudRepository;
private DefaultObjectServiceValidator validator;
/**
* Constructor
*
* @param crudRepository CRUD Repository
* @param validator validator
*/
public AbstractServiceImpl(CrudRepository crudRepository, DefaultObjectServiceValidator validator) {
this.crudRepository = crudRepository;
this.validator = validator;
}
/**
* Get By ID
* @param id ID
* @return Reactive Mono Object
*/
@Override
@Transactional(readOnly = true)
public Mono<T> getById(Long id) {
log.debug("find by id [{}]", id);
return Mono.justOrEmpty(crudRepository.findById(id));
}
/**
* Get All
* @return Reactive Flux list of Objects
*/
@Override
@Transactional(readOnly = true)
public Flux<T> getAll() {
log.debug("Find all");
return Flux.fromIterable(crudRepository.findAll());
}
/**
* Save Object
* @param object object
* @return object (in case of create with new ID)
*/
@Override
@Transactional
public T save(T object) {
validator.onSave(object);
log.debug("Save object [{}]", object);
return (T) crudRepository.save(object);
}
/**
* Delete object
* @param object object
*/
@Override
@Transactional
public void delete(T object) {
log.debug("Delete object [{}]", object);
crudRepository.delete(object);
}
/**
* Delete object by id
*
* @param id object
*/
@Override
@Transactional
public void deleteById(Long id) {
log.debug("Delete object [{}]", id);
T byId = this.getById(id).block();
Validate.notNull(byId, Messages.DELETE_ID_WITHOUT_OBJECT.message(), Messages.DELETE_ID_WITHOUT_OBJECT);
crudRepository.delete(byId);
}
}
|
923d6cd892cdea99f46e3d01297a611faa27c849 | 40,311 | java | Java | src/test/java/fiuba/algo3/TP2/MovimientosUnidadesTest.java | AgustinLeguizamon/AlgoChess- | c85b0322a3cd43a3d99da2acbe355e28693bdd37 | [
"MIT"
] | null | null | null | src/test/java/fiuba/algo3/TP2/MovimientosUnidadesTest.java | AgustinLeguizamon/AlgoChess- | c85b0322a3cd43a3d99da2acbe355e28693bdd37 | [
"MIT"
] | null | null | null | src/test/java/fiuba/algo3/TP2/MovimientosUnidadesTest.java | AgustinLeguizamon/AlgoChess- | c85b0322a3cd43a3d99da2acbe355e28693bdd37 | [
"MIT"
] | 1 | 2021-05-21T14:26:38.000Z | 2021-05-21T14:26:38.000Z | 33.676692 | 124 | 0.665749 | 1,000,319 | package fiuba.algo3.TP2;
import fiuba.algo3.TP2.Modelo.AlgoChess.Jugador;
import fiuba.algo3.TP2.Modelo.Excepciones.*;
import fiuba.algo3.TP2.Modelo.Tablero.Tablero;
import fiuba.algo3.TP2.Modelo.Unidad.Soldado;
import fiuba.algo3.TP2.Modelo.Unidad.Unidad;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
public class MovimientosUnidadesTest {
/* Norte */
@Test
public void testSoldadoEnTableroSeMueveAlNorteYLoOcupaConExito(){
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 0);
Assertions.assertTrue(tablero.estaOcupado(0,1));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testJineteEnTableroSeMueveAlNorteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 0);
Assertions.assertTrue(tablero.estaOcupado(0,1));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCuranderoEnTableroSeMueveAlNorteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("curandero",1,1);
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,0);
Assertions.assertTrue(tablero.estaOcupado(0,1));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCatapultaNoSeMueveAlNorte() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("catapulta",1,1);
Assertions.assertThrows(UnidadNoMovibleException.class, () -> jugador.moverUnidad(1, 1, 0));
}
/* Este */
@Test
public void testSoldadoEnTableroSeMueveAlesteYLoOcupaConExito(){
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,2);
Assertions.assertTrue(tablero.estaOcupado(1,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testJineteEnTableroSeMueveAlesteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,2);
Assertions.assertTrue(tablero.estaOcupado(1,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCuranderoEnTableroSeMueveAlEsteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("curandero",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,2);
Assertions.assertTrue(tablero.estaOcupado(1,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCatapultaNoSeMueveAlEste() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("catapulta",1,1);
Assertions.assertThrows(UnidadNoMovibleException.class,
() -> jugador.moverUnidad(1, 1, 2));
}
/* Sureste */
@Test
public void testSoldadoEnTableroSeMueveAlSuresteYLoOcupaConExito(){
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,3);
Assertions.assertTrue(tablero.estaOcupado(2,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testJineteEnTableroSeMueveAlSuresteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,3);
Assertions.assertTrue(tablero.estaOcupado(2,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCuranderoEnTableroSeMueveAlSuresteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("curandero",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 3);
Assertions.assertTrue(tablero.estaOcupado(2,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCatapultaNoSeMueveAlSureste() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("catapulta",1,1);
Assertions.assertThrows(UnidadNoMovibleException.class,
() -> jugador.moverUnidad(1, 1, 3));
}
/* Noreste */
@Test
public void testSoldadoEnTableroSeMueveAlNoresteYLoOcupaConExito(){
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 1);
Assertions.assertTrue(tablero.estaOcupado(0,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testJineteEnTableroSeMueveAlNoresteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,1);
Assertions.assertTrue(tablero.estaOcupado(0,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCuranderoEnTableroSeMueveAlNoresteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("curandero",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,1);
Assertions.assertTrue(tablero.estaOcupado(0,2));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCatapultaNoSeMueveAlNoreste() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("catapulta",1,1);
Assertions.assertThrows(UnidadNoMovibleException.class,
() -> jugador.moverUnidad(1, 1, 1));
}
/* Sur */
@Test
public void testSoldadoEnTableroSeMueveAlSurYLoOcupaConExito(){
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 4);
Assertions.assertTrue(tablero.estaOcupado(2,1));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testJineteEnTableroSeMueveAlSurYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,4);
Assertions.assertTrue(tablero.estaOcupado(2,1));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCuranderoEnTableroSeMueveAlSurYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("curandero",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 4);
Assertions.assertTrue(tablero.estaOcupado(2,1));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCatapultaNoSeMueveAlSur() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("catapulta",1,1);
Assertions.assertThrows(UnidadNoMovibleException.class,
() -> jugador.moverUnidad(1, 1, 4));
}
/* Suroeste */
@Test
public void testSoldadoEnTableroSeMueveAlSuroesteYLoOcupaConExito(){
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 5);
Assertions.assertTrue(tablero.estaOcupado(2,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testJineteEnTableroSeMueveAlSuroesteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 5);
Assertions.assertTrue(tablero.estaOcupado(2,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCuranderoEnTableroSeMueveAlSuroesteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("curandero",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 5);
Assertions.assertTrue(tablero.estaOcupado(2,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCatapultaNoSeMueveAlSuroeste() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("catapulta",1,1);
Assertions.assertThrows(UnidadNoMovibleException.class,
() -> jugador.moverUnidad(1, 1, 5));
}
/* Oeste */
@Test
public void testSoldadoEnTableroSeMueveAlOesteYLoOcupaConExito(){
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 6);
Assertions.assertTrue(tablero.estaOcupado(1,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testJineteEnTableroSeMueveAOesteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,6);
Assertions.assertTrue(tablero.estaOcupado(1,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCuranderoEnTableroSeMueveAlOesteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("curandero",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1, 6);
Assertions.assertTrue(tablero.estaOcupado(1,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCatapultaNoSeMueveAlOeste() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("catapulta",1,1);
Assertions.assertThrows(UnidadNoMovibleException.class,
() -> jugador.moverUnidad(1, 1, 6));
}
/* NorOeste */
@Test
public void testSoldadoEnTableroSeMueveAlNorOesteYLoOcupaConExito(){
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,7);
Assertions.assertTrue(tablero.estaOcupado(0,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testJineteEnTableroSeMueveAlNorOesteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,7);
Assertions.assertTrue(tablero.estaOcupado(0,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCuranderoEnTableroSeMueveAlNorOesteYLoOcupaConExito() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("curandero",1,1);
jugador.resetMovimientoUnidades();
jugador.resetMovimientoUnidades();
jugador.moverUnidad(1,1,7);
Assertions.assertTrue(tablero.estaOcupado(0,0));
Assertions.assertFalse(tablero.estaOcupado(1,1));
}
@Test
public void testCatapultaNoSeMueveAlNoOreste() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("catapulta",1,1);
Assertions.assertThrows(UnidadNoMovibleException.class,
() -> jugador.moverUnidad(1, 1, 7));
}
@Test
public void testUnidadNoPuedeMoverseAUnEspacioOcupado() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("jinete",1,1);
jugador.comprarUnidad("jinete",0,0);
jugador.resetMovimientoUnidades();
Assertions.assertThrows(CasilleroEstaOcupadoException.class,
() -> jugador.moverUnidad(1,1,7));
}
@Test
public void testJugadorAliadoTrataDeMoverUnaUnidadQueNoEstaEnElCasilleroYNoPuede() {
Tablero tablero = new Tablero();
Jugador jugador = new Jugador("Juan", tablero);
jugador.comprarUnidad("soldado",1,1);
jugador.resetMovimientoUnidades();
Assertions.assertThrows(NoHayUnidadEnCasilleroException.class,
() -> jugador.moverUnidad(3,3,0));
}
@Test
public void testJugadorNoPuedeMoverUnidadEnemiga() {
Tablero tablero = new Tablero();
Jugador jugador1 = new Jugador("Juan", tablero);
Jugador jugador2 = new Jugador("Pedro", tablero);
jugador1.comprarUnidad("jinete", 9, 10);
jugador1.resetMovimientoUnidades();
tablero.cambiarEstado();
jugador1.resetMovimientoUnidades();
jugador2.comprarUnidad("jinete", 11, 12);
jugador2.resetMovimientoUnidades();
tablero.cambiarEstado();
jugador2.resetMovimientoUnidades();
Assertions.assertThrows(CasilleroSeleccionadoNoPoseeNingunaUnidadAliadaException.class,
() -> jugador1.moverUnidad(11,12,0));
}
@Test
public void testJugadorAliadoMueveUnSoldadoQueTieneOtrosDosAdyacentesYLosTresSeMuevenALaVez() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",2,5);
jugadorAliado.comprarUnidad("soldado",2,6);
jugadorAliado.comprarUnidad("soldado",2,7);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(2,6,0);
Assertions.assertFalse(tablero.estaOcupado(2,5));
Assertions.assertFalse(tablero.estaOcupado(2,6));
Assertions.assertFalse(tablero.estaOcupado(2,7));
Assertions.assertTrue(tablero.estaOcupado(1,5));
Assertions.assertTrue(tablero.estaOcupado(1,6));
Assertions.assertTrue(tablero.estaOcupado(1,7));
}
@Test
public void testJugadorAliadoMueveUnSoldadoQueTieneSoloUnoAdyacenteYElOtroNoSeMueve() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",2,5);
jugadorAliado.comprarUnidad("soldado",2,6);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(2,5,0);
Assertions.assertTrue(tablero.estaOcupado(1,5));
Assertions.assertFalse(tablero.estaOcupado(1,6));
Assertions.assertTrue(tablero.estaOcupado(2,6));
}
@Test
public void testJugadorAliadoMueveUnSoldadoQueTieneUnoSoloAdyacentePeroEsteTieneOtroAdyacentePorLoQueSeMuevenLosTres() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",2,5);
jugadorAliado.comprarUnidad("soldado",2,6);
jugadorAliado.comprarUnidad("soldado",2,7);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.resetMovimientoUnidades();
//tablero.imprimirTablero();
jugadorAliado.moverUnidad(2,5,0);
//tablero.imprimirTablero();
Assertions.assertFalse(tablero.estaOcupado(2,5));
Assertions.assertFalse(tablero.estaOcupado(2,6));
Assertions.assertFalse(tablero.estaOcupado(2,7));
Assertions.assertTrue(tablero.estaOcupado(1,5));
Assertions.assertTrue(tablero.estaOcupado(1,6));
Assertions.assertTrue(tablero.estaOcupado(1,7));
}
@Test
public void testJugadorAliadoMueveUnBatallonEnColumnaHaciaElNorteYCadaUnoOcupaSuNuevoCasilleroConExito(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
tablero.cambiarEstado();
jugadorAliado.comprarUnidad("soldado",14,5);
jugadorAliado.comprarUnidad("soldado",15,5);
jugadorAliado.comprarUnidad("soldado",16,5);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(14,5,0);
Assertions.assertFalse(tablero.estaOcupado(16,5));
Assertions.assertTrue(tablero.estaOcupado(13,5));
Assertions.assertTrue(tablero.estaOcupado(14,5));
Assertions.assertTrue(tablero.estaOcupado(15,5));
}
@Test
public void testJugadorAliadoMueveUnBatallonEnFilaHaciaElEsteYCadaUnoOcupaSuNuevoCasilleroConExito(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
tablero.cambiarEstado();
jugadorAliado.comprarUnidad("soldado",14,5);
jugadorAliado.comprarUnidad("soldado",14,6);
jugadorAliado.comprarUnidad("soldado",14,7);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(14,7,2);
Assertions.assertFalse(tablero.estaOcupado(14,5));
Assertions.assertTrue(tablero.estaOcupado(14,6));
Assertions.assertTrue(tablero.estaOcupado(14,7));
Assertions.assertTrue(tablero.estaOcupado(14,8));
}
@Test
public void testJugadorAliadoMueveUnBatallonEnColumnaHaciaElSurYCadaUnoOcupaSuNuevoCasilleroConExito(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
tablero.cambiarEstado();
jugadorAliado.comprarUnidad("soldado",14,5);
jugadorAliado.comprarUnidad("soldado",15,5);
jugadorAliado.comprarUnidad("soldado",16,5);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(14,5,4);
Assertions.assertFalse(tablero.estaOcupado(14,5));
Assertions.assertTrue(tablero.estaOcupado(15,5));
Assertions.assertTrue(tablero.estaOcupado(16,5));
Assertions.assertTrue(tablero.estaOcupado(17,5));
}
@Test
public void testJugadorAliadoMueveUnBatallonEnFilaHaciaElOesteYCadaUnoOcupaSuNuevoCasilleroConExito(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
tablero.cambiarEstado();
jugadorAliado.comprarUnidad("soldado",14,5);
jugadorAliado.comprarUnidad("soldado",14,6);
jugadorAliado.comprarUnidad("soldado",14,7);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(14,5,6);
Assertions.assertFalse(tablero.estaOcupado(14,7));
Assertions.assertTrue(tablero.estaOcupado(14,4));
Assertions.assertTrue(tablero.estaOcupado(14,5));
Assertions.assertTrue(tablero.estaOcupado(14,6));
}
@Test
public void testJugadorAliadoMueveUnBatallonHaciaElNoresteYCadaUnoOcupaSuNuevoCasilleroConExito(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
tablero.cambiarEstado();
jugadorAliado.comprarUnidad("soldado",14,5);
jugadorAliado.comprarUnidad("soldado",13,6);
jugadorAliado.comprarUnidad("soldado",14,7);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(14,5,1);
Assertions.assertTrue(tablero.estaOcupado(13,6));
Assertions.assertTrue(tablero.estaOcupado(12,7));
Assertions.assertTrue(tablero.estaOcupado(13,8));
}
@Test
public void testJugadorAliadoMueveUnBatallonHaciaElSuresteYCadaUnoOcupaSuNuevoCasilleroConExito(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
tablero.cambiarEstado();
jugadorAliado.comprarUnidad("soldado",12,5);
jugadorAliado.comprarUnidad("soldado",11,6);
jugadorAliado.comprarUnidad("soldado",10,7);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(10,7,3);
Assertions.assertTrue(tablero.estaOcupado(13,6));
Assertions.assertTrue(tablero.estaOcupado(12,7));
Assertions.assertTrue(tablero.estaOcupado(11,8));
}
@Test
public void testJugadorAliadoMueveUnBatallonHaciaElSuroesteYCadaUnoOcupaSuNuevoCasilleroConExito(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",4,3);
jugadorAliado.comprarUnidad("soldado",5,4);
jugadorAliado.comprarUnidad("soldado",6,5);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(4,3,5);
Assertions.assertTrue(tablero.estaOcupado(5,2));
Assertions.assertTrue(tablero.estaOcupado(6,3));
Assertions.assertTrue(tablero.estaOcupado(7,4));
}
@Test
public void testJugadorAliadoMueveUnBatallonHaciaElNoroesteYCadaUnoOcupaSuNuevoCasilleroConExito(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("soldado",7,6);
jugadorAliado.comprarUnidad("soldado",8,7);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(8,7,7);
Assertions.assertTrue(tablero.estaOcupado(6,4));
Assertions.assertTrue(tablero.estaOcupado(6,5));
Assertions.assertTrue(tablero.estaOcupado(7,6));
}
@Test
public void testJugadorAliadoMueveUnSoldadoQueNoConformaUnBatallonYLosOtrosSoldadosNoSeMueven(){
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado",9,5);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(7,5,0);
Assertions.assertTrue(tablero.estaOcupado(6,5));
Assertions.assertTrue(tablero.estaOcupado(7,7));
Assertions.assertTrue(tablero.estaOcupado(9,5));
}
@Test
public void testJugadorMueveUnBatallonDeHastaTresSoldadosComoMaximoYElCuartoNoSeMueve() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus", tablero);
jugadorAliado.comprarUnidad("soldado", 6, 5);
jugadorAliado.comprarUnidad("soldado", 7, 5);
jugadorAliado.comprarUnidad("soldado", 8, 6);
jugadorAliado.comprarUnidad("soldado", 9, 6);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(6, 5, 0);
Assertions.assertTrue(tablero.estaOcupado(5, 5));
Assertions.assertTrue(tablero.estaOcupado(6, 5));
Assertions.assertTrue(tablero.estaOcupado(7, 6));
Assertions.assertFalse(tablero.estaOcupado(8, 6));
Assertions.assertTrue(tablero.estaOcupado(7, 6));
}
@Test
public void testJugadorMueveUnSoldadoYSoloLosDosAdyacentesInmediatosSeMueven() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus", tablero);
jugadorAliado.comprarUnidad("soldado", 6, 4);
jugadorAliado.comprarUnidad("soldado", 6, 5);
jugadorAliado.comprarUnidad("soldado", 7, 5);
jugadorAliado.comprarUnidad("soldado", 7, 6);
jugadorAliado.comprarUnidad("soldado", 8, 6);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(7, 5, 2);
Assertions.assertFalse(tablero.estaOcupado(6, 5));
Assertions.assertTrue(tablero.estaOcupado(6, 6));
Assertions.assertTrue(tablero.estaOcupado(7, 6));
Assertions.assertTrue(tablero.estaOcupado(7, 7));
Assertions.assertFalse(tablero.estaOcupado(8, 7));
}
@Test
public void testJugadorAliadoMueveUnBatallonDeTresSoldadosQueTienenJinetesAdyacentesPeroEstosNoSeMueven() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus", tablero);
jugadorAliado.comprarUnidad("soldado", 6, 4);
jugadorAliado.comprarUnidad("soldado", 6, 5);
jugadorAliado.comprarUnidad("soldado", 7, 5);
jugadorAliado.comprarUnidad("jinete", 7, 3);
jugadorAliado.comprarUnidad("jinete", 8, 6);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(6, 4, 2);
Assertions.assertTrue(tablero.estaOcupado(6, 5));
Assertions.assertTrue(tablero.estaOcupado(6, 6));
Assertions.assertTrue(tablero.estaOcupado(7, 6));
Assertions.assertFalse(tablero.estaOcupado(7, 7));
Assertions.assertFalse(tablero.estaOcupado(8, 7));
}
@Test
public void testBatallonDeCuatroSoldadosSeMuevenSoloTres() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("soldado",7,6);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado", 7,8);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(7,6,4);
Assertions.assertTrue(tablero.estaOcupado(8,5));
Assertions.assertTrue(tablero.estaOcupado(8,6));
Assertions.assertTrue(tablero.estaOcupado(8,7));
Assertions.assertTrue(tablero.estaOcupado(7,8));
}
@Test
public void testJugadorAliadoMueveUnBatallonConUnObstaculoSeMuevenDosYUnoNo() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,6);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("jinete", 8,5);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(7,7,4);
Assertions.assertTrue(tablero.estaOcupado(8,6));
Assertions.assertTrue(tablero.estaOcupado(8,7));
Assertions.assertTrue(tablero.estaOcupado(7,5));
Assertions.assertTrue(tablero.estaOcupado(8,5));
}
@Test
public void testSeDisuelveElBatallonLuegoDeQueUnSoldadoSeTopeConUnObstaculo() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,6);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("jinete", 8,5);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(7,7,4);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(8,7,4);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(9,7,4);
Assertions.assertTrue(tablero.estaOcupado(10,7));
Assertions.assertTrue(tablero.estaOcupado(9,6));
Assertions.assertTrue(tablero.estaOcupado(8,5));
Assertions.assertTrue(tablero.estaOcupado(7,5));
}
@Test
public void testCuandoBatallonSeDisuelveSePasaAMoverUnSoloSodado() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",4,6);
jugadorAliado.comprarUnidad("soldado",5,6);
jugadorAliado.comprarUnidad("soldado",6,6);
jugadorAliado.comprarUnidad("catapulta", 5,7);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.moverUnidad(4,6,2);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(4,7,2);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(4,8,2);
// tablero.imprimirTablero();
Assertions.assertTrue(tablero.estaOcupado(4,9));
Assertions.assertTrue(tablero.estaOcupado(5,6));
Assertions.assertTrue(tablero.estaOcupado(5,7));
Assertions.assertTrue(tablero.estaOcupado(6,8));
}
@Test
public void testBatallonSeMueveEnLosBorderDelTableroConExito() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",0,0);
jugadorAliado.comprarUnidad("soldado",0,1);
jugadorAliado.comprarUnidad("soldado",0,2);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(0,0,2);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(0,2,2);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(0,2,2);
Assertions.assertTrue(tablero.estaOcupado(0,3));
Assertions.assertTrue(tablero.estaOcupado(0,4));
Assertions.assertTrue(tablero.estaOcupado(0,5));
}
@Test
public void testBatallonEnFilaSeIntentaMoverAlEstePeroTieneUnObstaculoPorLoQueNingunSoldadoSeMueve() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",4,0);
jugadorAliado.comprarUnidad("soldado",4,1);
jugadorAliado.comprarUnidad("soldado",4,2);
jugadorAliado.comprarUnidad("curandero",4,3);
jugadorAliado.resetMovimientoUnidades();
Assertions.assertThrows(BatallonNoSePuedeMoverException.class,
() -> jugadorAliado.moverUnidad(4,0,2));
Assertions.assertTrue(tablero.estaOcupado(4,0));
Assertions.assertTrue(tablero.estaOcupado(4,1));
Assertions.assertTrue(tablero.estaOcupado(4,2));
}
@Test
public void testBatallonEnColumnaSeIntentaMoverAlSurPeroTieneUnObstaculoPorLoQueNingunSoldadoSeMueve() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",4,2);
jugadorAliado.comprarUnidad("soldado",5,2);
jugadorAliado.comprarUnidad("soldado",6,2);
jugadorAliado.comprarUnidad("soldado",7,2);
jugadorAliado.comprarUnidad("catapulta",8,2);
jugadorAliado.resetMovimientoUnidades();
Assertions.assertThrows(BatallonNoSePuedeMoverException.class,
() -> jugadorAliado.moverUnidad(4,2,4));
}
@Test
public void testCuandoBatallonSeDisuelveLosSoldadosVuelvenAMoversePorSeparado() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado",7,6);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("jinete", 8,5);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.moverUnidad(7,5,4);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.moverUnidad(8,6,4);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.moverUnidad(9,7,4);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
Assertions.assertTrue(tablero.estaOcupado(10,7));
Assertions.assertTrue(tablero.estaOcupado(9,6));
Assertions.assertTrue(tablero.estaOcupado(8,5));
Assertions.assertTrue(tablero.estaOcupado(7,5));
}
@Test
public void testCadaSoldadoDelBatallonTieneUnObstaculoPorLoQueNoSeMueve() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado",7,6);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("jinete", 8,5);
jugadorAliado.comprarUnidad("curandero", 8,6);
jugadorAliado.comprarUnidad("catapulta", 8,7);
jugadorAliado.resetMovimientoUnidades();
Assertions.assertThrows(BatallonNoSePuedeMoverException.class,
() -> jugadorAliado.moverUnidad(7,6,4));
}
@Test
public void testDosSoldadosDelBatallonTienenUnObstaculoPorLoQueSoloUnoSeMueve() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado",7,6);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("curandero", 8,6);
jugadorAliado.comprarUnidad("jinete", 8,5);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.moverUnidad(7,7,4);
// tablero.imprimirTablero();
Assertions.assertTrue(tablero.estaOcupado(8,7));
}
@Test
public void testUnSoldadosDelBatallonTienenUnObstaculoPorLoQueSoloDosSeMueven() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado",7,6);
jugadorAliado.comprarUnidad("soldado",7,5);
jugadorAliado.comprarUnidad("jinete", 8,5);
jugadorAliado.resetMovimientoUnidades();
// tablero.imprimirTablero();
jugadorAliado.moverUnidad(7,7,4);
// tablero.imprimirTablero();
Assertions.assertTrue(tablero.estaOcupado(8,7));
Assertions.assertTrue(tablero.estaOcupado(8,6));
}
@Test
public void testSoldadoSeMueveSoloHastaJuntarseConOtrosDosYDesdeEsePuntoSeMuevenComoBatallon() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.comprarUnidad("soldado",8,4);
jugadorAliado.comprarUnidad("soldado",9,4);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(7,7,6);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(7,6,6);
jugadorAliado.resetMovimientoUnidades();
jugadorAliado.moverUnidad(7,5,6);
jugadorAliado.resetMovimientoUnidades();
Assertions.assertTrue(tablero.estaOcupado(7,4));
Assertions.assertTrue(tablero.estaOcupado(8,3));
Assertions.assertTrue(tablero.estaOcupado(9,3));
}
/* la idea de este test que es los batallones no intercambien soldados
* pero no se me ocurre como hacer que no pase
*
*
@Test
public void testUnBatallonAliadoMantieneSusSoldadosAlPasarPorOtrosSoldadosAliados() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",4,2);
jugadorAliado.comprarUnidad("soldado",5,2);
jugadorAliado.comprarUnidad("soldado",6,2);
jugadorAliado.comprarUnidad("soldado",4,4);
jugadorAliado.comprarUnidad("soldado",5,4);
jugadorAliado.comprarUnidad("soldado",6,4);
tablero.imprimirTablero();
jugadorAliado.moverUnidad(5,2,2);
tablero.imprimirTablero();
jugadorAliado.moverUnidad(5,3,6);
tablero.imprimirTablero();
}
*/
@Test
public void testSoldadoAliadoSeMueveHaciaAlNorteYSeEncuentraConOtrosDosPorLoQueSeMuevenEnBatallon() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado", 9, 7);
jugadorAliado.comprarUnidad("soldado", 7, 8);
jugadorAliado.comprarUnidad("soldado", 7, 9);
jugadorAliado.resetMovimientoUnidades();
Unidad soldado1 = tablero.getUnidad(9,7);
Unidad soldado2 = tablero.getUnidad(7,8);
Unidad soldado3 = tablero.getUnidad(7,9);
tablero.moverUnidad(9,7,0);
jugadorAliado.resetMovimientoUnidades();
tablero.moverUnidad(8,7,0);
jugadorAliado.resetMovimientoUnidades();
tablero.moverUnidad(7,7,0);
jugadorAliado.resetMovimientoUnidades();
Assertions.assertSame(tablero.getUnidad(6,7), soldado1);
Assertions.assertSame(tablero.getUnidad(5,8), soldado2);
Assertions.assertSame(tablero.getUnidad(5,9), soldado3);
}
//vista
@Test
public void testJugadorEnModoPasivoHaceQueElSoldadoSeMueva() {
Tablero tablero = new Tablero();
Jugador jugadorAliado = new Jugador("agus",tablero);
jugadorAliado.comprarUnidad("soldado",7,7);
jugadorAliado.resetMovimientoUnidades();
int[] posUnidad = new int [2];
int[] destino = new int [2];
posUnidad[0] = 7;
posUnidad[1] = 7;
destino[0] = 8;
destino[1] = 8;
jugadorAliado.realizarAccion(posUnidad,destino);
Assertions.assertTrue(tablero.estaOcupado(8,8));
}
}
|
923d6ec4b0fb98c62459dcbf801c219f2831da98 | 986 | java | Java | guide/src/main/java/com/app/hubert/guide/lifecycle/ListenerFragment.java | weileng11/NewbieGuide-master | 7713cc70fd9d8c5f02ade4360b62a30caec42d6d | [
"Apache-2.0"
] | 3,236 | 2017-09-12T00:02:41.000Z | 2022-03-31T12:01:04.000Z | guide/src/main/java/com/app/hubert/guide/lifecycle/ListenerFragment.java | yanbo469/NewbieGuide | 1acb465828e3f22b7e2efb8a3b2ad7c14a9926d8 | [
"Apache-2.0"
] | 194 | 2017-09-12T01:16:33.000Z | 2022-03-17T01:00:30.000Z | guide/src/main/java/com/app/hubert/guide/lifecycle/ListenerFragment.java | yanbo469/NewbieGuide | 1acb465828e3f22b7e2efb8a3b2ad7c14a9926d8 | [
"Apache-2.0"
] | 467 | 2017-09-12T00:02:51.000Z | 2022-03-18T14:23:26.000Z | 24.04878 | 75 | 0.657201 | 1,000,320 | package com.app.hubert.guide.lifecycle;
import android.app.Fragment;
import com.app.hubert.guide.util.LogUtil;
public class ListenerFragment extends Fragment {
FragmentLifecycle mFragmentLifecycle;
public void setFragmentLifecycle(FragmentLifecycle lifecycle) {
mFragmentLifecycle = lifecycle;
}
@Override
public void onStart() {
super.onStart();
LogUtil.d("onStart: ");
if (mFragmentLifecycle != null) mFragmentLifecycle.onStart();
}
@Override
public void onStop() {
super.onStop();
if (mFragmentLifecycle != null) mFragmentLifecycle.onStop();
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mFragmentLifecycle != null) mFragmentLifecycle.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
LogUtil.d("onDestroy: ");
if (mFragmentLifecycle != null) mFragmentLifecycle.onDestroy();
}
}
|
923d7110622ec86a13b46b8c3e1fb84d5bb8b549 | 103 | java | Java | src/main/java/me/caneva20/Core/Generics/Functions/F0/Func.java | caneva20/CNVCore | 8ab60867562f1ce496b18e16d91e097de04b2276 | [
"MIT"
] | null | null | null | src/main/java/me/caneva20/Core/Generics/Functions/F0/Func.java | caneva20/CNVCore | 8ab60867562f1ce496b18e16d91e097de04b2276 | [
"MIT"
] | null | null | null | src/main/java/me/caneva20/Core/Generics/Functions/F0/Func.java | caneva20/CNVCore | 8ab60867562f1ce496b18e16d91e097de04b2276 | [
"MIT"
] | null | null | null | 17.166667 | 47 | 0.737864 | 1,000,321 | package me.caneva20.Core.Generics.Functions.F0;
public interface Func<TReturn> {
TReturn run();
}
|
923d7134f4e23aa988d0d67765af28ea8cc61df2 | 1,167 | java | Java | Labwork11/app/src/main/java/ge/edu/ibsu/mobile/labwork11/InputService.java | bmuradashvili/ibsu-mobile | 6f5f12e05a134860213ad172f1ee83f72938fea2 | [
"Apache-2.0"
] | null | null | null | Labwork11/app/src/main/java/ge/edu/ibsu/mobile/labwork11/InputService.java | bmuradashvili/ibsu-mobile | 6f5f12e05a134860213ad172f1ee83f72938fea2 | [
"Apache-2.0"
] | null | null | null | Labwork11/app/src/main/java/ge/edu/ibsu/mobile/labwork11/InputService.java | bmuradashvili/ibsu-mobile | 6f5f12e05a134860213ad172f1ee83f72938fea2 | [
"Apache-2.0"
] | null | null | null | 32.416667 | 118 | 0.700943 | 1,000,322 | package ge.edu.ibsu.mobile.labwork11;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import ge.edu.ibsu.mobile.labwork11.activities.LoginActivity;
import ge.edu.ibsu.mobile.labwork11.utils.SharedPreferenceUtils;
public class InputService extends IntentService {
public static final String ACTION_START_MAIN_ACTIVITY = "ge.edu.ibsu.mobile.labwork11.action.START_MAIN_ACTIVITY";
public InputService() {
super("InputService");
}
public InputService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (InputService.ACTION_START_MAIN_ACTIVITY.equals(action)) {
String email = intent.getStringExtra(LoginActivity.EMAIL_TAG);
SharedPreferenceUtils.getInstance(this).putString(LoginActivity.EMAIL_TAG, email);
Intent broadcastIntent = new Intent(InputService.ACTION_START_MAIN_ACTIVITY);
sendBroadcast(broadcastIntent);
}
}
}
}
|
923d713c96276ac0502ea1e6848a6e2d12ecdbd2 | 927 | java | Java | sabot/kernel/src/main/java/com/dremio/exec/store/ReferenceConflictException.java | geetek/dremio-oss | 812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2 | [
"Apache-2.0"
] | null | null | null | sabot/kernel/src/main/java/com/dremio/exec/store/ReferenceConflictException.java | geetek/dremio-oss | 812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2 | [
"Apache-2.0"
] | null | null | null | sabot/kernel/src/main/java/com/dremio/exec/store/ReferenceConflictException.java | geetek/dremio-oss | 812c7f32f9437df52b1d7bd8d5c45f9a79b6e9d2 | [
"Apache-2.0"
] | null | null | null | 28.090909 | 75 | 0.733549 | 1,000,323 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.exec.store;
/**
* TODO: DX-43144 Wording
*/
public class ReferenceConflictException extends Exception {
private static final long serialVersionUID = 1L;
public ReferenceConflictException() {
super();
}
public ReferenceConflictException(Throwable cause) {
super(cause);
}
}
|
923d7146af221e2ea67683d7acbfcd1e6fdf0c4b | 3,788 | java | Java | src/com/n0texpecterr0r/datastructure/linear/LinkedList.java | N0tExpectErr0r/DataStructReview | a7d0f4dcc3922ffbba40b05e6617f8bc7f28d16b | [
"Apache-2.0"
] | 1 | 2019-11-01T03:32:26.000Z | 2019-11-01T03:32:26.000Z | src/com/n0texpecterr0r/datastructure/linear/LinkedList.java | N0tExpectErr0r/DataStructureReview | a7d0f4dcc3922ffbba40b05e6617f8bc7f28d16b | [
"Apache-2.0"
] | null | null | null | src/com/n0texpecterr0r/datastructure/linear/LinkedList.java | N0tExpectErr0r/DataStructureReview | a7d0f4dcc3922ffbba40b05e6617f8bc7f28d16b | [
"Apache-2.0"
] | null | null | null | 24.43871 | 90 | 0.43057 | 1,000,324 | package com.n0texpecterr0r.datastructure.linear;
/**
* 基于双向循环链表实现的LinkedList
*/
public class LinkedList<T> {
private Entry<T> head;
private int length;
private static class Entry<T> {
T data;
Entry<T> prev;
Entry<T> next;
public Entry(T data) {
this.data = data;
}
}
public void add(T data) {
length++;
Entry<T> insert = new Entry<>(data);
if (head == null) {
head = insert;
head.next = head;
head.prev = head;
} else {
Entry<T> tail = head.prev;
head.prev = insert;
insert.next = head;
insert.prev = tail;
tail.next = insert;
}
}
public void add(int index, T data) {
checkBounds(index);
length++;
Entry<T> insert = new Entry<>(data);
if (index == 0 && head == null) {
head = insert;
head.next = head;
head.prev = head;
} else {
Entry<T> node = head;
if (index == 0) {
head = insert;
}
for (int i = 0; i < index; i++) {
node = node.next;
}
insert.prev = node.prev;
node.prev.next = insert;
node.prev = insert;
insert.next = node;
}
}
public void addAll(LinkedList<T> list) {
for (int i = 0; i < list.length; i++) {
add(list.get(i));
}
}
public void remove(T data) {
if (head == null) {
return;
}
Entry<T> node = head;
boolean found = false;
do {
if (node.data == data) {
found = true;
break;
}
node = node.next;
} while (node != head);
if (found) {
if (node == head) {
head = node.next;
}
node.prev.next = node.next;
node.next.prev = node.prev;
node.prev = null;
node.next = null;
node = null;
length--;
}
}
public T get(int index) {
checkBounds(index);
// 根据位置从尾端或头端进行获取
if (index >= length / 2) {
Entry<T> node = head;
for (int i = 0; i < index; i++) {
node = node.next;
}
return node.data;
} else {
Entry<T> node = head.prev;
for (int i = 0; i < length - index - 1; i++) {
node = node.prev;
}
return node.data;
}
}
public boolean contains(T data) {
return indexOf(data) > 0;
}
public int indexOf(T data) {
Entry<T> node = head;
int index = 0;
do {
if (node.data == data) {
return index;
}
index++;
node = node.next;
} while (node != head);
return -1;
}
public int size() {
return length;
}
private void checkBounds(int index) {
if (index > length || index < 0) {
throw new IndexOutOfBoundsException("index: " + index + " length: " + length);
}
}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
for (int i = 0; i < 100; i++) {
list.add(i + 1);
}
System.out.println("index of 25: " + list.indexOf(25));
list.remove(15);
list.add(10, 260);
System.out.println("index of 25: " + list.indexOf(25));
System.out.println(list.contains(16));
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
}
|
923d716128c0d68dc0ef161b5e12cea64bb5f67d | 1,285 | java | Java | src/main/java/com/blazemeter/bamboo/plugin/logging/AgentUserNotifier.java | Blazemeter/blazemeter-bamboo-plugin | 7f987b46075527dfa650e8ee201dcee47722447c | [
"Apache-2.0"
] | 4 | 2015-02-20T22:49:33.000Z | 2020-10-12T19:12:07.000Z | src/main/java/com/blazemeter/bamboo/plugin/logging/AgentUserNotifier.java | Blazemeter/blazemeter-bamboo-plugin | 7f987b46075527dfa650e8ee201dcee47722447c | [
"Apache-2.0"
] | 2 | 2017-08-23T01:06:04.000Z | 2021-06-23T23:27:54.000Z | src/main/java/com/blazemeter/bamboo/plugin/logging/AgentUserNotifier.java | Blazemeter/blazemeter-bamboo-plugin | 7f987b46075527dfa650e8ee201dcee47722447c | [
"Apache-2.0"
] | 7 | 2017-06-27T08:56:15.000Z | 2020-10-12T19:12:08.000Z | 30.595238 | 75 | 0.730739 | 1,000,325 | /**
* Copyright 2017 BlazeMeter Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blazemeter.bamboo.plugin.logging;
import com.atlassian.bamboo.build.logger.BuildLogger;
import com.blazemeter.api.logging.UserNotifier;
public class AgentUserNotifier implements UserNotifier {
private BuildLogger buildLogger;
public AgentUserNotifier(BuildLogger buildLogger) {
this.buildLogger = buildLogger;
}
@Override
public void notifyInfo(String info) {
buildLogger.addBuildLogEntry(info);
}
@Override
public void notifyWarning(String warn) {
buildLogger.addBuildLogEntry("WARNING: " + warn);
}
@Override
public void notifyError(String error) {
buildLogger.addErrorLogEntry(error);
}
}
|
923d72036c8d4cd10af7a9fc65bd1c80ad4146dc | 4,232 | java | Java | server-core/src/main/java/io/onedev/server/buildspec/job/trigger/PullRequestTrigger.java | chancat87/onedev | 38ee186994d29e5cc4c816f9c37a92fc82500bc4 | [
"MIT"
] | 7,137 | 2018-12-25T02:07:47.000Z | 2022-03-31T20:56:56.000Z | server-core/src/main/java/io/onedev/server/buildspec/job/trigger/PullRequestTrigger.java | chancat87/onedev | 38ee186994d29e5cc4c816f9c37a92fc82500bc4 | [
"MIT"
] | 68 | 2019-01-07T12:08:30.000Z | 2022-03-26T00:59:15.000Z | server-core/src/main/java/io/onedev/server/buildspec/job/trigger/PullRequestTrigger.java | chancat87/onedev | 38ee186994d29e5cc4c816f9c37a92fc82500bc4 | [
"MIT"
] | 592 | 2019-01-07T03:00:58.000Z | 2022-03-25T08:56:09.000Z | 34.406504 | 177 | 0.705104 | 1,000,326 | package io.onedev.server.buildspec.job.trigger;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
import io.onedev.commons.codeassist.InputSuggestion;
import io.onedev.server.buildspec.job.SubmitReason;
import io.onedev.server.git.GitUtils;
import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.util.match.Matcher;
import io.onedev.server.util.match.PathMatcher;
import io.onedev.server.util.patternset.PatternSet;
import io.onedev.server.web.editable.annotation.Editable;
import io.onedev.server.web.editable.annotation.NameOfEmptyValue;
import io.onedev.server.web.editable.annotation.Patterns;
import io.onedev.server.web.util.SuggestionUtils;
public abstract class PullRequestTrigger extends JobTrigger {
private static final long serialVersionUID = 1L;
private String branches;
private String paths;
@Editable(name="Target Branches", order=100, description="Optionally specify space-separated "
+ "target branches of the pull requests to check. Use '**', '*' or '?' for <a href='$docRoot/pages/path-wildcard.md' target='_blank'>path wildcard match</a>. "
+ "Prefix with '-' to exclude. Leave empty to match all branches")
@Patterns(suggester = "suggestBranches", path=true)
@NameOfEmptyValue("Any branch")
public String getBranches() {
return branches;
}
public void setBranches(String branches) {
this.branches = branches;
}
@SuppressWarnings("unused")
private static List<InputSuggestion> suggestBranches(String matchWith) {
return SuggestionUtils.suggestBranches(Project.get(), matchWith);
}
@Editable(name="Touched Files", order=200,
description="Optionally specify space-separated files to check. Use '**', '*' or '?' for <a href='$docRoot/pages/path-wildcard.md' target='_blank'>path wildcard match</a>. "
+ "Prefix with '-' to exclude. Leave empty to match all files")
@Patterns(suggester = "getPathSuggestions", path=true)
@NameOfEmptyValue("Any file")
public String getPaths() {
return paths;
}
public void setPaths(String paths) {
this.paths = paths;
}
@SuppressWarnings("unused")
private static List<InputSuggestion> getPathSuggestions(String matchWith) {
return SuggestionUtils.suggestBlobs(Project.get(), matchWith);
}
private boolean touchedFile(PullRequest request) {
if (getPaths() != null) {
Collection<String> changedFiles = GitUtils.getChangedFiles(request.getTargetProject().getRepository(),
request.getBaseCommit(), request.getLatestUpdate().getHeadCommit());
PatternSet patternSet = PatternSet.parse(getPaths());
Matcher matcher = new PathMatcher();
for (String changedFile: changedFiles) {
if (patternSet.matches(matcher, changedFile))
return true;
}
return false;
} else {
return true;
}
}
@Nullable
protected SubmitReason triggerMatches(PullRequest request) {
String targetBranch = request.getTargetBranch();
Matcher matcher = new PathMatcher();
if ((branches == null || PatternSet.parse(branches).matches(matcher, targetBranch))
&& touchedFile(request)) {
return new SubmitReason() {
@Override
public String getRefName() {
return request.getMergeRef();
}
@Override
public PullRequest getPullRequest() {
return request;
}
@Override
public String getDescription() {
return "Pull request #" + request.getNumber() + " is opened/updated";
}
};
}
return null;
}
protected String getTriggerDescription(String action) {
String description;
if (getBranches() != null && getPaths() != null)
description = String.format("When " + action + " pull requests targeting branches '%s' and touching files '%s'", getBranches(), getPaths());
else if (getBranches() != null)
description = String.format("When " + action + " pull requests targeting branches '%s'", getBranches());
else if (getPaths() != null)
description = String.format("When " + action + " pull requests touching files '%s'", getPaths());
else
description = "When " + action + " pull requests";
return description;
}
}
|
923d7206b926a763bd4b48ae57abcca1cb9f18c6 | 927 | java | Java | netty-tutorialis/time/src/main/java/com/example/time/client/TimeClientConfigurer.java | mike-neck/java-til | 97829e7c519c5ee27b33b097042479c580694c38 | [
"Apache-2.0"
] | null | null | null | netty-tutorialis/time/src/main/java/com/example/time/client/TimeClientConfigurer.java | mike-neck/java-til | 97829e7c519c5ee27b33b097042479c580694c38 | [
"Apache-2.0"
] | 1 | 2018-03-08T05:02:38.000Z | 2018-03-08T05:02:38.000Z | netty-tutorialis/time/src/main/java/com/example/time/client/TimeClientConfigurer.java | mike-neck/java-til | 97829e7c519c5ee27b33b097042479c580694c38 | [
"Apache-2.0"
] | null | null | null | 33.107143 | 81 | 0.772384 | 1,000,327 | /*
* Copyright 2018 Shinya Mochida
*
* Licensed under the Apache License,Version2.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.example.time.client;
import com.example.client.ClientChannelInitializerConfigurer;
import io.netty.channel.ChannelHandlerAdapter;
public class TimeClientConfigurer implements ClientChannelInitializerConfigurer {
@Override
public ChannelHandlerAdapter handlerAdapter() {
return new TimeClientHandler();
}
}
|
923d72ddd0718edca27b4cdb10c25e5e3b7b1f99 | 10,198 | java | Java | misc/eu.hansolo.enzo/src/main/java/eu/hansolo/enzo/splitflap/SplitFlapBuilder.java | dhakehurst/net.akehurst.application.framework.examples | ff622351f295cc578f0305f68ea8528b66f043a3 | [
"Apache-2.0"
] | 52 | 2015-04-27T20:43:28.000Z | 2021-09-06T16:16:25.000Z | misc/eu.hansolo.enzo/src/main/java/eu/hansolo/enzo/splitflap/SplitFlapBuilder.java | dhakehurst/net.akehurst.application.framework.examples | ff622351f295cc578f0305f68ea8528b66f043a3 | [
"Apache-2.0"
] | 5 | 2015-01-21T18:35:15.000Z | 2019-06-21T09:14:21.000Z | misc/eu.hansolo.enzo/src/main/java/eu/hansolo/enzo/splitflap/SplitFlapBuilder.java | dhakehurst/net.akehurst.application.framework.examples | ff622351f295cc578f0305f68ea8528b66f043a3 | [
"Apache-2.0"
] | 25 | 2015-04-08T17:34:23.000Z | 2021-03-10T12:29:56.000Z | 42.848739 | 107 | 0.63032 | 1,000,328 | /*
* Copyright (c) 2013 by Gerrit Grunwald
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.hansolo.enzo.splitflap;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Dimension2D;
import javafx.scene.paint.Color;
import java.util.HashMap;
public class SplitFlapBuilder<B extends SplitFlapBuilder<B>> {
private HashMap<String, Property> properties = new HashMap<>();
// ******************** Constructors **************************************
protected SplitFlapBuilder() {}
// ******************** Methods *******************************************
public static final SplitFlapBuilder create() {
return new SplitFlapBuilder();
}
public final SplitFlapBuilder keepAspect(final boolean KEEP_ASPECT) {
properties.put("keepAspect", new SimpleBooleanProperty(KEEP_ASPECT));
return this;
}
public final SplitFlapBuilder flipTime(final double FLIP_TIME) {
properties.put("flipTime", new SimpleDoubleProperty(FLIP_TIME));
return this;
}
public final SplitFlapBuilder wordMode(final boolean WORD_MODE) {
properties.put("wordMode", new SimpleBooleanProperty(WORD_MODE));
return this;
}
public final SplitFlapBuilder withFixture(final boolean WITH_FIXTURE) {
properties.put("withFixture", new SimpleBooleanProperty(WITH_FIXTURE));
return this;
}
public final SplitFlapBuilder darkFixture(final boolean DARK_FIXTURE) {
properties.put("darkFixture", new SimpleBooleanProperty(DARK_FIXTURE));
return this;
}
public final SplitFlapBuilder squareFlaps(final boolean SQUARE_FLAPS) {
properties.put("squareFlaps", new SimpleBooleanProperty(SQUARE_FLAPS));
return this;
}
public final SplitFlapBuilder flapColor(final Color FLAP_COLOR) {
properties.put("flapColor", new SimpleObjectProperty<>(FLAP_COLOR));
return this;
}
public final SplitFlapBuilder textColor(final Color TEXT_COLOR) {
properties.put("textColor", new SimpleObjectProperty<>(TEXT_COLOR));
return this;
}
public final SplitFlapBuilder text(final String TEXT) {
properties.put("text", new SimpleStringProperty(TEXT));
return this;
}
public final SplitFlapBuilder selection(final String[] SELECTION) {
properties.put("selection", new SimpleObjectProperty<>(SELECTION));
return this;
}
public final B prefSize(final double WIDTH, final double HEIGHT) {
properties.put("prefSize", new SimpleObjectProperty<>(new Dimension2D(WIDTH, HEIGHT)));
return (B)this;
}
public final B minSize(final double WIDTH, final double HEIGHT) {
properties.put("minSize", new SimpleObjectProperty<>(new Dimension2D(WIDTH, HEIGHT)));
return (B)this;
}
public final B maxSize(final double WIDTH, final double HEIGHT) {
properties.put("maxSize", new SimpleObjectProperty<>(new Dimension2D(WIDTH, HEIGHT)));
return (B)this;
}
public final B prefWidth(final double PREF_WIDTH) {
properties.put("prefWidth", new SimpleDoubleProperty(PREF_WIDTH));
return (B)this;
}
public final B prefHeight(final double PREF_HEIGHT) {
properties.put("prefHeight", new SimpleDoubleProperty(PREF_HEIGHT));
return (B)this;
}
public final B minWidth(final double MIN_WIDTH) {
properties.put("minWidth", new SimpleDoubleProperty(MIN_WIDTH));
return (B)this;
}
public final B minHeight(final double MIN_HEIGHT) {
properties.put("minHeight", new SimpleDoubleProperty(MIN_HEIGHT));
return (B)this;
}
public final B maxWidth(final double MAX_WIDTH) {
properties.put("maxWidth", new SimpleDoubleProperty(MAX_WIDTH));
return (B)this;
}
public final B maxHeight(final double MAX_HEIGHT) {
properties.put("maxHeight", new SimpleDoubleProperty(MAX_HEIGHT));
return (B)this;
}
public final B scaleX(final double SCALE_X) {
properties.put("scaleX", new SimpleDoubleProperty(SCALE_X));
return (B)this;
}
public final B scaleY(final double SCALE_Y) {
properties.put("scaleY", new SimpleDoubleProperty(SCALE_Y));
return (B)this;
}
public final B layoutX(final double LAYOUT_X) {
properties.put("layoutX", new SimpleDoubleProperty(LAYOUT_X));
return (B)this;
}
public final B layoutY(final double LAYOUT_Y) {
properties.put("layoutY", new SimpleDoubleProperty(LAYOUT_Y));
return (B)this;
}
public final B translateX(final double TRANSLATE_X) {
properties.put("translateX", new SimpleDoubleProperty(TRANSLATE_X));
return (B)this;
}
public final B translateY(final double TRANSLATE_Y) {
properties.put("translateY", new SimpleDoubleProperty(TRANSLATE_Y));
return (B)this;
}
public final SplitFlap build() {
final SplitFlap CONTROL;
if (properties.containsKey("selection")) {
if (properties.containsKey("text")) {
CONTROL = new SplitFlap(((ObjectProperty<String[]>) properties.get("selection")).get(),
((StringProperty) properties.get("text")).get());
} else {
CONTROL = new SplitFlap(((ObjectProperty<String[]>) properties.get("selection")).get(),
((ObjectProperty<String[]>) properties.get("selection")).get()[0]);
}
} else {
CONTROL = new SplitFlap();
}
for (String key : properties.keySet()) {
if ("keepAspect".equals(key)) {
CONTROL.setKeepAspect(((BooleanProperty) properties.get(key)).get());
} else if ("flipTime".equals(key)) {
CONTROL.setFlipTime(((DoubleProperty) properties.get(key)).get());
} else if ("wordMode".equals(key)) {
CONTROL.setWordMode(((BooleanProperty) properties.get(key)).get());
} else if ("withFixture".equals(key)) {
CONTROL.setWithFixture(((BooleanProperty) properties.get(key)).get());
} else if ("darkFixture".equals(key)) {
CONTROL.setDarkFixture(((BooleanProperty) properties.get(key)).get());
} else if ("squareFlaps".equals(key)) {
CONTROL.setSquareFlaps(((BooleanProperty) properties.get(key)).get());
} else if ("flapColor".equals(key)) {
CONTROL.setFlapColor(((ObjectProperty<Color>) properties.get(key)).get());
} else if ("textColor".equals(key)) {
CONTROL.setTextColor(((ObjectProperty<Color>) properties.get(key)).get());
} else if ("text".equals(key)) {
CONTROL.setText(((StringProperty) properties.get(key)).get());
} else if ("selection".equals(key)) {
CONTROL.setSelection(((ObjectProperty<String[]>) properties.get(key)).get());
} else if ("prefSize".equals(key)) {
Dimension2D dim = ((ObjectProperty<Dimension2D>) properties.get(key)).get();
CONTROL.setPrefSize(dim.getWidth(), dim.getHeight());
} else if("minSize".equals(key)) {
Dimension2D dim = ((ObjectProperty<Dimension2D>) properties.get(key)).get();
CONTROL.setPrefSize(dim.getWidth(), dim.getHeight());
} else if("maxSize".equals(key)) {
Dimension2D dim = ((ObjectProperty<Dimension2D>) properties.get(key)).get();
CONTROL.setPrefSize(dim.getWidth(), dim.getHeight());
} else if("prefWidth".equals(key)) {
CONTROL.setPrefWidth(((DoubleProperty) properties.get(key)).get());
} else if("prefHeight".equals(key)) {
CONTROL.setPrefHeight(((DoubleProperty) properties.get(key)).get());
} else if("minWidth".equals(key)) {
CONTROL.setMinWidth(((DoubleProperty) properties.get(key)).get());
} else if("minHeight".equals(key)) {
CONTROL.setMinHeight(((DoubleProperty) properties.get(key)).get());
} else if("maxWidth".equals(key)) {
CONTROL.setMaxWidth(((DoubleProperty) properties.get(key)).get());
} else if("maxHeight".equals(key)) {
CONTROL.setMaxHeight(((DoubleProperty) properties.get(key)).get());
} else if("scaleX".equals(key)) {
CONTROL.setScaleX(((DoubleProperty) properties.get(key)).get());
} else if("scaleY".equals(key)) {
CONTROL.setScaleY(((DoubleProperty) properties.get(key)).get());
} else if ("layoutX".equals(key)) {
CONTROL.setLayoutX(((DoubleProperty) properties.get(key)).get());
} else if ("layoutY".equals(key)) {
CONTROL.setLayoutY(((DoubleProperty) properties.get(key)).get());
} else if ("translateX".equals(key)) {
CONTROL.setTranslateX(((DoubleProperty) properties.get(key)).get());
} else if ("translateY".equals(key)) {
CONTROL.setTranslateY(((DoubleProperty) properties.get(key)).get());
}
}
return CONTROL;
}
}
|
923d7384edd7aaa60033efaf5adb8665f6f4490f | 3,982 | java | Java | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/TaskStatisticsForAuditCheckJsonUnmarshaller.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | 1 | 2022-01-04T04:11:16.000Z | 2022-01-04T04:11:16.000Z | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/TaskStatisticsForAuditCheckJsonUnmarshaller.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/TaskStatisticsForAuditCheckJsonUnmarshaller.java | vinayakpokharkar/aws-sdk-java | fd409dee8ae23fb8953e0bb4dbde65536a7e0514 | [
"Apache-2.0"
] | null | null | null | 43.758242 | 136 | 0.667002 | 1,000,329 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.iot.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* TaskStatisticsForAuditCheck JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TaskStatisticsForAuditCheckJsonUnmarshaller implements Unmarshaller<TaskStatisticsForAuditCheck, JsonUnmarshallerContext> {
public TaskStatisticsForAuditCheck unmarshall(JsonUnmarshallerContext context) throws Exception {
TaskStatisticsForAuditCheck taskStatisticsForAuditCheck = new TaskStatisticsForAuditCheck();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("totalFindingsCount", targetDepth)) {
context.nextToken();
taskStatisticsForAuditCheck.setTotalFindingsCount(context.getUnmarshaller(Long.class).unmarshall(context));
}
if (context.testExpression("failedFindingsCount", targetDepth)) {
context.nextToken();
taskStatisticsForAuditCheck.setFailedFindingsCount(context.getUnmarshaller(Long.class).unmarshall(context));
}
if (context.testExpression("succeededFindingsCount", targetDepth)) {
context.nextToken();
taskStatisticsForAuditCheck.setSucceededFindingsCount(context.getUnmarshaller(Long.class).unmarshall(context));
}
if (context.testExpression("skippedFindingsCount", targetDepth)) {
context.nextToken();
taskStatisticsForAuditCheck.setSkippedFindingsCount(context.getUnmarshaller(Long.class).unmarshall(context));
}
if (context.testExpression("canceledFindingsCount", targetDepth)) {
context.nextToken();
taskStatisticsForAuditCheck.setCanceledFindingsCount(context.getUnmarshaller(Long.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return taskStatisticsForAuditCheck;
}
private static TaskStatisticsForAuditCheckJsonUnmarshaller instance;
public static TaskStatisticsForAuditCheckJsonUnmarshaller getInstance() {
if (instance == null)
instance = new TaskStatisticsForAuditCheckJsonUnmarshaller();
return instance;
}
}
|
923d74c8d7b7ba465976a5f54b572c46658c44e0 | 970 | java | Java | src/main/java/unalcol/optimization/real/testbed/Griewangk.java | anonypeople/argen | 955524f4c03a906a84f57e3532c7834b9cef61ab | [
"MIT"
] | null | null | null | src/main/java/unalcol/optimization/real/testbed/Griewangk.java | anonypeople/argen | 955524f4c03a906a84f57e3532c7834b9cef61ab | [
"MIT"
] | null | null | null | src/main/java/unalcol/optimization/real/testbed/Griewangk.java | anonypeople/argen | 955524f4c03a906a84f57e3532c7834b9cef61ab | [
"MIT"
] | null | null | null | 24.871795 | 76 | 0.584536 | 1,000,330 | package unalcol.optimization.real.testbed;
import unalcol.optimization.OptimizationFunction;
/**
* <p>Title: Griewangk</p>
* <p>Description: The Griewangk function</p>
* <p>Copyright: Copyright (c) 2010</p>
* <p>Company: Kunsamu</p>
*
* @author Jonatan Gomez
* @version 1.0
*/
public class Griewangk extends OptimizationFunction<double[]> {
/**
* Constructor: Creates a Griewangk function
*/
public Griewangk() {
}
/**
* Evaluate the OptimizationFunction function over the real vector given
*
* @param x Real vector to be evaluated
* @return the OptimizationFunction function over the real vector
*/
public Double apply(double[] x) {
int n = x.length;
double sum = 0.0;
double prod = 1.0;
for (int i = 0; i < n; i++) {
sum += x[i] * x[i] / 4000.0;
prod *= Math.cos(x[i] / Math.sqrt(i + 1.0));
}
return (1.0 + sum - prod);
}
}
|
923d76884e848428c358e91b61ec78e0a099c528 | 499 | java | Java | src/main/java/org/txazo/designpattern/structural/proxy/staticproxy/IServiceCompositionProxy.java | txazo/java | d3e9b20ee98c890bfaa464140554961d9850a06d | [
"Apache-2.0"
] | null | null | null | src/main/java/org/txazo/designpattern/structural/proxy/staticproxy/IServiceCompositionProxy.java | txazo/java | d3e9b20ee98c890bfaa464140554961d9850a06d | [
"Apache-2.0"
] | 2 | 2021-07-02T18:51:34.000Z | 2021-08-09T20:59:24.000Z | src/main/java/org/txazo/designpattern/structural/proxy/staticproxy/IServiceCompositionProxy.java | txazo/java | d3e9b20ee98c890bfaa464140554961d9850a06d | [
"Apache-2.0"
] | 1 | 2016-08-15T15:05:32.000Z | 2016-08-15T15:05:32.000Z | 20.791667 | 61 | 0.695391 | 1,000,332 | package org.txazo.designpattern.structural.proxy.staticproxy;
import org.txazo.designpattern.structural.proxy.IService;
/**
* 组合实现静态代理
*/
public class IServiceCompositionProxy implements IService {
private IService iService;
public IServiceCompositionProxy(IService iService) {
this.iService = iService;
}
@Override
public void service() {
System.out.println("Proxy before");
iService.service();
System.out.println("Proxy after");
}
}
|
923d76cfdfdb7326cc68c4e9ea435477cad2ec58 | 1,141 | java | Java | gfycat-core/src/main/java/com/gfycat/core/NoAuthAPI.java | gfycat/gfycat-android-sdk | 5590fcbc4066327e33c1b59ec47baebaa5e56ed7 | [
"Apache-2.0"
] | 9 | 2017-03-09T02:37:50.000Z | 2022-03-08T17:42:36.000Z | gfycat-core/src/main/java/com/gfycat/core/NoAuthAPI.java | gfycat/gfycat-android-sdk | 5590fcbc4066327e33c1b59ec47baebaa5e56ed7 | [
"Apache-2.0"
] | 8 | 2017-04-03T16:49:04.000Z | 2020-06-28T19:34:08.000Z | gfycat-core/src/main/java/com/gfycat/core/NoAuthAPI.java | gfycat/gfycat-android-sdk | 5590fcbc4066327e33c1b59ec47baebaa5e56ed7 | [
"Apache-2.0"
] | 4 | 2018-03-04T07:30:33.000Z | 2022-03-01T18:29:11.000Z | 31.694444 | 98 | 0.756354 | 1,000,333 | /*
* Copyright (c) 2015-present, Gfycat, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gfycat.core;
import io.reactivex.Observable;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.PUT;
import retrofit2.http.Url;
/**
* Separated from other apis because this request must execute without auth.
* That's why this api creates with separated OkHttpClient.
*/
public interface NoAuthAPI {
@PUT
Observable<Response<ResponseBody>> uploadAvatarImage(@Url String url, @Body RequestBody body);
}
|
923d771da9842c0f9ccc9cc71f00169aae7c64eb | 2,669 | java | Java | src/main/java/net/pjtb/vs/shared/EventAddresses.java | Kevin-Jin/verticle-story | 9b6c33eb65532d66245794f55dac5063ca91430b | [
"Apache-2.0"
] | 1 | 2015-10-14T17:39:34.000Z | 2015-10-14T17:39:34.000Z | src/main/java/net/pjtb/vs/shared/EventAddresses.java | Kevin-Jin/verticle-story | 9b6c33eb65532d66245794f55dac5063ca91430b | [
"Apache-2.0"
] | null | null | null | src/main/java/net/pjtb/vs/shared/EventAddresses.java | Kevin-Jin/verticle-story | 9b6c33eb65532d66245794f55dac5063ca91430b | [
"Apache-2.0"
] | null | null | null | 36.067568 | 149 | 0.756088 | 1,000,334 | package net.pjtb.vs.shared;
import net.pjtb.vs.mapside.ChannelMap;
import net.pjtb.vs.playerside.Chatroom;
import net.pjtb.vs.playerside.Guild;
import net.pjtb.vs.playerside.Party;
public final class EventAddresses {
/**
* Sample usage: String.format(EventAddresses.MAP_REQUEST, EventAddresses.fullyQualifiedChannelKey(world, channel));
*/
public static final String MAP_REQUEST = ChannelMap.class.getCanonicalName() + "[%05d].request";
/**
* Sample usage: String.format(EventAddresses.MAP_BROADCAST, EventAddresses.fullyQualifiedChannelKey(world, channel), EventAddresses.mapKey(mapId));
*/
public static final String MAP_BROADCAST = ChannelMap.class.getCanonicalName() + "[%05d][%09d].broadcast";
/**
* Sample usage: String.format(EventAddresses.PARTY_BROADCAST, EventAddresses.worldKey(world), EventAddresses.partyKey(partyId));
*/
public static final String PARTY_BROADCAST = Party.class.getCanonicalName() + "[%03d][%010d].broadcast";
/**
* Sample usage: String.format(EventAddresses.PARTY_REQUEST, EventAddresses.worldKey(world));
*/
public static final String PARTY_REQUEST = Party.class.getCanonicalName() + "[%03d].request";
/**
* Sample usage: String.format(EventAddresses.GUILD_BROADCAST, EventAddresses.worldKey(world), EventAddresses.guildKey(guildId));
*/
public static final String GUILD_BROADCAST = Guild.class.getCanonicalName() + "[%03d][%010d].broadcast";
/**
* Sample usage: String.format(EventAddresses.CHATROOM_BROADCAST, EventAddresses.worldKey(world), EventAddresses.chatroomKey(chatroomd));
*/
public static final String CHATROOM_BROADCAST = Chatroom.class.getCanonicalName() + "[%03d][%010d].broadcast";
/**
* Sample usage: String.format(EventAddresses.SPECS_LOADED_NOTIFICATION, "map");
*/
public static final String SPECS_LOADED_NOTIFICATION = Specs.class.getCanonicalName() + "[%s].done";
public static final short LOGIN_CH = -2;
public static final short OFFLINE_CH = -1;
public static final short SHOP_CH = 20;
public static Short fullyQualifiedChannelKey(byte world, byte channel) {
return Short.valueOf((short) (world * 100 + channel));
}
public static Byte worldKey(byte world) {
return Byte.valueOf(world);
}
public static Byte channelKey(byte channel) {
return Byte.valueOf(channel);
}
public static Integer mapKey(int mapId) {
return Integer.valueOf(mapId);
}
public static Integer partyKey(int partyId) {
return Integer.valueOf(partyId);
}
public static Integer guildKey(int guildId) {
return Integer.valueOf(guildId);
}
public static Integer chatroomKey(int chatroomId) {
return Integer.valueOf(chatroomId);
}
private EventAddresses() {
}
}
|
923d78f0c186cc6ec6b09ea59f19dac0afe8de23 | 1,700 | java | Java | app/src/main/java/db/juhaku/juhakudb/core/android/ResultTransformer.java | juhaku/juhakudb | 56365a46f1c875dac5c72d09414bcb9e432f94d9 | [
"MIT"
] | 1 | 2018-10-01T11:07:29.000Z | 2018-10-01T11:07:29.000Z | app/src/main/java/db/juhaku/juhakudb/core/android/ResultTransformer.java | juhaku/juhakudb | 56365a46f1c875dac5c72d09414bcb9e432f94d9 | [
"MIT"
] | 2 | 2017-11-12T09:34:43.000Z | 2018-03-16T21:29:57.000Z | app/src/main/java/db/juhaku/juhakudb/core/android/ResultTransformer.java | juhaku/juhakudb | 56365a46f1c875dac5c72d09414bcb9e432f94d9 | [
"MIT"
] | 1 | 2018-03-09T16:28:48.000Z | 2018-03-09T16:28:48.000Z | 35.416667 | 99 | 0.754706 | 1,000,335 | /**
MIT License
Copyright (c) 2018 juhaku
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 db.juhaku.juhakudb.core.android;
import java.util.List;
/**
* Created by juha on 26/04/16.
* <p>Implement this interface to provide custom conversion for list of result set objects returned
* by database query.</p>
* @author juha
*
* @since 1.0.2
*/
public interface ResultTransformer<T> {
/**
* Converts list of {@link ResultSet} objects returned by database query.
*
* @param resultSets {@link ResultSet} returned by database query.
* @return instance of object that is converted from result sets.
*
* @since 1.0.2
*/
T transformResult(List<ResultSet> resultSets);
}
|
923d797517ad3a80dee370cd6cc70ff2c1bb28f8 | 2,446 | java | Java | ICC/SOOT-Nightly/soot-github/src/soot/baf/internal/BFieldPutInst.java | dongy6/type-inference | 90d002a1e2d0a3d160ab204084da9d5be5fdd971 | [
"Apache-2.0"
] | 1 | 2019-12-07T16:13:03.000Z | 2019-12-07T16:13:03.000Z | ICC/SOOT-Nightly/soot-github/src/soot/baf/internal/BFieldPutInst.java | dongy6/type-inference | 90d002a1e2d0a3d160ab204084da9d5be5fdd971 | [
"Apache-2.0"
] | null | null | null | ICC/SOOT-Nightly/soot-github/src/soot/baf/internal/BFieldPutInst.java | dongy6/type-inference | 90d002a1e2d0a3d160ab204084da9d5be5fdd971 | [
"Apache-2.0"
] | null | null | null | 26.021277 | 82 | 0.666803 | 1,000,336 | /* Soot - a J*va Optimization Framework
* Copyright (C) 1999 Patrick Lam, Patrick Pominville and Raja Vallee-Rai
* Copyright (C) 2004 Ondrej Lhotak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot.baf.internal;
import soot.*;
import soot.baf.*;
import soot.util.*;
public class BFieldPutInst extends AbstractInst implements FieldPutInst
{
SootFieldRef fieldRef;
public BFieldPutInst(SootFieldRef fieldRef)
{
if( fieldRef.isStatic() ) throw new RuntimeException("wrong static-ness");
this.fieldRef = fieldRef;
}
public int getInCount()
{
return 2;
}
public int getOutCount()
{
return 0;
}
public Object clone()
{
return new BFieldPutInst(fieldRef);
}
public int getInMachineCount()
{
return AbstractJasminClass.sizeOfType(fieldRef.type()) + 1;
}
public int getOutMachineCount()
{
return 0;
}
final public String getName() { return "fieldput"; }
final String getParameters()
{
return " " + fieldRef.getSignature();
}
protected void getParameters( UnitPrinter up ) {
up.literal(" ");
up.fieldRef(fieldRef);
}
public SootFieldRef getFieldRef() { return fieldRef; }
public SootField getField() { return fieldRef.resolve(); }
public void apply(Switch sw)
{
((InstSwitch) sw).caseFieldPutInst(this);
}
public boolean containsFieldRef() { return true; }
}
|
923d797a95b184d761ffcb45e89622a8738260bb | 2,239 | java | Java | Database Reverse Engineering/src/org/netbeans/jpa/modeler/reveng/database/generator/IPersistenceModelGenerator.java | foxerfly/Netbeans-JPA-Modeler | b1b92c10aaf97e6df97756713cb8324669c7f94b | [
"Apache-2.0"
] | 2 | 2017-06-05T13:26:44.000Z | 2021-06-27T18:02:36.000Z | Database Reverse Engineering/src/org/netbeans/jpa/modeler/reveng/database/generator/IPersistenceModelGenerator.java | foxerfly/Netbeans-JPA-Modeler | b1b92c10aaf97e6df97756713cb8324669c7f94b | [
"Apache-2.0"
] | null | null | null | Database Reverse Engineering/src/org/netbeans/jpa/modeler/reveng/database/generator/IPersistenceModelGenerator.java | foxerfly/Netbeans-JPA-Modeler | b1b92c10aaf97e6df97756713cb8324669c7f94b | [
"Apache-2.0"
] | null | null | null | 35.539683 | 80 | 0.737829 | 1,000,337 | /**
* Copyright [2014] Gaurav Gupta
*
* 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.netbeans.jpa.modeler.reveng.database.generator;
import java.io.IOException;
import java.util.Set;
import org.netbeans.api.progress.aggregate.ProgressContributor;
import org.netbeans.jpa.modeler.reveng.database.ImportHelper;
import org.netbeans.modules.j2ee.persistence.wizard.fromdb.ProgressPanel;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
/**
* This interface allows project implementation to provide a custom generator of
* ORM Java classes from a DB model.
*/
public interface IPersistenceModelGenerator {
void init(WizardDescriptor wiz);
void uninit();
String getFQClassName(String tableName);
String generateEntityName(String className);
/**
* Generates entity beans / entity classes based on the model represented by
* the given <code>helper</code>.
*
* @param progressPanel the panel for displaying progress during the
* generation, or null if no panel should be displayed.
* @param helper the helper that specifies the generation options
* @param dcschemafile the schema for generating.
* @param progressContributor the progress contributor for the generation
* process.
*
*/
void generateModel(final ProgressPanel progressPanel,
final ImportHelper helper,
final FileObject dbschemaFile,
final ProgressContributor progressContributor) throws IOException;
/**
* @return a set of <code>FileObject</code>s representing the generated
* classes or an empty set if no classes were generated, never null.
*/
Set<FileObject> createdObjects();
}
|
923d799f7492c6e290718df6232f6149cc2944ba | 5,094 | java | Java | src/main/java/org/verdictdb/connection/StaticMetaData.java | mozafari/verdict | 48533d410cbbc91dc2ce41506edde9e04004c6b8 | [
"Apache-2.0"
] | 82 | 2016-05-06T22:15:41.000Z | 2018-03-26T17:10:07.000Z | src/main/java/org/verdictdb/connection/StaticMetaData.java | mozafari/verdict | 48533d410cbbc91dc2ce41506edde9e04004c6b8 | [
"Apache-2.0"
] | 65 | 2016-05-07T20:36:32.000Z | 2018-03-22T21:30:53.000Z | src/main/java/org/verdictdb/connection/StaticMetaData.java | mozafari/verdict | 48533d410cbbc91dc2ce41506edde9e04004c6b8 | [
"Apache-2.0"
] | 23 | 2016-07-02T17:14:09.000Z | 2018-03-23T17:48:14.000Z | 32.240506 | 98 | 0.708284 | 1,000,338 | /*
* Copyright 2018 University of Michigan
*
* 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.verdictdb.connection;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.verdictdb.commons.DataTypeConverter;
import org.verdictdb.exception.VerdictDBDbmsException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StaticMetaData implements MetaDataProvider {
public static class TableInfo {
String schema;
String tablename;
public TableInfo(String schema, String tablename) {
this.schema = schema;
this.tablename = tablename;
}
public static TableInfo getTableInfo(String schema, String tablename) {
return new TableInfo(schema, tablename);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
private String defaultSchema = "";
// The value pair: left is column name and right is its type
private HashMap<TableInfo, List<Pair<String, Integer>>> tablesData = new HashMap<>();
private List<String> schemas = new ArrayList<>();
private HashMap<String, List<String>> tables = new HashMap<>();
// TODO: what is the difference from tableData?
private HashMap<Pair<String, String>, List<Pair<String, Integer>>> columns = new HashMap<>();
private HashMap<Pair<String, String>, List<String>> partitions = new HashMap<>();
public StaticMetaData() {}
public StaticMetaData(HashMap<TableInfo, List<Pair<String, Integer>>> tablesData) {
this.tablesData = tablesData;
for (Map.Entry<TableInfo, List<Pair<String, Integer>>> entry : tablesData.entrySet()) {
if (!schemas.contains(entry.getKey().schema)) {
schemas.add(entry.getKey().schema);
}
tables.get(entry.getKey().schema).add(entry.getKey().tablename);
columns.put(
new ImmutablePair<>(entry.getKey().schema, entry.getKey().tablename), entry.getValue());
}
}
public void addTableData(TableInfo table, List<Pair<String, Integer>> column) {
tablesData.put(table, column);
if (!schemas.contains(table.schema)) {
schemas.add(table.schema);
tables.put(table.schema, new ArrayList<String>());
}
tables.get(table.schema).add(table.tablename);
columns.put(new ImmutablePair<>(table.schema, table.tablename), column);
}
public void addPartition(TableInfo table, List<String> column) {
partitions.put(new ImmutablePair<>(table.schema, table.tablename), column);
}
public void setDefaultSchema(String schema) {
defaultSchema = schema;
}
@Override
public List<String> getPrimaryKey(String schema, String table) throws VerdictDBDbmsException {
return null;
}
@Override
public List<String> getSchemas() {
return schemas;
}
@Override
public List<String> getTables(String schema) {
return tables.get(schema);
}
@Override
public List<Pair<String, String>> getColumns(String schema, String table) {
List<Pair<String, String>> nameAndType = new ArrayList<>();
List<Pair<String, Integer>> nameAndIntType = columns.get(new ImmutablePair<>(schema, table));
for (Pair<String, Integer> a : nameAndIntType) {
nameAndType.add(Pair.of(a.getLeft(), DataTypeConverter.typeName(a.getRight())));
}
return nameAndType;
}
// ignores catalog
@Override
public List<Pair<String, String>> getColumns(String catalog, String schema, String table) {
List<Pair<String, String>> nameAndType = new ArrayList<>();
List<Pair<String, Integer>> nameAndIntType = columns.get(new ImmutablePair<>(schema, table));
for (Pair<String, Integer> a : nameAndIntType) {
nameAndType.add(Pair.of(a.getLeft(), DataTypeConverter.typeName(a.getRight())));
}
return nameAndType;
}
@Override
public List<String> getPartitionColumns(String schema, String table) {
return partitions.get(new ImmutablePair<>(schema, table));
}
public String getDefaultSchema() {
return defaultSchema;
}
public HashMap<TableInfo, List<Pair<String, Integer>>> getTablesData() {
return tablesData;
}
}
|
923d7a8fcb1447d24b247769cc97db16d222ae5b | 1,007 | java | Java | components/gateway-model/src/main/java/io/fabric8/gateway/model/loadbalancer/RoundRobinLoadBalanceDefinition.java | rcernich/fabric8io-fabric8 | 551d151c5d6d2d8c24d5d35877bfec79a5210153 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2016-04-30T14:17:14.000Z | 2016-04-30T14:17:14.000Z | components/gateway-model/src/main/java/io/fabric8/gateway/model/loadbalancer/RoundRobinLoadBalanceDefinition.java | rcernich/fabric8io-fabric8 | 551d151c5d6d2d8c24d5d35877bfec79a5210153 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | components/gateway-model/src/main/java/io/fabric8/gateway/model/loadbalancer/RoundRobinLoadBalanceDefinition.java | rcernich/fabric8io-fabric8 | 551d151c5d6d2d8c24d5d35877bfec79a5210153 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 34.724138 | 77 | 0.746773 | 1,000,339 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.gateway.model.loadbalancer;
import io.fabric8.gateway.loadbalancer.LoadBalancer;
import io.fabric8.gateway.loadbalancer.RoundRobinLoadBalancer;
/**
*/
public class RoundRobinLoadBalanceDefinition extends LoadBalancerDefinition {
@Override
protected LoadBalancer createLoadBalancer() {
return new RoundRobinLoadBalancer();
}
}
|
923d7a9d2822d9534057c96b8f515109605b1433 | 957 | java | Java | apex-checks/src/test/java/org/fundacionjala/enforce/sonarqube/apex/checks/BrokenNullCheckTest.java | Nagendra080389/ApexReviewer | 53cd024b113e8e7b1264634cc7fb5e318df9eb27 | [
"MIT"
] | null | null | null | apex-checks/src/test/java/org/fundacionjala/enforce/sonarqube/apex/checks/BrokenNullCheckTest.java | Nagendra080389/ApexReviewer | 53cd024b113e8e7b1264634cc7fb5e318df9eb27 | [
"MIT"
] | null | null | null | apex-checks/src/test/java/org/fundacionjala/enforce/sonarqube/apex/checks/BrokenNullCheckTest.java | Nagendra080389/ApexReviewer | 53cd024b113e8e7b1264634cc7fb5e318df9eb27 | [
"MIT"
] | null | null | null | 36.807692 | 155 | 0.755486 | 1,000,340 | package org.fundacionjala.enforce.sonarqube.apex.checks;
import static org.fundacionjala.enforce.sonarqube.apex.ApexAstScanner.scanFile;
import java.io.File;
import org.junit.Test;
import org.sonar.squidbridge.api.SourceFile;
import org.sonar.squidbridge.checks.CheckMessagesVerifier;
public class BrokenNullCheckTest {
private SourceFile sourceFile;
private BrokenNullCheck check;
@Test
public void TestAvoidEmptyFinally() {
check = new BrokenNullCheck();
sourceFile = scanFile(new File("src/test/resources/checks/BrokenNullcheckTest.cls"), check);
CheckMessagesVerifier.verify(sourceFile.getCheckMessages())
.next().atLine(6).withMessage("Broken null check - ensure your string has appropriate null checks i.e., use (!= null && != blank) or (=null || =blank)")
.next().atLine(17).withMessage("Broken null check - ensure your string has appropriate null checks i.e., use (!= null && != blank) or (=null || =blank)")
.noMore();
}
}
|
923d7acf726258d99a2ac25ee460642d585efd2d | 4,621 | java | Java | module/src/main/java/zipkin/module/aws/sqs/ZipkinSQSCredentialsConfiguration.java | trajano/zipkin-aws | 5c73661158841a2fc90d21bfa1ac8c14a6587ede | [
"Apache-2.0"
] | 70 | 2016-10-01T03:11:39.000Z | 2021-11-10T04:26:07.000Z | module/src/main/java/zipkin/module/aws/sqs/ZipkinSQSCredentialsConfiguration.java | trajano/zipkin-aws | 5c73661158841a2fc90d21bfa1ac8c14a6587ede | [
"Apache-2.0"
] | 132 | 2016-09-29T14:10:58.000Z | 2022-02-12T05:03:06.000Z | module/src/main/java/zipkin/module/aws/sqs/ZipkinSQSCredentialsConfiguration.java | trajano/zipkin-aws | 5c73661158841a2fc90d21bfa1ac8c14a6587ede | [
"Apache-2.0"
] | 32 | 2016-09-29T13:46:10.000Z | 2022-02-12T05:43:11.000Z | 39.836207 | 100 | 0.77494 | 1,000,341 | /*
* Copyright 2016-2020 The OpenZipkin 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 zipkin.module.aws.sqs;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
@Configuration
@EnableConfigurationProperties(ZipkinSQSCollectorProperties.class)
@Conditional(ZipkinSQSCollectorModule.SQSSetCondition.class)
class ZipkinSQSCredentialsConfiguration {
/** Setup {@link AWSSecurityTokenService} client an IAM role to assume is given. */
@Bean
@ConditionalOnMissingBean
@Conditional(STSSetCondition.class)
AWSSecurityTokenService securityTokenService(ZipkinSQSCollectorProperties properties) {
return AWSSecurityTokenServiceClientBuilder.standard()
.withCredentials(getDefaultCredentialsProvider(properties))
.withRegion(properties.awsStsRegion)
.build();
}
@Autowired(required = false)
private AWSSecurityTokenService securityTokenService;
/** By default, get credentials from the {@link DefaultAWSCredentialsProviderChain */
@Bean
@ConditionalOnMissingBean
AWSCredentialsProvider credentialsProvider(ZipkinSQSCollectorProperties properties) {
if (securityTokenService != null) {
return new STSAssumeRoleSessionCredentialsProvider.Builder(
properties.awsStsRoleArn, "zipkin-server")
.withStsClient(securityTokenService)
.build();
} else {
return getDefaultCredentialsProvider(properties);
}
}
private static AWSCredentialsProvider getDefaultCredentialsProvider(
ZipkinSQSCollectorProperties properties) {
AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain();
// Create credentials provider from ID and secret if given.
if (!isNullOrEmpty(properties.awsAccessKeyId)
&& !isNullOrEmpty(properties.awsSecretAccessKey)) {
provider =
new AWSStaticCredentialsProvider(
new BasicAWSCredentials(properties.awsAccessKeyId, properties.awsSecretAccessKey));
}
return provider;
}
private static boolean isNullOrEmpty(String value) {
return (value == null || value.equals(""));
}
/**
* This condition passes when {@link ZipkinSQSCollectorProperties#getAwsStsRoleArn()} is set to
* non-empty.
*
* <p>This is here because the yaml defaults this property to empty like this, and spring-boot
* doesn't have an option to treat empty properties as unset.
*
* <pre>{@code
* aws-sts-role-arn: ${SQS_AWS_STS_ROLE_ARN:}
* }</pre>
*/
static final class STSSetCondition extends SpringBootCondition {
private static final String PROPERTY_NAME = "zipkin.collector.sqs.aws-sts-role-arn";
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata a) {
String queueUrl = context.getEnvironment().getProperty(PROPERTY_NAME);
return isEmpty(queueUrl)
? ConditionOutcome.noMatch(PROPERTY_NAME + " isn't set")
: ConditionOutcome.match();
}
private static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
}
}
|
923d7aeb9710323a244d14139df33e564491f230 | 1,412 | java | Java | immersionbar-sample/src/main/java/com/gyf/immersionbar/sample/activity/AllEditActivity.java | wangrunxiang/ImmersionBar | d2099d682e5a89e62b9953a8430a76261f59da08 | [
"Apache-2.0"
] | 10,841 | 2016-11-07T01:57:17.000Z | 2022-03-31T02:59:33.000Z | immersionbar-sample/src/main/java/com/gyf/immersionbar/sample/activity/AllEditActivity.java | wangrunxiang/ImmersionBar | d2099d682e5a89e62b9953a8430a76261f59da08 | [
"Apache-2.0"
] | 534 | 2017-05-03T07:18:19.000Z | 2022-03-31T06:49:33.000Z | immersionbar-sample/src/main/java/com/gyf/immersionbar/sample/activity/AllEditActivity.java | wangrunxiang/ImmersionBar | d2099d682e5a89e62b9953a8430a76261f59da08 | [
"Apache-2.0"
] | 1,879 | 2017-04-19T13:12:36.000Z | 2022-03-26T12:52:58.000Z | 26.641509 | 113 | 0.691218 | 1,000,342 | package com.gyf.immersionbar.sample.activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.sample.R;
import com.gyf.immersionbar.sample.adapter.EditAdapter;
import java.util.ArrayList;
import butterknife.BindView;
/**
* @author geyifeng
*/
public class AllEditActivity extends BaseActivity {
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
private ArrayList<String> mData = new ArrayList<>();
@Override
protected int getLayoutId() {
return R.layout.activity_all_edit;
}
@Override
protected void initImmersionBar() {
super.initImmersionBar();
ImmersionBar.with(this).titleBar(R.id.toolbar).keyboardEnable(true).init();
}
@Override
protected void initData() {
super.initData();
for (int i = 0; i < 20; i++) {
mData.add(String.valueOf(i));
}
}
@Override
protected void initView() {
super.initView();
EditAdapter adapter = new EditAdapter();
adapter.addHeaderView(LayoutInflater.from(this).inflate(R.layout.item_edit_header, recyclerView, false));
adapter.addFooterView(LayoutInflater.from(this).inflate(R.layout.item_edit_footer, recyclerView, false));
adapter.setNewData(mData);
recyclerView.setAdapter(adapter);
}
}
|
923d7b83b813c6bdd796d6dae5fb78274f36b8cd | 181 | java | Java | oym-demo-base/oym-demo-web/src/main/java/com/oym/base/web/model/BaseDto.java | 5zyd14/zyd-demo | 8e8403bc4752890f1571cba90ae1efc58bcdf1cc | [
"MIT"
] | 2 | 2019-10-15T02:52:18.000Z | 2019-11-25T00:49:41.000Z | oym-demo-base/oym-demo-web/src/main/java/com/oym/base/web/model/BaseDto.java | Oh-YoungMan/oym-demo | 8e8403bc4752890f1571cba90ae1efc58bcdf1cc | [
"MIT"
] | 6 | 2020-10-21T01:37:01.000Z | 2020-10-21T05:05:54.000Z | oym-demo-base/oym-demo-web/src/main/java/com/oym/base/web/model/BaseDto.java | Oh-YoungMan/oym-demo | 8e8403bc4752890f1571cba90ae1efc58bcdf1cc | [
"MIT"
] | null | null | null | 15.083333 | 47 | 0.707182 | 1,000,343 | package com.oym.base.web.model;
import java.io.Serializable;
/**
* @author zhangyd
* @date 2019/10/27 4:14
* @desc dto抽象类
*/
public interface BaseDto extends Serializable {
}
|
923d7bdc85fdf2d34a91cd80dae57952385a05d7 | 2,257 | java | Java | bisectPlugin/bisectPlugin-server/src/main/java/org/tkirill/teamcity/bisectPlugin/BisectController.java | tkirill/tc-bisect | 003c219c00231d01c03c8ee375fa9675dcd737b1 | [
"MIT"
] | 11 | 2015-06-14T17:33:29.000Z | 2022-02-25T01:51:43.000Z | bisectPlugin/bisectPlugin-server/src/main/java/org/tkirill/teamcity/bisectPlugin/BisectController.java | tkirill/tc-bisect | 003c219c00231d01c03c8ee375fa9675dcd737b1 | [
"MIT"
] | 5 | 2015-06-15T05:17:04.000Z | 2015-09-22T06:30:08.000Z | bisectPlugin/bisectPlugin-server/src/main/java/org/tkirill/teamcity/bisectPlugin/BisectController.java | tkirill/tc-bisect | 003c219c00231d01c03c8ee375fa9675dcd737b1 | [
"MIT"
] | 2 | 2016-10-09T12:17:34.000Z | 2019-10-10T21:34:58.000Z | 35.265625 | 133 | 0.70093 | 1,000,344 | package org.tkirill.teamcity.bisectPlugin;
import jetbrains.buildServer.controllers.BaseFormXmlController;
import jetbrains.buildServer.serverSide.CustomDataStorage;
import jetbrains.buildServer.serverSide.SBuild;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.vcs.SVcsModification;
import jetbrains.buildServer.web.openapi.WebControllerManager;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class BisectController extends BaseFormXmlController {
public BisectController(SBuildServer server, WebControllerManager manager) {
super(server);
manager.registerController("/bisect/run.html", this);
}
@Override
protected ModelAndView doGet(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response) {
return null;
}
@Override
protected void doPost(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Element xmlResponse) {
long buildId = Long.parseLong(request.getParameter("buildId"));
SBuild build = myServer.findBuildInstanceById(buildId);
if (build == null) {
response.setStatus(404);
return;
}
CustomDataStorage storage = build.getBuildType().getCustomDataStorage("bisectPlugin");
BisectRepository repository = new BisectRepository(storage);
if (!repository.exists(buildId)) {
try {
Bisect bisect = new Bisect(buildId);
bisect.setChanges(getChangeIds(build));
repository.save(bisect);
} catch (IOException e) {
response.setStatus(500);
return;
}
}
response.setStatus(200);
}
private List<Long> getChangeIds(SBuild build) {
List<Long> result = new ArrayList<Long>();
for (SVcsModification modification : build.getContainingChanges()) {
result.add(modification.getId());
}
return result;
}
}
|
923d7bdfde5ce7f57d312e41c01fc5b9f4b2e8cb | 219 | java | Java | 2-restapi/Aufgabe_Alle_Meine_Stromkreise_Bewertung/src/test/java/dhbwka/wwi/vertsys/rest/amsreview/ApplicationTests.java | DennisSchulmeister/dhbwka-wwi-vertsys-2020-quellcodes | 9c1fb4e7b70942d41529991fd95022aff7f44e72 | [
"CC-BY-4.0"
] | null | null | null | 2-restapi/Aufgabe_Alle_Meine_Stromkreise_Bewertung/src/test/java/dhbwka/wwi/vertsys/rest/amsreview/ApplicationTests.java | DennisSchulmeister/dhbwka-wwi-vertsys-2020-quellcodes | 9c1fb4e7b70942d41529991fd95022aff7f44e72 | [
"CC-BY-4.0"
] | 1 | 2021-03-11T11:45:12.000Z | 2021-03-11T11:45:12.000Z | 2-restapi/Loesung_Alle_Meine_Stromkreise_Bewertung/src/test/java/dhbwka/wwi/vertsys/rest/amsreview/ApplicationTests.java | DennisSchulmeister/dhbwka-wwi-vertsys-2020-quellcodes | 9c1fb4e7b70942d41529991fd95022aff7f44e72 | [
"CC-BY-4.0"
] | 5 | 2021-01-24T08:42:06.000Z | 2021-05-29T22:10:33.000Z | 15.642857 | 60 | 0.785388 | 1,000,345 | package dhbwka.wwi.vertsys.rest.amsreview;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApplicationTests {
@Test
void contextLoads() {
}
}
|
923d7c4b8116b99265dd783546698e88ea6aadc5 | 1,677 | java | Java | app/src/main/java/com/flys/fragments/behavior/SplashScreenFragment.java | amadoubakari/G-Learning | 81f062c12c7959780097df1fa9994ba2554ea1df | [
"MIT"
] | 2 | 2020-07-11T20:28:32.000Z | 2021-10-07T06:47:57.000Z | app/src/main/java/com/flys/fragments/behavior/SplashScreenFragment.java | amadoubakari/G-Learning | 81f062c12c7959780097df1fa9994ba2554ea1df | [
"MIT"
] | null | null | null | app/src/main/java/com/flys/fragments/behavior/SplashScreenFragment.java | amadoubakari/G-Learning | 81f062c12c7959780097df1fa9994ba2554ea1df | [
"MIT"
] | null | null | null | 24.304348 | 90 | 0.721527 | 1,000,346 | package com.flys.fragments.behavior;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OptionsMenu;
import com.flys.R;
import com.flys.architecture.core.AbstractFragment;
import com.flys.architecture.core.ISession;
import com.flys.architecture.custom.CoreState;
@EFragment(R.layout.fragment_splash_screen)
@OptionsMenu(R.menu.menu_vide)
public class SplashScreenFragment extends AbstractFragment {
@Override
public CoreState saveFragment() {
return new CoreState();
}
@Override
protected int getNumView() {
return mainActivity.SPLASHSCREEN_FRAGMENT;
}
@Override
protected void initFragment(CoreState previousState) {
// ((AppCompatActivity) mainActivity).getSupportActionBar().hide();
}
@Override
protected void initView(CoreState previousState) {
//Necessary time in milisecond to launch the application
int WAITING_TIME = 1500;
new Handler().postDelayed(() -> {
mainActivity.navigateToView(mainActivity.FISH_FRAGMENT, ISession.Action.NONE);
}, WAITING_TIME);
}
@Override
protected void updateOnSubmit(CoreState previousState) {
}
@Override
protected void updateOnRestore(CoreState previousState) {
}
@Override
protected void notifyEndOfUpdates() {
}
@Override
protected void notifyEndOfTasks(boolean runningTasksHaveBeenCanceled) {
}
//Nous cachons le bottom navigation view
@Override
protected boolean hideNavigationBottomView() {
return true;
}
}
|
923d7c8371712d9acf39c31c287873e3b36508f1 | 920 | java | Java | api/src/main/java/com/kids/api/notification/FCMNotification.java | hyungjun26/kicolearn | f76bbeee52a1a1cf9d40705bc5e27d536dcf8ac2 | [
"MIT"
] | null | null | null | api/src/main/java/com/kids/api/notification/FCMNotification.java | hyungjun26/kicolearn | f76bbeee52a1a1cf9d40705bc5e27d536dcf8ac2 | [
"MIT"
] | null | null | null | api/src/main/java/com/kids/api/notification/FCMNotification.java | hyungjun26/kicolearn | f76bbeee52a1a1cf9d40705bc5e27d536dcf8ac2 | [
"MIT"
] | 1 | 2020-11-17T01:55:11.000Z | 2020-11-17T01:55:11.000Z | 24.864865 | 89 | 0.652174 | 1,000,347 | package com.kids.api.notification;
import org.json.JSONObject;
import com.kids.api.notification.model.exception.NotificationNotFoundException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.SuperBuilder;
@Data
@AllArgsConstructor
@SuperBuilder
public class FCMNotification {
private String to;
private NotificationData data;
private Notification notification;
public JSONObject toJSON() {
// if (this.notification == null) {
// throw new NotificationNotFoundException(this, "cannot found notification");
// }
JSONObject body = new JSONObject();
body.put("to", this.to);
if (this.data != null) {
body.put("data", this.data.toJSON());
}
if (this.notification != null) {
body.put("notification", this.notification.toJSON());
}
return body;
}
}
|
923d7da08497ffdc285fe872f9d8ef0893608c60 | 2,264 | java | Java | PCP/src/main/java/PCP/data/PCPVariablePayload.java | JacopoWolf/PotatoChatProtocol | eea339951c3a2ab354adb7651a7f2242d7ce55b0 | [
"Unlicense"
] | 12 | 2019-10-25T15:15:41.000Z | 2020-04-23T18:10:36.000Z | PCP/src/main/java/PCP/data/PCPVariablePayload.java | JacopoWolf/PotatoChatProtocol | eea339951c3a2ab354adb7651a7f2242d7ce55b0 | [
"Unlicense"
] | 62 | 2019-10-20T10:10:01.000Z | 2020-04-06T06:39:19.000Z | PCP/src/main/java/PCP/data/PCPVariablePayload.java | JacopoWolf/PotatoChatProtocol | eea339951c3a2ab354adb7651a7f2242d7ce55b0 | [
"Unlicense"
] | 11 | 2019-10-25T11:04:32.000Z | 2021-02-17T09:45:29.000Z | 28.3 | 92 | 0.503092 | 1,000,348 | /*
* this is a school project under "The Unlicence".
*/
package PCP.data;
import java.nio.charset.*;
import java.util.*;
/**
*
* @author Jacopo_Wolf
*/
public abstract class PCPVariablePayload implements IPCPData
{
/**
*
* @return the variable lenght message to send
*/
abstract public String getMessage();
@Override
public final Collection<byte[]> toBytes()
{
// puts message here
Collection<byte[]> out = new ArrayList<>();
// allocates byte arrays
byte[] messageBytes = this.getMessage().getBytes( StandardCharsets.ISO_8859_1 );
byte[] header = this.header();
// necessary to calculation
int msgRelativeMaxLenght =
// MAX - header - payloadDelimitator
this.getVersion().MAX_PACKET_LENGHT - header.length - 1;
int nPacketsToSent =
// ( msgTOT / msgREL ) + 1
( this.getMessage().length() / msgRelativeMaxLenght ) + 1 ;
int absMsgPointer = 0; // absolute message pointer
int packetN = 0; // current packet number
for ( ; packetN < nPacketsToSent; packetN++ )
{
int bufferLenght =
( messageBytes.length - absMsgPointer ) > msgRelativeMaxLenght ?
this.getVersion().MAX_PACKET_LENGHT :
(header.length + (messageBytes.length - absMsgPointer) + 1);
byte[] buffer = new byte[ bufferLenght ];
int i = 0;
// appends header
for( byte b : this.header() )
buffer[i++] = b;
// appends message payload
for
(
int relMsgPointer = 0;
relMsgPointer < msgRelativeMaxLenght && absMsgPointer < messageBytes.length;
relMsgPointer++, absMsgPointer++
)
{
buffer[i++] = messageBytes[ absMsgPointer ];
}
// delimitator
buffer[i++] = 0;
// add current packet to the list
out.add(buffer);
}
return out;
}
}
|
923d7f21c012531d19a36a5840954ccf85b12416 | 5,307 | java | Java | aws-connect-instance/src/test/java/software/amazon/connect/instance/ListHandlerTest.java | darthe/aws-cloudformation-resource-providers-connect | d676e65bbaaf03e767957e363b7670feffdf02f7 | [
"Apache-2.0"
] | null | null | null | aws-connect-instance/src/test/java/software/amazon/connect/instance/ListHandlerTest.java | darthe/aws-cloudformation-resource-providers-connect | d676e65bbaaf03e767957e363b7670feffdf02f7 | [
"Apache-2.0"
] | null | null | null | aws-connect-instance/src/test/java/software/amazon/connect/instance/ListHandlerTest.java | darthe/aws-cloudformation-resource-providers-connect | d676e65bbaaf03e767957e363b7670feffdf02f7 | [
"Apache-2.0"
] | null | null | null | 45.75 | 167 | 0.74072 | 1,000,349 | package software.amazon.connect.instance;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import software.amazon.awssdk.services.connect.ConnectClient;
import software.amazon.awssdk.services.connect.model.*;
import software.amazon.cloudformation.exceptions.CfnGeneralServiceException;
import software.amazon.cloudformation.proxy.Credentials;
import software.amazon.cloudformation.proxy.*;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.connect.instance.InstanceTestDataProvider.*;
@ExtendWith(MockitoExtension.class)
public class ListHandlerTest {
private ListHandler handler;
private AmazonWebServicesClientProxy proxy;
private ProxyClient<ConnectClient> proxyClient;
private LoggerProxy logger;
@Mock
private ConnectClient connectClient;
@BeforeEach
public void setup() {
final Credentials MOCK_CREDENTIALS = new Credentials("accessKey", "secretKey", "token");
logger = new LoggerProxy();
handler = new ListHandler();
proxy = new AmazonWebServicesClientProxy(logger, MOCK_CREDENTIALS, () -> Duration.ofSeconds(600).toMillis());
proxyClient = proxy.newProxy(() -> connectClient);
}
@Test
public void testHandleRequest_SimpleSuccess() {
mockListInstancesRequest_Success();
mockListInstanceAttributesRequest_Success();
final ResourceModel model = ResourceModel.builder().build();
final ResourceHandlerRequest<ResourceModel> request = ResourceHandlerRequest.<ResourceModel>builder()
.desiredResourceState(model)
.build();
final ProgressEvent<ResourceModel, CallbackContext> response =
handler.handleRequest(proxy, request, new CallbackContext(), proxyClient, logger);
assertThat(response).isNotNull();
assertThat(response.getStatus()).isEqualTo(OperationStatus.SUCCESS);
assertThat(response.getCallbackContext()).isNull();
assertThat(response.getCallbackDelaySeconds()).isEqualTo(0);
assertThat(response.getResourceModel()).isNull();
assertThat(response.getResourceModels()).isNotNull();
assertThat(response.getMessage()).isNull();
assertThat(response.getErrorCode()).isNull();
}
@Test
public void testHandleRequest_Exception() {
final ResourceModel model = ResourceModel.builder().build();
final ResourceHandlerRequest<ResourceModel> request = ResourceHandlerRequest.<ResourceModel>builder()
.desiredResourceState(model)
.build();
final ArgumentCaptor<ListInstancesRequest> listInstancesRequestArgumentCaptor = ArgumentCaptor.forClass(ListInstancesRequest.class);
when(proxyClient.client().listInstances(listInstancesRequestArgumentCaptor.capture())).thenThrow(new RuntimeException());
assertThrows(CfnGeneralServiceException.class, () ->
handler.handleRequest(proxy, request, new CallbackContext(), proxyClient, logger));
verify(proxyClient.client()).listInstances(listInstancesRequestArgumentCaptor.capture());
}
private void mockListInstancesRequest_Success() {
final ArgumentCaptor<ListInstancesRequest> listInstancesRequestArgumentCaptor = ArgumentCaptor.forClass(ListInstancesRequest.class);
InstanceSummary summary = InstanceSummary.builder()
.arn(INSTANCE_ARN)
.id(INSTANCE_ID)
.instanceAlias(INSTANCE_ALIAS)
.instanceStatus(INSTANCE_STATUS_ACTIVE)
.createdTime(Instant.now())
.build();
List<InstanceSummary> summaryList = Lists.newArrayList(summary);
final ListInstancesResponse listInstancesResponse = ListInstancesResponse.builder()
.instanceSummaryList(summaryList)
.build();
when(proxyClient.client().listInstances(listInstancesRequestArgumentCaptor.capture())).thenReturn(listInstancesResponse);
}
private void mockListInstanceAttributesRequest_Success() {
final ArgumentCaptor<ListInstanceAttributesRequest> listInstanceAttributesRequestArgumentCaptor = ArgumentCaptor.forClass(ListInstanceAttributesRequest.class);
List<Attribute> attributes = Lists.newArrayList();
attributes.add(Attribute.builder().attributeType(InstanceAttributeType.INBOUND_CALLS).value("true").build());
attributes.add(Attribute.builder().attributeType(InstanceAttributeType.OUTBOUND_CALLS).value("true").build());
final ListInstanceAttributesResponse listInstanceAttributesResponse = ListInstanceAttributesResponse.builder()
.attributes(attributes)
.build();
when(proxyClient.client().listInstanceAttributes(listInstanceAttributesRequestArgumentCaptor.capture())).thenReturn(listInstanceAttributesResponse);
}
}
|
923d7f43d0bddff0234850a5f8d63d2c0fa75aec | 942 | java | Java | app/src/main/java/br/com/inaconsultoria/ireceitas/ui/adapter/RecyclerViewAdapterBase.java | lnfjunior/iReceitas | 66283e997c2c091cea26c5babcf5ec3c3a1ae3de | [
"MIT"
] | null | null | null | app/src/main/java/br/com/inaconsultoria/ireceitas/ui/adapter/RecyclerViewAdapterBase.java | lnfjunior/iReceitas | 66283e997c2c091cea26c5babcf5ec3c3a1ae3de | [
"MIT"
] | null | null | null | app/src/main/java/br/com/inaconsultoria/ireceitas/ui/adapter/RecyclerViewAdapterBase.java | lnfjunior/iReceitas | 66283e997c2c091cea26c5babcf5ec3c3a1ae3de | [
"MIT"
] | null | null | null | 22.97561 | 111 | 0.700637 | 1,000,350 | package br.com.inaconsultoria.ireceitas.ui.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* iReceitas
* Created by Luiz Nogueira on 16/12/2018
* All rights reserved 2018.
*/
public abstract class RecyclerViewAdapterBase<T, V extends View> extends RecyclerView.Adapter<ViewWrapper<V>> {
protected List<T> items = new ArrayList<T>();
@Override
public int getItemCount() {
return items.size();
}
@Override
public final ViewWrapper<V> onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewWrapper<V>(onCreateItemView(parent, viewType));
}
protected abstract V onCreateItemView(ViewGroup parent, int viewType);
public List<T> getItems() {
return items;
}
public void setItems(List<T> items) {
this.items = items;
}
}
|
923d7f6d9195ab100acdf0bcc2f1a58e609590e6 | 200 | java | Java | src/main/java/com/kasokuz/snaildb/controller/auth/response/LogResponse.java | white-snail/snaildb-api | 3b54bea60489aabb1830b8db1c9bfe87651a7222 | [
"MIT"
] | null | null | null | src/main/java/com/kasokuz/snaildb/controller/auth/response/LogResponse.java | white-snail/snaildb-api | 3b54bea60489aabb1830b8db1c9bfe87651a7222 | [
"MIT"
] | null | null | null | src/main/java/com/kasokuz/snaildb/controller/auth/response/LogResponse.java | white-snail/snaildb-api | 3b54bea60489aabb1830b8db1c9bfe87651a7222 | [
"MIT"
] | null | null | null | 16.666667 | 53 | 0.77 | 1,000,351 | package com.kasokuz.snaildb.controller.auth.response;
public class LogResponse {
public final Boolean successful;
public LogResponse(Boolean successful) {
this.successful = successful;
}
}
|
923d7fd7ff0ba2eb6c5fbc19af22ca46a83f4bdd | 1,498 | java | Java | test/plugin/scenarios/gateway-3.x-scenario/gateway-projectB-scenario/src/main/java/test/apache/skywalking/apm/testcase/sc/gateway/projectB/controller/TestController.java | geekymv/skywalking-java | 88a7778637a0c246e33b23e9ec88f70391c93802 | [
"Apache-2.0"
] | null | null | null | test/plugin/scenarios/gateway-3.x-scenario/gateway-projectB-scenario/src/main/java/test/apache/skywalking/apm/testcase/sc/gateway/projectB/controller/TestController.java | geekymv/skywalking-java | 88a7778637a0c246e33b23e9ec88f70391c93802 | [
"Apache-2.0"
] | null | null | null | test/plugin/scenarios/gateway-3.x-scenario/gateway-projectB-scenario/src/main/java/test/apache/skywalking/apm/testcase/sc/gateway/projectB/controller/TestController.java | geekymv/skywalking-java | 88a7778637a0c246e33b23e9ec88f70391c93802 | [
"Apache-2.0"
] | null | null | null | 36.536585 | 106 | 0.725634 | 1,000,352 | /*
* 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 test.apache.skywalking.apm.testcase.sc.gateway.projectB.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class TestController {
@RequestMapping("/provider/b/testcase")
public String testcase() {
try {
new RestTemplate().getForEntity("http://localhost:8080/provider/timeout/error", String.class);
} catch (Exception e) {
}
return "1";
}
@RequestMapping("/provider/b/healthCheck")
public String healthCheck() {
return "Success";
}
}
|
923d7fef2fdce80ba1c22c8b363cf29504128404 | 97 | java | Java | Maven/src/main/java/ProjetoPOO/negocios/AlunoInexistenteException.java | MatthewMartins/Repositorio_POO_Academia-FitPro | d59414cf7c33aa430a83e8d5d3cce9b9efa0ce95 | [
"Apache-2.0"
] | null | null | null | Maven/src/main/java/ProjetoPOO/negocios/AlunoInexistenteException.java | MatthewMartins/Repositorio_POO_Academia-FitPro | d59414cf7c33aa430a83e8d5d3cce9b9efa0ce95 | [
"Apache-2.0"
] | null | null | null | Maven/src/main/java/ProjetoPOO/negocios/AlunoInexistenteException.java | MatthewMartins/Repositorio_POO_Academia-FitPro | d59414cf7c33aa430a83e8d5d3cce9b9efa0ce95 | [
"Apache-2.0"
] | null | null | null | 16.166667 | 59 | 0.793814 | 1,000,353 | package ProjetoPOO.negocios;
public class AlunoInexistenteException extends Exception {
}
|
923d803866e3ca3e6dce863dad8d3d11416ec366 | 10,976 | java | Java | blocklylib-core/src/main/java/com/google/blockly/android/ui/mutator/ProcedureDefinitionMutatorFragment.java | Phuong06061994/blockly-android | 9dacf4def6e62429ab3c3d8de3b735b323e47d7b | [
"Apache-2.0"
] | 709 | 2016-05-17T15:33:00.000Z | 2022-03-30T05:43:46.000Z | blocklylib-core/src/main/java/com/google/blockly/android/ui/mutator/ProcedureDefinitionMutatorFragment.java | seanwallawalla-forks/blockly-android | 9dacf4def6e62429ab3c3d8de3b735b323e47d7b | [
"Apache-2.0"
] | 410 | 2016-05-19T23:51:48.000Z | 2021-04-30T08:53:17.000Z | blocklylib-core/src/main/java/com/google/blockly/android/ui/mutator/ProcedureDefinitionMutatorFragment.java | seanwallawalla-forks/blockly-android | 9dacf4def6e62429ab3c3d8de3b735b323e47d7b | [
"Apache-2.0"
] | 263 | 2016-05-17T23:25:35.000Z | 2022-02-14T21:07:57.000Z | 38.647887 | 99 | 0.646775 | 1,000,354 | /*
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.blockly.android.ui.mutator;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import com.google.blockly.android.R;
import com.google.blockly.android.control.BlocklyController;
import com.google.blockly.android.control.NameManager;
import com.google.blockly.android.control.ProcedureManager;
import com.google.blockly.android.control.ProcedureManager.ArgumentIndexUpdate;
import com.google.blockly.android.ui.MutatorFragment;
import com.google.blockly.model.Mutator;
import com.google.blockly.model.ProcedureInfo;
import com.google.blockly.model.mutator.ProcedureDefinitionMutator;
import java.util.ArrayList;
import java.util.List;
/**
* Standard UI fragment for editing the {@link ProcedureDefinitionMutator} attached to
* {@code procedures_defnoreturn} and {@code procedures_defreturn} blocks.
*/
public class ProcedureDefinitionMutatorFragment extends MutatorFragment {
public static final MutatorFragment.Factory FACTORY =
new MutatorFragment.Factory<ProcedureDefinitionMutatorFragment>() {
@Override
public ProcedureDefinitionMutatorFragment newMutatorFragment(Mutator mutator) {
ProcedureDefinitionMutatorFragment fragment =
new ProcedureDefinitionMutatorFragment();
fragment.init((ProcedureDefinitionMutator) mutator);
return fragment;
}
};
private static final int VH_TYPE_ARGUMENT = 1;
private static final int VH_TYPE_ADD = 2;
private static final int NO_ORIGINAL_INDEX = -1;
private static final String NEW_ARGUMENT_NAME = "x";
private BlocklyController mController;
private NameManager mVariableNameManager;
private ProcedureManager mProcedureManager;
private String mProcedureName;
private ArrayList<ArgInfo> mArgInfos = new ArrayList<>(); // Name, original index
private boolean mHasStatementInput = true;
private Adapter mAdapter;
private EditText mActiveArgNameField = null;
private RecyclerView mRecycler;
private void init(ProcedureDefinitionMutator mutator) {
mController = mutator.getBlock().getController();
mVariableNameManager = mController.getWorkspace().getVariableNameManager();
mProcedureManager = mController.getWorkspace().getProcedureManager();
mProcedureName = mutator.getProcedureName();
mHasStatementInput = mutator.hasStatementInput();
List<String> arguments = mutator.getArgumentNameList();
int count = arguments.size();
mArgInfos.clear();
mArgInfos.ensureCapacity(count);
for (int i = 0; i < count; ++i) {
mArgInfos.add(new ArgInfo(arguments.get(i), i));
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View contentView = inflater.inflate(
R.layout.procedure_definition_mutator_dialog, null, false);
String headerFormat = getString(R.string.mutator_procedure_def_header_format);
String headerText = String.format(headerFormat, mProcedureName);
TextView header = (TextView)contentView.findViewById(R.id.mutator_procedure_def_header);
header.setText(headerText);
mRecycler = (RecyclerView) contentView.findViewById(R.id.mutator_procedure_def_recycler);
mRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
mAdapter = new Adapter();
mRecycler.setAdapter(mAdapter);
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle(R.string.mutator_procedure_def_title)
.setPositiveButton(R.string.mutator_done, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishMutation();
}
})
.setView(contentView)
.create();
return dialog;
}
private View.OnClickListener mOnAddClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
int argPosition = mArgInfos.size();
mArgInfos.add(new ArgInfo(NEW_ARGUMENT_NAME, NO_ORIGINAL_INDEX));
mAdapter.notifyItemInserted(argPosition);
}
};
private View.OnClickListener mOnDeleteClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = mArgInfos.indexOf(v.getTag()); // Set by onBindViewHolder(..)
if (position >= 0) {
mArgInfos.remove(position);
mAdapter.notifyItemRemoved(position);
}
}
};
private View.OnFocusChangeListener mArgFocusChangeListener = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
EditText argNameField = (EditText) v;
if (hasFocus) {
mActiveArgNameField = argNameField;
} else {
validateAndApplyArgNameChange(argNameField);
mActiveArgNameField = null;
}
}
};
private void validateAndApplyArgNameChange(EditText argNameField) {
ArgInfo argInfo = (ArgInfo) argNameField.getTag();
String newName = argNameField.getText().toString();
newName = mVariableNameManager.makeValidName(newName, null);
if (newName != null && mVariableNameManager.getExisting(newName) == null) {
argInfo.name = newName;
}
}
private void finishMutation() {
if (mActiveArgNameField != null) {
validateAndApplyArgNameChange(mActiveArgNameField);
}
int count = mArgInfos.size();
List<String> argNames = new ArrayList<>(count);
List<ProcedureManager.ArgumentIndexUpdate> indexUpdates = null;
for (int i = 0; i < count; ++i) {
ArgInfo argInfo = mArgInfos.get(i);
argNames.add(argInfo.name);
if (argInfo.originalIndex != NO_ORIGINAL_INDEX) {
if (indexUpdates == null) {
indexUpdates = new ArrayList<>();
}
indexUpdates.add(new ArgumentIndexUpdate(argInfo.originalIndex, i));
}
}
mProcedureManager.mutateProcedure(mProcedureName,
new ProcedureInfo(mProcedureName, argNames, mHasStatementInput),
indexUpdates);
}
private static class ViewHolder extends RecyclerView.ViewHolder {
ImageButton mAddButton = null;
EditText mArgName = null;
ImageButton mDeleteButton = null;
public ViewHolder(View view, int viewType) {
super(view);
if (viewType == VH_TYPE_ADD) {
mAddButton = (ImageButton) view.findViewById(R.id.procedure_argument_add);
} else
if (viewType == VH_TYPE_ARGUMENT) {
mArgName = (EditText) view.findViewById(R.id.procedure_argument_name);
mDeleteButton = (ImageButton) view.findViewById(R.id.procedure_argument_delete);
}
}
}
private class Adapter extends RecyclerView.Adapter<ViewHolder> {
LayoutInflater mInflater;
public Adapter() {
mInflater = LayoutInflater.from(getContext());
}
@Override
public int getItemViewType(int position) {
if (position == mArgInfos.size()) {
return VH_TYPE_ADD;
} else {
return VH_TYPE_ARGUMENT;
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == VH_TYPE_ADD) {
view = mInflater.inflate(R.layout.procedure_definition_mutator_add, null);
} else if (viewType == VH_TYPE_ARGUMENT) {
view = mInflater.inflate(R.layout.procedure_definition_mutator_argument, null);
} else {
throw new IllegalStateException("Unrecognized view type " + viewType);
}
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.WRAP_CONTENT));
return new ViewHolder(view, viewType);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (holder.getItemViewType() == VH_TYPE_ADD) {
holder.mAddButton.setOnClickListener(mOnAddClick);
}
if (holder.getItemViewType() == VH_TYPE_ARGUMENT) {
ArgInfo arg = mArgInfos.get(position);
holder.mArgName.setText(arg.name);
holder.mArgName.setTag(arg);
holder.mArgName.setOnFocusChangeListener(mArgFocusChangeListener);
holder.mDeleteButton.setTag(arg);
holder.mDeleteButton.setOnClickListener(mOnDeleteClick);
}
}
@Override
public void onViewRecycled(ViewHolder holder) {
if (holder.mAddButton != null) {
holder.mAddButton.setOnClickListener(null);
holder.mAddButton.setTag(null);
}
if (holder.mDeleteButton != null) {
holder.mDeleteButton.setOnClickListener(null);
holder.mDeleteButton.setTag(null);
}
super.onViewRecycled(holder);
}
@Override
public int getItemCount() {
return mArgInfos.size() + 1;
}
}
private static final class ArgInfo {
ArgInfo(String name, int originalPosition) {
this.name = name;
this.originalIndex = originalPosition;
}
String name;
int originalIndex; // or NO_ORIGINAL_INDEX
}
}
|
923d80605da7a2020c97e2daaf82babf714ac893 | 4,121 | java | Java | json-object.native/src/test/java/org/kjots/json/object/ntive/NativeJsonObjectMapTest.java | kjots/json-toolkit | 3cf569bb4e385e87ab8ff8efe4ba0e470fae412e | [
"Apache-2.0"
] | null | null | null | json-object.native/src/test/java/org/kjots/json/object/ntive/NativeJsonObjectMapTest.java | kjots/json-toolkit | 3cf569bb4e385e87ab8ff8efe4ba0e470fae412e | [
"Apache-2.0"
] | null | null | null | json-object.native/src/test/java/org/kjots/json/object/ntive/NativeJsonObjectMapTest.java | kjots/json-toolkit | 3cf569bb4e385e87ab8ff8efe4ba0e470fae412e | [
"Apache-2.0"
] | 1 | 2019-04-23T03:01:41.000Z | 2019-04-23T03:01:41.000Z | 30.272059 | 149 | 0.685936 | 1,000,355 | /*
* Copyright © 2010 Karl J. Ots <hzdkv@example.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.kjots.json.object.ntive;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import com.google.inject.Guice;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.kjots.json.object.shared.JsonObject;
import org.kjots.json.object.shared.JsonObjectFactory;
import org.kjots.json.object.simple.SimpleJsonObjectModule;
/**
* Native JSON Object Map Test.
* <p>
* Created: 11th November 2010.
*
* @author <a href="mailto:hzdkv@example.com">Karl J. Ots <kjots@kjots.org></a>
* @since 1.0
*/
public class NativeJsonObjectMapTest {
/**
* Cast JSON Object.
*/
public static interface CastJsonObject extends JsonObject {
}
/** The test native JSON object map. */
private NativeJsonObjectMap<JsonObject> testNativeJsonObjectMap;
/**
* Setup the test class.
*/
@BeforeClass
public static void setupClass() {
Guice.createInjector(new SimpleJsonObjectModule());
}
/**
* Setup the test environment.
*/
@Before
public void setup() {
this.testNativeJsonObjectMap = new NativeJsonObjectMap<JsonObject>(JsonObject.class);
}
/**
* Test the casting of a JSON object map.
* <p>
* This test asserts that the native JSON object map correctly casts the
* element of the map to the class provided to the cast element method.
*/
@Test
public void testCastElement() {
NativeJsonObjectMap<CastJsonObject> testCastJsonObjectMap = testNativeJsonObjectMap.castElement(CastJsonObject.class);
testNativeJsonObjectMap.set("key", JsonObjectFactory.get().createJsonObject());
assertSame("testNativeJsonObjectMap.map !== testCastJsonObjectMap.map", testNativeJsonObjectMap.map, testCastJsonObjectMap.map);
assertTrue("testCastJsonObjectMap[0] !instanceof " + CastJsonObject.class.getName(), testCastJsonObjectMap.get("key") instanceof CastJsonObject);
}
/**
* Test the retrieval of an element of the map.
* <p>
* This test asserts that the native JSON object map correctly retrieves
* elements of the map.
*/
@Test
public void testGet() {
JsonObject[] jsonObjects = this.createJsonObjects(5);
for (int i = 0; i < 5; i++) {
testNativeJsonObjectMap.map.put(Integer.toString(i), jsonObjects[i]);
}
for (int i = 0; i < 5; i++) {
assertEquals("testJsonObjectMap[\"" + Integer.toString(i) + "\"]", jsonObjects[i], testNativeJsonObjectMap.get(Integer.toString(i)));
}
}
/**
* Test the setting of an element of the map.
* <p>
* This test asserts that the native JSON object map correctly sets
* elements of the map.
*/
@Test
public void testSet() {
JsonObject[] jsonObjects = this.createJsonObjects(5);
for (int i = 0; i < 5; i++) {
testNativeJsonObjectMap.set(Integer.toString(i), jsonObjects[i]);
}
for (int i = 0; i < 5; i++) {
assertEquals("object[\"" + Integer.toString(i) + "\"]", jsonObjects[i], ((JsonObject)testNativeJsonObjectMap.map.get(Integer.toString(i))));
}
}
/**
* Create an array of JSON objects.
*
* @param n The number of JSON objects.
* @return The JSON objects.
*/
private JsonObject[] createJsonObjects(int n) {
JsonObject[] jsonObjects = new JsonObject[n];
for (int i = 0; i < n; i++) {
jsonObjects[i] = JsonObjectFactory.get().createJsonObject();
}
return jsonObjects;
}
}
|
923d811623a2fe1641a40cfd1baa9e39510c6f84 | 1,170 | java | Java | sandbox/code-gen/src/main/java/org/apache/plc4x/codegen/ast/ExceptionType.java | apache/incubator-plc4x | e6899ef63e2456a64ef0bd1189d9a7c4472ef04c | [
"Apache-2.0"
] | 60 | 2017-12-20T12:46:34.000Z | 2019-04-15T13:42:45.000Z | sandbox/code-gen/src/main/java/org/apache/plc4x/codegen/ast/ExceptionType.java | apache/incubator-plc4x | e6899ef63e2456a64ef0bd1189d9a7c4472ef04c | [
"Apache-2.0"
] | 26 | 2018-01-08T22:48:29.000Z | 2019-04-10T08:39:44.000Z | sandbox/code-gen/src/main/java/org/apache/plc4x/codegen/ast/ExceptionType.java | apache/incubator-plc4x | e6899ef63e2456a64ef0bd1189d9a7c4472ef04c | [
"Apache-2.0"
] | 30 | 2018-01-08T14:04:22.000Z | 2019-04-05T09:43:28.000Z | 28.536585 | 63 | 0.717094 | 1,000,356 | /*
* 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
*
* 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.apache.plc4x.codegen.ast;
/**
* Defines an Exception-Type.
*/
public class ExceptionType extends TypeDefinition {
ExceptionType(String typeString) {
super(typeString);
}
@Override
public <T> T accept(NodeVisitor<T> visitor) {
return null;
}
@Override
public void write(Generator writer) {
}
}
|
923d82376dc683e8b50ecc125b9cc1b8d59bd749 | 284 | java | Java | src/main/java/me/vrnsky/server/repository/interfaces/RecipeRepo.java | vrnsky/recipeper-server | 0cd6ed2b25361f8738e2f3a31f13501e004d1d4c | [
"Apache-2.0"
] | null | null | null | src/main/java/me/vrnsky/server/repository/interfaces/RecipeRepo.java | vrnsky/recipeper-server | 0cd6ed2b25361f8738e2f3a31f13501e004d1d4c | [
"Apache-2.0"
] | 19 | 2018-09-18T19:13:47.000Z | 2022-02-16T01:15:43.000Z | src/main/java/me/vrnsky/server/repository/interfaces/RecipeRepo.java | vrnsky/recipeper-server | 0cd6ed2b25361f8738e2f3a31f13501e004d1d4c | [
"Apache-2.0"
] | null | null | null | 21.846154 | 66 | 0.788732 | 1,000,357 | package me.vrnsky.server.repository.interfaces;
import me.vrnsky.server.domain.Recipe;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface RecipeRepo extends CrudRepository<Recipe, Long> {
@Override
List<Recipe> findAll();
}
|
923d83196cc2d23ac4ff8d094fe6e1319b0dc525 | 702 | java | Java | br.ufscar.sas.annotations/src/br/ufscar/sas/annotations/Activator.java | dsanmartins/PhdProject | 5d936be205ee23140cacbd10bf8217015b39a2b8 | [
"Apache-2.0"
] | null | null | null | br.ufscar.sas.annotations/src/br/ufscar/sas/annotations/Activator.java | dsanmartins/PhdProject | 5d936be205ee23140cacbd10bf8217015b39a2b8 | [
"Apache-2.0"
] | null | null | null | br.ufscar.sas.annotations/src/br/ufscar/sas/annotations/Activator.java | dsanmartins/PhdProject | 5d936be205ee23140cacbd10bf8217015b39a2b8 | [
"Apache-2.0"
] | null | null | null | 22.645161 | 83 | 0.763533 | 1,000,358 | package br.ufscar.sas.annotations;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
|
923d835bcdf74a9ad32cdb45da0117de6346f0c9 | 2,067 | java | Java | gtas-parent/gtas-parsers/src/main/java/gov/gtas/parsers/tamr/model/TamrMessage.java | alino1213/GTAS | 6e54f06edd8863895438da8188d4209e2dada3c9 | [
"BSD-3-Clause"
] | 90 | 2016-06-29T19:34:41.000Z | 2022-01-09T16:20:10.000Z | gtas-parent/gtas-parsers/src/main/java/gov/gtas/parsers/tamr/model/TamrMessage.java | alino1213/GTAS | 6e54f06edd8863895438da8188d4209e2dada3c9 | [
"BSD-3-Clause"
] | 1,765 | 2016-07-14T17:24:30.000Z | 2022-03-08T21:11:13.000Z | gtas-parent/gtas-parsers/src/main/java/gov/gtas/parsers/tamr/model/TamrMessage.java | alino1213/GTAS | 6e54f06edd8863895438da8188d4209e2dada3c9 | [
"BSD-3-Clause"
] | 142 | 2016-06-30T15:02:49.000Z | 2022-03-30T00:50:58.000Z | 24.317647 | 120 | 0.701016 | 1,000,359 | /*
* 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.parsers.tamr.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Model that encompasses all types of messages that can be sent from Tamr to
* GTAS.
* @author Cassidy Laidlaw
*/
public class TamrMessage {
/**
* The JMS message type, which is set by TamrMessageReceiver.
*/
@JsonIgnore
private TamrMessageType messageType;
private List<TamrTravelerResponse> travelerQuery;
private List<TamrHistoryCluster> historyClusters;
private Boolean acknowledgment = null;
private String error;
private List<TamrRecordError> recordErrors;
public TamrMessage() {
}
public TamrMessageType getMessageType() {
return messageType;
}
public void setMessageType(TamrMessageType messageType) {
this.messageType = messageType;
}
public List<TamrTravelerResponse> getTravelerQuery() {
return travelerQuery;
}
public void setTravelerQuery(List<TamrTravelerResponse> travelerQuery) {
this.travelerQuery = travelerQuery;
}
public List<TamrHistoryCluster> getHistoryClusters() {
return historyClusters;
}
public void setHistoryClusters(List<TamrHistoryCluster> historyClusters) {
this.historyClusters = historyClusters;
}
public Boolean getAcknowledgment() {
return acknowledgment;
}
public void setAcknowledgment(Boolean acknowledgment) {
this.acknowledgment = acknowledgment;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public List<TamrRecordError> getRecordErrors() {
return recordErrors;
}
public void setRecordErrors(List<TamrRecordError> recordErrors) {
this.recordErrors = recordErrors;
}
}
|
923d841e20f4ef97f83a29b8a3a8f39e917a39bc | 4,879 | java | Java | spiffyui/build/maven/maven-spiffyui-plugin/src/main/java/org/spiffyui/maven/plugins/BuildInfoMojo.java | spiffyui/spiffyui | d01cd1e66e081466cce48077b705b3790451f0dc | [
"Apache-2.0"
] | 5 | 2017-03-08T21:36:11.000Z | 2021-02-28T21:45:04.000Z | spiffyui/build/maven/maven-spiffyui-plugin/src/main/java/org/spiffyui/maven/plugins/BuildInfoMojo.java | spiffyui/spiffyui | d01cd1e66e081466cce48077b705b3790451f0dc | [
"Apache-2.0"
] | 2 | 2018-03-27T10:12:02.000Z | 2018-08-08T22:45:16.000Z | spiffyui/build/maven/maven-spiffyui-plugin/src/main/java/org/spiffyui/maven/plugins/BuildInfoMojo.java | spiffyui/spiffyui | d01cd1e66e081466cce48077b705b3790451f0dc | [
"Apache-2.0"
] | 2 | 2015-04-16T04:49:06.000Z | 2018-08-08T16:53:42.000Z | 32.311258 | 114 | 0.602173 | 1,000,360 | /*******************************************************************************
*
* Copyright 2011-2014 Spiffy UI Team
*
* 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.spiffyui.maven.plugins;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.json.JSONObject;
/**
* Generates a build-info descriptor. It is necessary to use the rev-info mojo
* prior to invoking this mojo, since the rev-info populates the @{code revision.number}
* and the @{code revision.date} properties.
*
* @goal build-info
* @phase generate-resources
*/
public class BuildInfoMojo extends AbstractMojo
{
/**
* The maven project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* The character encoding scheme to be applied exporting the JSON document
*
* @parameter expression="${encoding}" default-value="UTF-8"
*/
private String encoding;
/**
* The character encoding scheme to be applied exporting the JSON document
*
* @parameter expression="${dateFormat}" default-value="epoch"
*/
private String dateFormat;
/**
* The descriptor file to generate
*
* @parameter expression="${spiffyui.buildinfo.file}"
* default-value="${spiffyui.www}/build-info.json"
* @required
*/
private File outputFile;
/**
* The base directory of this project
*
* @parameter expression="${basedir}"
* @required
* @readonly
*/
private File basedir;
@Override
public void execute()
throws MojoExecutionException,
MojoFailureException
{
Properties p = project.getProperties();
String date = null;
if ("epoch".equals(dateFormat)) {
date = "" + new Date().getTime();
} else {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
date = sdf.format(cal.getTime());
}
List<Dependency> depsList = project.getDependencies();
Map<String, Dependency> deps = new HashMap<String, Dependency>();
for (Dependency dep : depsList) {
deps.put(dep.getArtifactId(), dep);
}
try {
File parent = outputFile.getParentFile();
if (!parent.exists()) {
FileUtils.forceMkdir(parent);
}
// Create file
PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFile), encoding));
JSONObject rev = new JSONObject();
rev.put("number", p.getProperty("revision.number"));
rev.put("date", p.getProperty("revision.date"));
JSONObject components = new JSONObject();
Dependency spiffyUiDep = deps.get("spiffyui");
String spiffyVer = (spiffyUiDep != null) ? spiffyUiDep.getVersion() : "n/a";
components.put("spiffyui", spiffyVer);
JSONObject info = new JSONObject();
info.put("schema", 1);
info.put("version", project.getVersion());
info.put("date", date);
info.put("user", System.getProperties().get("user.name"));
info.put("components", components);
info.put("revision", rev);
info.put("dir", basedir.getAbsolutePath());
out.write(info.toString());
// Close the output stream
out.close();
} catch (Exception e) { // Catch exception if any
throw new MojoExecutionException(e.getMessage());
}
}
}
|
923d84778546ef423d104377b69de9ae04db4eea | 1,242 | java | Java | src/main/java/com/mynamaneet/dolmodloader/file_classes/DolLocation.java | mynamaneet/DoL-ModLoader | 6ef39a3d84f30922175212b03bdcba5304581f27 | [
"MIT"
] | null | null | null | src/main/java/com/mynamaneet/dolmodloader/file_classes/DolLocation.java | mynamaneet/DoL-ModLoader | 6ef39a3d84f30922175212b03bdcba5304581f27 | [
"MIT"
] | null | null | null | src/main/java/com/mynamaneet/dolmodloader/file_classes/DolLocation.java | mynamaneet/DoL-ModLoader | 6ef39a3d84f30922175212b03bdcba5304581f27 | [
"MIT"
] | null | null | null | 24.84 | 95 | 0.651369 | 1,000,361 | package com.mynamaneet.dolmodloader.file_classes;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class DolLocation {
public DolLocation(File _directoryPath, String _name, String _parent){
this.directoryPath = _directoryPath;
this.name = _name;
this.parent = _parent;
}
public DolLocation(File _directoryPath, String _name, String _parent, boolean _hasChanged){
this.directoryPath = _directoryPath;
this.name = _name;
this.parent = _parent;
this.hasChanged = _hasChanged;
}
private File directoryPath;
private String name;
private String parent = "";
private ArrayList<TweeFile> tweeFiles = new ArrayList<>();
private boolean hasChanged = false;
public File getDirectoryPath(){
return directoryPath;
}
public String getName(){
return name;
}
public String getParent(){
return parent;
}
public List<TweeFile> getFiles(){
return tweeFiles;
}
public boolean hasChanged(){
return hasChanged;
}
public void addFile(TweeFile file){
tweeFiles.add(file);
}
public void setHasChanged(){
hasChanged = true;
}
}
|
923d86911572f4f405a7b0c3b623700c4356c032 | 4,375 | java | Java | thermo/CoMoIOChemistry/src/main/java/uk/ac/cam/ceb/como/io/chem/file/jaxb/Operator.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 21 | 2021-03-08T01:58:25.000Z | 2022-03-09T15:46:16.000Z | thermo/CoMoIOChemistry/src/main/java/uk/ac/cam/ceb/como/io/chem/file/jaxb/Operator.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 63 | 2021-05-04T15:05:30.000Z | 2022-03-23T14:32:29.000Z | thermo/CoMoIOChemistry/src/main/java/uk/ac/cam/ceb/como/io/chem/file/jaxb/Operator.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 15 | 2021-03-08T07:52:03.000Z | 2022-03-29T04:46:20.000Z | 24.305556 | 109 | 0.568 | 1,000,362 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.05.10 at 04:17:37 PM BST
//
package uk.ac.cam.ceb.como.io.chem.file.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <choice minOccurs="0">
* </choice>
* </sequence>
* <attGroup ref="{http://www.xml-cml.org/schema}dictRef"/>
* <attGroup ref="{http://www.xml-cml.org/schema}id"/>
* <attGroup ref="{http://www.xml-cml.org/schema}convention"/>
* <attGroup ref="{http://www.xml-cml.org/schema}title"/>
* <attGroup ref="{http://www.xml-cml.org/schema}type"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "operator")
public class Operator {
@XmlAttribute(name = "dictRef")
protected java.lang.String dictRef;
@XmlAttribute(name = "id")
protected java.lang.String id;
@XmlAttribute(name = "convention")
protected java.lang.String convention;
@XmlAttribute(name = "title")
protected java.lang.String title;
@XmlAttribute(name = "type")
protected java.lang.String type;
/**
* Gets the value of the dictRef property.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getDictRef() {
return dictRef;
}
/**
* Sets the value of the dictRef property.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setDictRef(java.lang.String value) {
this.dictRef = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setId(java.lang.String value) {
this.id = value;
}
/**
* Gets the value of the convention property.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getConvention() {
return convention;
}
/**
* Sets the value of the convention property.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setConvention(java.lang.String value) {
this.convention = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setTitle(java.lang.String value) {
this.title = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setType(java.lang.String value) {
this.type = value;
}
}
|
923d874f6a42b9ecbcf33b66f7d4f88b134d8359 | 2,324 | java | Java | Source/Plugins/Core/com.equella.core/src/com/tle/web/selection/home/sections/RootSelectionHomeSection.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 14 | 2019-10-09T23:59:32.000Z | 2022-03-01T08:34:56.000Z | Source/Plugins/Core/com.equella.core/src/com/tle/web/selection/home/sections/RootSelectionHomeSection.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 1,549 | 2019-08-16T01:07:16.000Z | 2022-03-31T23:57:34.000Z | Source/Plugins/Core/com.equella.core/src/com/tle/web/selection/home/sections/RootSelectionHomeSection.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 24 | 2019-09-05T00:09:35.000Z | 2021-10-19T05:10:39.000Z | 37.483871 | 88 | 0.787866 | 1,000,363 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.selection.home.sections;
import com.tle.web.resources.PluginResourceHelper;
import com.tle.web.resources.ResourcesService;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionResult;
import com.tle.web.sections.equella.layout.TwoColumnLayout;
import com.tle.web.sections.equella.layout.TwoColumnLayout.TwoColumnModel;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.selection.SelectionService;
import com.tle.web.selection.SelectionSession;
import com.tle.web.template.Breadcrumbs;
import com.tle.web.template.Decorations;
import javax.inject.Inject;
@SuppressWarnings("nls")
public class RootSelectionHomeSection extends TwoColumnLayout<TwoColumnModel> {
private static final PluginResourceHelper RESOURCES =
ResourcesService.getResourceHelper(RootSelectionHomeSection.class);
@Inject private SelectionService selectionService;
@Override
public SectionResult renderHtml(RenderEventContext context) {
SelectionSession session = selectionService.getCurrentSession(context);
if (session == null) {
throw new RuntimeException(RESOURCES.getString("error.requiresselectionsession"));
}
return super.renderHtml(context);
}
@Override
protected void addBreadcrumbsAndTitle(
SectionInfo info, Decorations decorations, Breadcrumbs crumbs) {
decorations.setContentBodyClass("selectiondashboard");
}
@Override
public Class<TwoColumnModel> getModelClass() {
return TwoColumnModel.class;
}
}
|
923d875a8a4d5de889184053a8ed6558e69fdff3 | 306 | java | Java | app/src/main/java/com/xujun/contralayout/base/permissions/PermissonListener.java | OnThinIce/CoordinatorLayoutDemo | e2a6978e3981da42e324ec30687f1aa0357276d6 | [
"Apache-2.0"
] | 958 | 2016-10-24T06:40:40.000Z | 2022-03-29T03:09:09.000Z | app/src/main/java/com/xujun/contralayout/base/permissions/PermissonListener.java | OnThinIce/CoordinatorLayoutDemo | e2a6978e3981da42e324ec30687f1aa0357276d6 | [
"Apache-2.0"
] | 17 | 2017-05-10T09:12:01.000Z | 2020-07-01T01:37:34.000Z | app/src/main/java/com/xujun/contralayout/base/permissions/PermissonListener.java | OnThinIce/CoordinatorLayoutDemo | e2a6978e3981da42e324ec30687f1aa0357276d6 | [
"Apache-2.0"
] | 173 | 2016-11-03T01:18:12.000Z | 2022-03-20T07:46:06.000Z | 17.055556 | 60 | 0.723127 | 1,000,364 | package com.xujun.contralayout.base.permissions;
import java.util.List;
/**
* @author xujun on 2016/12/27.
* lyhxr@example.com
*/
public interface PermissonListener {
void onGranted();
void onDenied(List<String> permisons);
void onParmanentDenied(List<String> parmanentDeniedPer);
}
|
923d87f33026a3c4f23893634bc0338816123337 | 2,715 | java | Java | components/camel-urlrewrite/src/test/java/org/apache/camel/component/urlrewrite/BaseUrlRewriteTest.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 13 | 2018-08-29T09:51:58.000Z | 2022-02-22T12:00:36.000Z | components/camel-urlrewrite/src/test/java/org/apache/camel/component/urlrewrite/BaseUrlRewriteTest.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 12 | 2019-11-13T03:09:32.000Z | 2022-02-01T01:05:20.000Z | components/camel-urlrewrite/src/test/java/org/apache/camel/component/urlrewrite/BaseUrlRewriteTest.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 202 | 2020-07-23T14:34:26.000Z | 2022-03-04T18:41:20.000Z | 32.710843 | 86 | 0.720074 | 1,000,365 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.urlrewrite;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.test.AvailablePortFinder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.BeforeClass;
/**
*
*/
public abstract class BaseUrlRewriteTest extends CamelTestSupport {
private static volatile int port;
private static volatile int port2;
private final AtomicInteger counter = new AtomicInteger(1);
@BeforeClass
public static void initPort() throws Exception {
// start from somewhere in the 23xxx range
port = AvailablePortFinder.getNextAvailable(23000);
// find another ports for proxy route test
port2 = AvailablePortFinder.getNextAvailable(24000);
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.addComponent("properties", new PropertiesComponent("ref:prop"));
return context;
}
@Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry jndi = super.createRegistry();
Properties prop = new Properties();
prop.setProperty("port", "" + getPort());
prop.setProperty("port2", "" + getPort2());
jndi.bind("prop", prop);
return jndi;
}
protected int getNextPort() {
return AvailablePortFinder.getNextAvailable(port + counter.getAndIncrement());
}
protected int getNextPort(int startWithPort) {
return AvailablePortFinder.getNextAvailable(startWithPort);
}
protected static int getPort() {
return port;
}
protected static int getPort2() {
return port2;
}
} |
923d88802bf9fe36cab3bcf026a6ae015c2b9c2c | 6,304 | java | Java | zookeeper-server/src/test/java/org/apache/zookeeper/server/embedded/ZookeeperServerClusterMutualAuthTest.java | tongjiaqiao/zookeeper | 69e8cf80168935edaf01e9e9024357780e1f54c2 | [
"Apache-2.0"
] | 2 | 2021-04-07T02:51:18.000Z | 2021-04-07T02:51:20.000Z | zookeeper-server/src/test/java/org/apache/zookeeper/server/embedded/ZookeeperServerClusterMutualAuthTest.java | tongjiaqiao/zookeeper | 69e8cf80168935edaf01e9e9024357780e1f54c2 | [
"Apache-2.0"
] | 1 | 2022-03-01T22:30:21.000Z | 2022-03-02T13:31:52.000Z | zookeeper-server/src/test/java/org/apache/zookeeper/server/embedded/ZookeeperServerClusterMutualAuthTest.java | tongjiaqiao/zookeeper | 69e8cf80168935edaf01e9e9024357780e1f54c2 | [
"Apache-2.0"
] | 1 | 2022-03-26T00:52:25.000Z | 2022-03-26T00:52:25.000Z | 44.394366 | 181 | 0.678299 | 1,000,366 | /**
* 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.zookeeper.server.embedded;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import javax.security.auth.login.Configuration;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.test.ClientBase;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Test Quorum Mutual Auth with ZooKeeperEmbedded.
*/
public class ZookeeperServerClusterMutualAuthTest {
@BeforeAll
public static void setUpEnvironment() {
System.setProperty("java.security.auth.login.config", new File("src/test/resources/embedded/test_jaas_server_auth.conf")
.getAbsolutePath());
Configuration.getConfiguration().refresh();
System.setProperty("zookeeper.admin.enableServer", "false");
System.setProperty("zookeeper.4lw.commands.whitelist", "*");
}
@AfterAll
public static void cleanUpEnvironment() throws InterruptedException, IOException {
System.clearProperty("zookeeper.admin.enableServer");
System.clearProperty("zookeeper.4lw.commands.whitelist");
System.clearProperty("java.security.auth.login.config");
Configuration.getConfiguration().refresh();
}
@TempDir
public Path baseDir;
@Test
public void testStart() throws Exception {
Path baseDir1 = baseDir.resolve("server1");
Path baseDir2 = baseDir.resolve("server2");
Path baseDir3 = baseDir.resolve("server3");
int clientport1 = PortAssignment.unique();
int clientport2 = PortAssignment.unique();
int clientport3 = PortAssignment.unique();
int port4 = PortAssignment.unique();
int port5 = PortAssignment.unique();
int port6 = PortAssignment.unique();
int port7 = PortAssignment.unique();
int port8 = PortAssignment.unique();
int port9 = PortAssignment.unique();
Properties config = new Properties();
config.put("host", "localhost");
config.put("ticktime", "10");
config.put("initLimit", "4000");
config.put("syncLimit", "5");
config.put("server.1", "localhost:" + port4 + ":" + port7);
config.put("server.2", "localhost:" + port5 + ":" + port8);
config.put("server.3", "localhost:" + port6 + ":" + port9);
config.put("quorum.auth.enableSasl", "true");
config.put("quorum.auth.learnerRequireSasl", "true");
config.put("quorum.auth.serverRequireSasl", "true");
config.put("quorum.auth.learner.loginContext", "QuorumLearner");
config.put("quorum.auth.server.loginContext", "QuorumServer");
config.put("quorum.auth.kerberos.servicePrincipal", "servicename/_HOST");
config.put("quorum.cnxn.threads.size", "20");
final Properties configZookeeper1 = new Properties();
configZookeeper1.putAll(config);
configZookeeper1.put("clientPort", clientport1 + "");
final Properties configZookeeper2 = new Properties();
configZookeeper2.putAll(config);
configZookeeper2.put("clientPort", clientport2 + "");
final Properties configZookeeper3 = new Properties();
configZookeeper3.putAll(config);
configZookeeper3.put("clientPort", clientport3 + "");
Files.createDirectories(baseDir1.resolve("data"));
Files.write(baseDir1.resolve("data").resolve("myid"), "1".getBytes("ASCII"));
Files.createDirectories(baseDir2.resolve("data"));
Files.write(baseDir2.resolve("data").resolve("myid"), "2".getBytes("ASCII"));
Files.createDirectories(baseDir3.resolve("data"));
Files.write(baseDir3.resolve("data").resolve("myid"), "3".getBytes("ASCII"));
try (ZooKeeperServerEmbedded zkServer1 = ZooKeeperServerEmbedded.builder().configuration(configZookeeper1).baseDir(baseDir1).exitHandler(ExitHandler.LOG_ONLY).build();
ZooKeeperServerEmbedded zkServer2 = ZooKeeperServerEmbedded.builder().configuration(configZookeeper2).baseDir(baseDir2).exitHandler(ExitHandler.LOG_ONLY).build();
ZooKeeperServerEmbedded zkServer3 = ZooKeeperServerEmbedded.builder().configuration(configZookeeper3).baseDir(baseDir3).exitHandler(ExitHandler.LOG_ONLY).build();) {
zkServer1.start();
zkServer2.start();
zkServer3.start();
assertTrue(ClientBase.waitForServerUp("localhost:" + clientport1, 60000));
assertTrue(ClientBase.waitForServerUp("localhost:" + clientport2, 60000));
assertTrue(ClientBase.waitForServerUp("localhost:" + clientport3, 60000));
for (int i = 0; i < 100; i++) {
ZookeeperServeInfo.ServerInfo status = ZookeeperServeInfo.getStatus("ReplicatedServer*");
System.out.println("status:" + status);
if (status.isLeader() && !status.isStandaloneMode() && status.getPeers().size() == 3) {
break;
}
Thread.sleep(100);
}
ZookeeperServeInfo.ServerInfo status = ZookeeperServeInfo.getStatus("ReplicatedServer*");
assertTrue(status.isLeader());
assertTrue(!status.isStandaloneMode());
assertEquals(3, status.getPeers().size());
}
}
}
|
923d896eea286b45505d4433f443d1bcd48fa42f | 244 | java | Java | taoq-boot-common/taoq-boot-starter-rbac/src/main/java/tech/taoq/rbac/mapper/RoleMenuMapper.java | iskeqi/keqi-spring-boot-starter-parent | 097a8549ddacc57773fb5d9ab816804f3023c5c7 | [
"Apache-2.0"
] | null | null | null | taoq-boot-common/taoq-boot-starter-rbac/src/main/java/tech/taoq/rbac/mapper/RoleMenuMapper.java | iskeqi/keqi-spring-boot-starter-parent | 097a8549ddacc57773fb5d9ab816804f3023c5c7 | [
"Apache-2.0"
] | null | null | null | taoq-boot-common/taoq-boot-starter-rbac/src/main/java/tech/taoq/rbac/mapper/RoleMenuMapper.java | iskeqi/keqi-spring-boot-starter-parent | 097a8549ddacc57773fb5d9ab816804f3023c5c7 | [
"Apache-2.0"
] | null | null | null | 20.333333 | 64 | 0.77459 | 1,000,367 | package tech.taoq.rbac.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import tech.taoq.rbac.domain.db.RoleMenuDO;
/**
* RoleMenuMapper
*
* @author keqi
*/
public interface RoleMenuMapper extends BaseMapper<RoleMenuDO> {
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.