text
stringlengths
7
1.01M
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.eql.session; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.tasks.TaskId; import org.elasticsearch.xpack.eql.action.EqlSearchTask; import java.time.ZoneId; public class EqlConfiguration extends org.elasticsearch.xpack.ql.session.Configuration { private final String[] indices; private final TimeValue requestTimeout; private final String clientId; private final boolean includeFrozenIndices; private final TaskId taskId; private final EqlSearchTask task; private final boolean isCaseSensitive; @Nullable private final QueryBuilder filter; public EqlConfiguration(String[] indices, ZoneId zi, String username, String clusterName, QueryBuilder filter, TimeValue requestTimeout, boolean includeFrozen, boolean isCaseSensitive, String clientId, TaskId taskId, EqlSearchTask task) { super(zi, username, clusterName); this.indices = indices; this.filter = filter; this.requestTimeout = requestTimeout; this.clientId = clientId; this.includeFrozenIndices = includeFrozen; this.isCaseSensitive = isCaseSensitive; this.taskId = taskId; this.task = task; } public String[] indices() { return indices; } public String indexAsWildcard() { return Strings.arrayToCommaDelimitedString(indices); } public TimeValue requestTimeout() { return requestTimeout; } public QueryBuilder filter() { return filter; } public String clientId() { return clientId; } public boolean includeFrozen() { return includeFrozenIndices; } public boolean isCaseSensitive() { return isCaseSensitive; } public boolean isCancelled() { return task.isCancelled(); } public TaskId getTaskId() { return taskId; } }
package seedu.docit.logic.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * Stores mapping of prefixes to their respective arguments. * Each key may be associated with multiple argument values. * Values for a given key are stored in a list, and the insertion ordering is maintained. * Keys are unique, but the list of argument values may contain duplicate argument values, i.e. the same argument value * can be inserted multiple times for the same prefix. */ public class ArgumentMultimap { /** Prefixes mapped to their respective arguments**/ private final Map<Prefix, List<String>> argMultimap = new HashMap<>(); /** * Associates the specified argument value with {@code prefix} key in this map. * If the map previously contained a mapping for the key, the new value is appended to the list of existing values. * * @param prefix Prefix key with which the specified argument value is to be associated * @param argValue Argument value to be associated with the specified prefix key */ public void put(Prefix prefix, String argValue) { List<String> argValues = getAllValues(prefix); argValues.add(argValue); argMultimap.put(prefix, argValues); } /** * Returns the last value of {@code prefix}. */ public Optional<String> getValue(Prefix prefix) { List<String> values = getAllValues(prefix); return values.isEmpty() ? Optional.empty() : Optional.of(values.get(values.size() - 1)); } /** * Returns all values of {@code prefix}. * If the prefix does not exist or has no values, this will return an empty list. * Modifying the returned list will not affect the underlying data structure of the ArgumentMultimap. */ public List<String> getAllValues(Prefix prefix) { if (!argMultimap.containsKey(prefix)) { return new ArrayList<>(); } return new ArrayList<>(argMultimap.get(prefix)); } /** * Returns the preamble (text before the first valid prefix). Trims any leading/trailing spaces. */ public String getPreamble() { return getValue(new Prefix("")).orElse(""); } }
package com.dexesttp.hkxpack.cli.components; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.xml.sax.SAXException; import com.dexesttp.hkxpack.data.HKXFile; import com.dexesttp.hkxpack.descriptor.HKXDescriptorFactory; import com.dexesttp.hkxpack.descriptor.HKXEnumResolver; import com.dexesttp.hkxpack.resources.DisplayProperties; import com.dexesttp.hkxpack.tagreader.TagXMLReader; import com.dexesttp.hkxpack.tagreader.exceptions.InvalidTagXMLException; import com.dexesttp.hkxpack.tagwriter.TagXMLWriter; /** * Testing interface, used to perform live tests with Eclipse. */ public final class HKXTest { private static final Logger LOGGER = Logger.getLogger(HKXTest.class.getName()); private HKXTest() { // NO OP } /** * Tests a HKX file {@code <filename>.hkx} by reading it and writing it back under {@code <filename>-new.hkx} * @param rootName the root directory * @param testName the file to test, without its extension */ public static void exec(final String rootName, final String testName) { String inputFileName = rootName + testName + ".hkx"; String outputFileName = rootName + testName + "-new.hkx"; DisplayProperties.displayDebugInfo = true; DisplayProperties.displayFileDebugInfo = true; DisplayProperties.displayReadTypesInfo = true; DisplayProperties.displayClassImportsInfo = true; DisplayProperties.displayEmbeddedData = true; try { // Read XML file File inFile = new File(inputFileName); HKXEnumResolver enumResolver = new HKXEnumResolver(); HKXDescriptorFactory descriptorFactory = new HKXDescriptorFactory(enumResolver); TagXMLReader reader = new TagXMLReader(inFile, descriptorFactory); HKXFile hkxFile = reader.read(); // Write XML file File outFile = new File(outputFileName); TagXMLWriter writer = new TagXMLWriter(outFile); writer.write(hkxFile); } catch (IOException | TransformerException | ParserConfigurationException | SAXException | InvalidTagXMLException e) { LOGGER.throwing(HKXTest.class.getName(), "exec", e); } } }
/** * */ package com.strandls.observation.util; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.strandls.authentication_utility.util.AuthUtil; import com.strandls.user.pojo.Role; import com.strandls.user.pojo.User; /** * @author Abhishek Rudra * */ public class TokenGenerator { public String generate(User user) { com.strandls.authentication_utility.model.User u1 = new com.strandls.authentication_utility.model.User(); u1.setAboutMe(user.getAboutMe()); u1.setAccountExpired(user.getAccountExpired()); u1.setAccountLocked(user.getAccountLocked()); u1.setDateCreated(user.getDateCreated()); u1.setEmail(user.getEmail()); u1.setEmailValidation(user.getEmailValidation()); u1.setEnabled(user.getEnabled()); u1.setHideEmial(user.getHideEmial()); u1.setIcon(user.getIcon()); u1.setId(user.getId()); u1.setIdentificationMail(user.getIdentificationMail()); u1.setInstitution(user.getInstitution()); u1.setLanguageId(user.getLanguageId()); u1.setLastLoginDate(user.getLastLoginDate()); u1.setLatitude(user.getLatitude()); u1.setLocation(user.getLocation()); u1.setLongitude(user.getLongitude()); u1.setMobileNumber(user.getMobileNumber()); u1.setMobileValidation(user.getMobileValidation()); u1.setName(user.getName()); u1.setOccupation(user.getOccupation()); u1.setPasswordExpired(user.getPasswordExpired()); u1.setProfilePic(user.getProfilePic()); Set<com.strandls.authentication_utility.model.Role> r1 = new HashSet<com.strandls.authentication_utility.model.Role>(); for (Role role : user.getRoles()) { com.strandls.authentication_utility.model.Role r = new com.strandls.authentication_utility.model.Role(); r.setAuthority(role.getAuthority()); r.setId(role.getId()); r.setVersion(role.getVersion()); r1.add(r); } u1.setRoles(r1); u1.setSendDigest(user.getSendDigest()); u1.setSendNotification(user.getSendNotification()); u1.setSendPushNotification(user.getSendPushNotification()); u1.setSexType(user.getSexType()); Set<com.strandls.authentication_utility.model.FirebaseTokens> fb = new HashSet<com.strandls.authentication_utility.model.FirebaseTokens>(); u1.setTokens(fb); u1.setUserName(user.getUserName()); u1.setVersion(user.getVersion()); Map<String, Object> token = AuthUtil.generateToken(u1, false); String accessToken = (String) token.get("access_token"); accessToken = "Bearer " + accessToken; return accessToken; } }
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.inception.recommendation.tasks; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import de.tudarmstadt.ukp.clarin.webanno.api.DocumentService; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument; import de.tudarmstadt.ukp.clarin.webanno.security.model.User; import de.tudarmstadt.ukp.inception.recommendation.api.RecommendationService; import de.tudarmstadt.ukp.inception.recommendation.api.model.Predictions; import de.tudarmstadt.ukp.inception.scheduling.Task; /** * This consumer predicts new annotations for a given annotation layer, if a classification tool for * this layer was selected previously. */ public class PredictionTask extends Task { private Logger log = LoggerFactory.getLogger(getClass()); private @Autowired RecommendationService recommendationService; private @Autowired DocumentService documentService; public PredictionTask(User aUser, Project aProject, String aTrigger) { super(aUser, aProject, aTrigger); } @Override public void run() { User user = getUser(); Project project = getProject(); List<SourceDocument> docs = documentService.listSourceDocuments(project); log.info("[{}]: Starting prediction...", user.getUsername()); long startTime = System.currentTimeMillis(); Predictions predictions = recommendationService.computePredictions(user, project, docs); log.debug("[{}]: Prediction complete ({} ms)", user.getUsername(), (System.currentTimeMillis() - startTime)); recommendationService.putIncomingPredictions(user, project, predictions); } }
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.health; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.indices.Stats; /** * {@link HealthIndicator} for Elasticsearch using a {@link JestClient}. * * @author Stephane Nicoll * @since 1.4.0 */ public class ElasticsearchJestHealthIndicator extends AbstractHealthIndicator { private final JestClient jestClient; public ElasticsearchJestHealthIndicator(JestClient jestClient) { this.jestClient = jestClient; } @Override protected void doHealthCheck(Health.Builder builder) throws Exception { JestResult aliases = this.jestClient.execute(new Stats.Builder().build()); JsonParser jsonParser = new JsonParser(); JsonElement root = jsonParser.parse(aliases.getJsonString()); JsonObject shards = root.getAsJsonObject().get("_shards").getAsJsonObject(); int failedShards = shards.get("failed").getAsInt(); if (failedShards != 0) { builder.outOfService(); } else { builder.up(); } } }
package com.bugzhu.thirdpay.paymodule; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.Toast; import com.alipay.sdk.app.PayTask; import com.bugzhu.thirdpay.R; import java.util.Map; /** * Created by Pashley on 2016/9/17. */ public class AlipayClientActivity extends Activity { private static final int RQF_PAY = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pay_module_dialog); Intent intent = getIntent(); if (intent == null) { Toast.makeText(this, getString(R.string.operation_error), Toast.LENGTH_SHORT).show(); finish(); return; } else { String orderParam = intent.getStringExtra("alipay"); doPay(orderParam); } } private void doPay(String orderParam) { final String payInfo = orderParam; // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);//沙箱测试 Runnable payRunnable = new Runnable() { @Override public void run() { // 构造PayTask 对象 PayTask alipay = new PayTask(AlipayClientActivity.this); Map<String, String> result = alipay.payV2(payInfo, true); Message msg = new Message(); msg.what = RQF_PAY; msg.obj = result.get("resultStatus"); mHandler.sendMessage(msg); } }; Thread payThread = new Thread(payRunnable); payThread.start(); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { String result = msg.obj.toString(); if (!isStrNull(result)) { setResult(PayCode.RESULT_CODE_ORDER); if (result.equals("9000")) {// 操作成功 setResult(PayCode.RESULT_CODE_PAYMENT_SUCCEED); } else if (result.equals("4000")) {// 系统异常 Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_system_exception), Toast.LENGTH_SHORT).show(); } else if (result.equals("4001")) {// 数据格式不正确 Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_system_exception), Toast.LENGTH_SHORT).show(); } else if (result.equals("4003")) {// 该用户绑定的支付宝账户被冻结或不允许支付 Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_account_exception), Toast.LENGTH_SHORT).show(); } else if (result.equals("4004")) {// 该用户已解除绑定 Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_has_unbound), Toast.LENGTH_SHORT).show(); } else if (result.equals("4005")) {// 绑定失败或没有绑定 Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_system_exception), Toast.LENGTH_SHORT).show(); } else if (result.equals("4006")) {// 订单支付失败 Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_order_error), Toast.LENGTH_SHORT).show(); } else if (result.equals("4010")) {// 重新绑定账户 Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_system_exception), Toast.LENGTH_SHORT).show(); } else if (result.equals("6000")) {// 支付服务正在进行升级操作 Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_system_exception), Toast.LENGTH_SHORT).show(); } else if (result.equals("6001")) {// 用户中途取消支付操作 setResult(PayCode.RESULT_CODE_PAYMENT_CANCEL); } else if (result.equals("7001")) {// 网页支付失败 setResult(PayCode.RESULT_CODE_PAYMENT_ERROR); } else if (result.equals("8000")) {// 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态) setResult(PayCode.RESULT_CODE_PAYMENT_CANCEL); } else { Toast.makeText(AlipayClientActivity.this, getString(R.string.pay_error), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(AlipayClientActivity.this, getString(R.string.alipay_system_exception), Toast.LENGTH_SHORT).show(); } finish(); } }; public boolean isStrNull(String str) { if (str == null || "".equals(str) || "null".equals(str) || "default".equals(str) || "undefined".equals(str)) { return true; } return false; } }
package org.fisco.bcos.web3j.crypto; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import java.security.SignatureException; import org.bouncycastle.math.ec.ECPoint; import org.junit.Test; public class SignTest { private static final byte[] TEST_MESSAGE = "A test message".getBytes(); // @Test // public void testSignMessage() { // Sign.SignatureData signatureData = Sign.signPrefixedMessage(TEST_MESSAGE, // SampleKeys.KEY_PAIR); // // Sign.SignatureData expected = new Sign.SignatureData( // (byte) 28, // Numeric.hexStringToByteArray( // "0x0464eee9e2fe1a10ffe48c78b80de1ed8dcf996f3f60955cb2e03cb21903d930"), // Numeric.hexStringToByteArray( // "0x06624da478b3f862582e85b31c6a21c6cae2eee2bd50f55c93c4faad9d9c8d7f") // ); // // assertThat(signatureData, is(expected)); // } // @Test // public void testSignedMessageToKey() throws SignatureException { // Sign.SignatureData signatureData = Sign.signPrefixedMessage(TEST_MESSAGE, // SampleKeys.KEY_PAIR); // BigInteger key = Sign.signedPrefixedMessageToKey(TEST_MESSAGE, signatureData); // assertThat(key, equalTo(SampleKeys.PUBLIC_KEY)); // } @Test public void testPublicKeyFromPrivateKey() { assertThat(Sign.publicKeyFromPrivate(SampleKeys.PRIVATE_KEY), equalTo(SampleKeys.PUBLIC_KEY)); } @Test(expected = RuntimeException.class) public void testInvalidSignature() throws SignatureException { Sign.signedMessageToKey( TEST_MESSAGE, new Sign.SignatureData((byte) 27, new byte[] {1}, new byte[] {0})); } @Test public void testPublicKeyFromPrivatePoint() { ECPoint point = Sign.publicPointFromPrivate(SampleKeys.PRIVATE_KEY); assertThat(Sign.publicFromPoint(point.getEncoded(false)), equalTo(SampleKeys.PUBLIC_KEY)); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/group_service.proto package com.google.monitoring.v3; /** * <pre> * The `CreateGroup` request. * </pre> * * Protobuf type {@code google.monitoring.v3.CreateGroupRequest} */ public final class CreateGroupRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.monitoring.v3.CreateGroupRequest) CreateGroupRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateGroupRequest.newBuilder() to construct. private CreateGroupRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateGroupRequest() { name_ = ""; validateOnly_ = false; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CreateGroupRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 18: { com.google.monitoring.v3.Group.Builder subBuilder = null; if (group_ != null) { subBuilder = group_.toBuilder(); } group_ = input.readMessage(com.google.monitoring.v3.Group.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(group_); group_ = subBuilder.buildPartial(); } break; } case 24: { validateOnly_ = input.readBool(); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.v3.GroupServiceProto.internal_static_google_monitoring_v3_CreateGroupRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.v3.GroupServiceProto.internal_static_google_monitoring_v3_CreateGroupRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.v3.CreateGroupRequest.class, com.google.monitoring.v3.CreateGroupRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 4; private volatile java.lang.Object name_; /** * <pre> * The project in which to create the group. The format is * `"projects/{project_id_or_number}"`. * </pre> * * <code>string name = 4;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <pre> * The project in which to create the group. The format is * `"projects/{project_id_or_number}"`. * </pre> * * <code>string name = 4;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int GROUP_FIELD_NUMBER = 2; private com.google.monitoring.v3.Group group_; /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public boolean hasGroup() { return group_ != null; } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public com.google.monitoring.v3.Group getGroup() { return group_ == null ? com.google.monitoring.v3.Group.getDefaultInstance() : group_; } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public com.google.monitoring.v3.GroupOrBuilder getGroupOrBuilder() { return getGroup(); } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; private boolean validateOnly_; /** * <pre> * If true, validate this request but do not create the group. * </pre> * * <code>bool validate_only = 3;</code> */ public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (group_ != null) { output.writeMessage(2, getGroup()); } if (validateOnly_ != false) { output.writeBool(3, validateOnly_); } if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, name_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (group_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getGroup()); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, validateOnly_); } if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, name_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.monitoring.v3.CreateGroupRequest)) { return super.equals(obj); } com.google.monitoring.v3.CreateGroupRequest other = (com.google.monitoring.v3.CreateGroupRequest) obj; boolean result = true; result = result && getName() .equals(other.getName()); result = result && (hasGroup() == other.hasGroup()); if (hasGroup()) { result = result && getGroup() .equals(other.getGroup()); } result = result && (getValidateOnly() == other.getValidateOnly()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (hasGroup()) { hash = (37 * hash) + GROUP_FIELD_NUMBER; hash = (53 * hash) + getGroup().hashCode(); } hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getValidateOnly()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.monitoring.v3.CreateGroupRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.monitoring.v3.CreateGroupRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.monitoring.v3.CreateGroupRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.monitoring.v3.CreateGroupRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.monitoring.v3.CreateGroupRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * The `CreateGroup` request. * </pre> * * Protobuf type {@code google.monitoring.v3.CreateGroupRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.monitoring.v3.CreateGroupRequest) com.google.monitoring.v3.CreateGroupRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.v3.GroupServiceProto.internal_static_google_monitoring_v3_CreateGroupRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.v3.GroupServiceProto.internal_static_google_monitoring_v3_CreateGroupRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.v3.CreateGroupRequest.class, com.google.monitoring.v3.CreateGroupRequest.Builder.class); } // Construct using com.google.monitoring.v3.CreateGroupRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; if (groupBuilder_ == null) { group_ = null; } else { group_ = null; groupBuilder_ = null; } validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.monitoring.v3.GroupServiceProto.internal_static_google_monitoring_v3_CreateGroupRequest_descriptor; } @java.lang.Override public com.google.monitoring.v3.CreateGroupRequest getDefaultInstanceForType() { return com.google.monitoring.v3.CreateGroupRequest.getDefaultInstance(); } @java.lang.Override public com.google.monitoring.v3.CreateGroupRequest build() { com.google.monitoring.v3.CreateGroupRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.monitoring.v3.CreateGroupRequest buildPartial() { com.google.monitoring.v3.CreateGroupRequest result = new com.google.monitoring.v3.CreateGroupRequest(this); result.name_ = name_; if (groupBuilder_ == null) { result.group_ = group_; } else { result.group_ = groupBuilder_.build(); } result.validateOnly_ = validateOnly_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.monitoring.v3.CreateGroupRequest) { return mergeFrom((com.google.monitoring.v3.CreateGroupRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.monitoring.v3.CreateGroupRequest other) { if (other == com.google.monitoring.v3.CreateGroupRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (other.hasGroup()) { mergeGroup(other.getGroup()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.monitoring.v3.CreateGroupRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.monitoring.v3.CreateGroupRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object name_ = ""; /** * <pre> * The project in which to create the group. The format is * `"projects/{project_id_or_number}"`. * </pre> * * <code>string name = 4;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The project in which to create the group. The format is * `"projects/{project_id_or_number}"`. * </pre> * * <code>string name = 4;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The project in which to create the group. The format is * `"projects/{project_id_or_number}"`. * </pre> * * <code>string name = 4;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <pre> * The project in which to create the group. The format is * `"projects/{project_id_or_number}"`. * </pre> * * <code>string name = 4;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <pre> * The project in which to create the group. The format is * `"projects/{project_id_or_number}"`. * </pre> * * <code>string name = 4;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private com.google.monitoring.v3.Group group_ = null; private com.google.protobuf.SingleFieldBuilderV3< com.google.monitoring.v3.Group, com.google.monitoring.v3.Group.Builder, com.google.monitoring.v3.GroupOrBuilder> groupBuilder_; /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public boolean hasGroup() { return groupBuilder_ != null || group_ != null; } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public com.google.monitoring.v3.Group getGroup() { if (groupBuilder_ == null) { return group_ == null ? com.google.monitoring.v3.Group.getDefaultInstance() : group_; } else { return groupBuilder_.getMessage(); } } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public Builder setGroup(com.google.monitoring.v3.Group value) { if (groupBuilder_ == null) { if (value == null) { throw new NullPointerException(); } group_ = value; onChanged(); } else { groupBuilder_.setMessage(value); } return this; } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public Builder setGroup( com.google.monitoring.v3.Group.Builder builderForValue) { if (groupBuilder_ == null) { group_ = builderForValue.build(); onChanged(); } else { groupBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public Builder mergeGroup(com.google.monitoring.v3.Group value) { if (groupBuilder_ == null) { if (group_ != null) { group_ = com.google.monitoring.v3.Group.newBuilder(group_).mergeFrom(value).buildPartial(); } else { group_ = value; } onChanged(); } else { groupBuilder_.mergeFrom(value); } return this; } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public Builder clearGroup() { if (groupBuilder_ == null) { group_ = null; onChanged(); } else { group_ = null; groupBuilder_ = null; } return this; } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public com.google.monitoring.v3.Group.Builder getGroupBuilder() { onChanged(); return getGroupFieldBuilder().getBuilder(); } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ public com.google.monitoring.v3.GroupOrBuilder getGroupOrBuilder() { if (groupBuilder_ != null) { return groupBuilder_.getMessageOrBuilder(); } else { return group_ == null ? com.google.monitoring.v3.Group.getDefaultInstance() : group_; } } /** * <pre> * A group definition. It is an error to define the `name` field because * the system assigns the name. * </pre> * * <code>.google.monitoring.v3.Group group = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.monitoring.v3.Group, com.google.monitoring.v3.Group.Builder, com.google.monitoring.v3.GroupOrBuilder> getGroupFieldBuilder() { if (groupBuilder_ == null) { groupBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.monitoring.v3.Group, com.google.monitoring.v3.Group.Builder, com.google.monitoring.v3.GroupOrBuilder>( getGroup(), getParentForChildren(), isClean()); group_ = null; } return groupBuilder_; } private boolean validateOnly_ ; /** * <pre> * If true, validate this request but do not create the group. * </pre> * * <code>bool validate_only = 3;</code> */ public boolean getValidateOnly() { return validateOnly_; } /** * <pre> * If true, validate this request but do not create the group. * </pre> * * <code>bool validate_only = 3;</code> */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; onChanged(); return this; } /** * <pre> * If true, validate this request but do not create the group. * </pre> * * <code>bool validate_only = 3;</code> */ public Builder clearValidateOnly() { validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.monitoring.v3.CreateGroupRequest) } // @@protoc_insertion_point(class_scope:google.monitoring.v3.CreateGroupRequest) private static final com.google.monitoring.v3.CreateGroupRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.monitoring.v3.CreateGroupRequest(); } public static com.google.monitoring.v3.CreateGroupRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateGroupRequest> PARSER = new com.google.protobuf.AbstractParser<CreateGroupRequest>() { @java.lang.Override public CreateGroupRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CreateGroupRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<CreateGroupRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateGroupRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.monitoring.v3.CreateGroupRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package org.hl7.fhir.r4.model.codesystems; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Wed, Jan 30, 2019 16:19-0500 for FHIR v4.0.0 import org.hl7.fhir.exceptions.FHIRException; public enum V3ReligiousAffiliation { /** * Adventist */ _1001, /** * African Religions */ _1002, /** * Afro-Caribbean Religions */ _1003, /** * Agnosticism */ _1004, /** * Anglican */ _1005, /** * Animism */ _1006, /** * Atheism */ _1007, /** * Babi & Baha'I faiths */ _1008, /** * Baptist */ _1009, /** * Bon */ _1010, /** * Cao Dai */ _1011, /** * Celticism */ _1012, /** * Christian (non-Catholic, non-specific) */ _1013, /** * Confucianism */ _1014, /** * Cyberculture Religions */ _1015, /** * Divination */ _1016, /** * Fourth Way */ _1017, /** * Free Daism */ _1018, /** * Gnosis */ _1019, /** * Hinduism */ _1020, /** * Humanism */ _1021, /** * Independent */ _1022, /** * Islam */ _1023, /** * Jainism */ _1024, /** * Jehovah's Witnesses */ _1025, /** * Judaism */ _1026, /** * Latter Day Saints */ _1027, /** * Lutheran */ _1028, /** * Mahayana */ _1029, /** * Meditation */ _1030, /** * Messianic Judaism */ _1031, /** * Mitraism */ _1032, /** * New Age */ _1033, /** * non-Roman Catholic */ _1034, /** * Occult */ _1035, /** * Orthodox */ _1036, /** * Paganism */ _1037, /** * Pentecostal */ _1038, /** * Process, The */ _1039, /** * Reformed/Presbyterian */ _1040, /** * Roman Catholic Church */ _1041, /** * Satanism */ _1042, /** * Scientology */ _1043, /** * Shamanism */ _1044, /** * Shiite (Islam) */ _1045, /** * Shinto */ _1046, /** * Sikism */ _1047, /** * Spiritualism */ _1048, /** * Sunni (Islam) */ _1049, /** * Taoism */ _1050, /** * Theravada */ _1051, /** * Unitarian-Universalism */ _1052, /** * Universal Life Church */ _1053, /** * Vajrayana (Tibetan) */ _1054, /** * Veda */ _1055, /** * Voodoo */ _1056, /** * Wicca */ _1057, /** * Yaohushua */ _1058, /** * Zen Buddhism */ _1059, /** * Zoroastrianism */ _1060, /** * Assembly of God */ _1061, /** * Brethren */ _1062, /** * Christian Scientist */ _1063, /** * Church of Christ */ _1064, /** * Church of God */ _1065, /** * Congregational */ _1066, /** * Disciples of Christ */ _1067, /** * Eastern Orthodox */ _1068, /** * Episcopalian */ _1069, /** * Evangelical Covenant */ _1070, /** * Friends */ _1071, /** * Full Gospel */ _1072, /** * Methodist */ _1073, /** * Native American */ _1074, /** * Nazarene */ _1075, /** * Presbyterian */ _1076, /** * Protestant */ _1077, /** * Protestant, No Denomination */ _1078, /** * Reformed */ _1079, /** * Salvation Army */ _1080, /** * Unitarian Universalist */ _1081, /** * United Church of Christ */ _1082, /** * added to help the parsers */ NULL; public static V3ReligiousAffiliation fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("1001".equals(codeString)) return _1001; if ("1002".equals(codeString)) return _1002; if ("1003".equals(codeString)) return _1003; if ("1004".equals(codeString)) return _1004; if ("1005".equals(codeString)) return _1005; if ("1006".equals(codeString)) return _1006; if ("1007".equals(codeString)) return _1007; if ("1008".equals(codeString)) return _1008; if ("1009".equals(codeString)) return _1009; if ("1010".equals(codeString)) return _1010; if ("1011".equals(codeString)) return _1011; if ("1012".equals(codeString)) return _1012; if ("1013".equals(codeString)) return _1013; if ("1014".equals(codeString)) return _1014; if ("1015".equals(codeString)) return _1015; if ("1016".equals(codeString)) return _1016; if ("1017".equals(codeString)) return _1017; if ("1018".equals(codeString)) return _1018; if ("1019".equals(codeString)) return _1019; if ("1020".equals(codeString)) return _1020; if ("1021".equals(codeString)) return _1021; if ("1022".equals(codeString)) return _1022; if ("1023".equals(codeString)) return _1023; if ("1024".equals(codeString)) return _1024; if ("1025".equals(codeString)) return _1025; if ("1026".equals(codeString)) return _1026; if ("1027".equals(codeString)) return _1027; if ("1028".equals(codeString)) return _1028; if ("1029".equals(codeString)) return _1029; if ("1030".equals(codeString)) return _1030; if ("1031".equals(codeString)) return _1031; if ("1032".equals(codeString)) return _1032; if ("1033".equals(codeString)) return _1033; if ("1034".equals(codeString)) return _1034; if ("1035".equals(codeString)) return _1035; if ("1036".equals(codeString)) return _1036; if ("1037".equals(codeString)) return _1037; if ("1038".equals(codeString)) return _1038; if ("1039".equals(codeString)) return _1039; if ("1040".equals(codeString)) return _1040; if ("1041".equals(codeString)) return _1041; if ("1042".equals(codeString)) return _1042; if ("1043".equals(codeString)) return _1043; if ("1044".equals(codeString)) return _1044; if ("1045".equals(codeString)) return _1045; if ("1046".equals(codeString)) return _1046; if ("1047".equals(codeString)) return _1047; if ("1048".equals(codeString)) return _1048; if ("1049".equals(codeString)) return _1049; if ("1050".equals(codeString)) return _1050; if ("1051".equals(codeString)) return _1051; if ("1052".equals(codeString)) return _1052; if ("1053".equals(codeString)) return _1053; if ("1054".equals(codeString)) return _1054; if ("1055".equals(codeString)) return _1055; if ("1056".equals(codeString)) return _1056; if ("1057".equals(codeString)) return _1057; if ("1058".equals(codeString)) return _1058; if ("1059".equals(codeString)) return _1059; if ("1060".equals(codeString)) return _1060; if ("1061".equals(codeString)) return _1061; if ("1062".equals(codeString)) return _1062; if ("1063".equals(codeString)) return _1063; if ("1064".equals(codeString)) return _1064; if ("1065".equals(codeString)) return _1065; if ("1066".equals(codeString)) return _1066; if ("1067".equals(codeString)) return _1067; if ("1068".equals(codeString)) return _1068; if ("1069".equals(codeString)) return _1069; if ("1070".equals(codeString)) return _1070; if ("1071".equals(codeString)) return _1071; if ("1072".equals(codeString)) return _1072; if ("1073".equals(codeString)) return _1073; if ("1074".equals(codeString)) return _1074; if ("1075".equals(codeString)) return _1075; if ("1076".equals(codeString)) return _1076; if ("1077".equals(codeString)) return _1077; if ("1078".equals(codeString)) return _1078; if ("1079".equals(codeString)) return _1079; if ("1080".equals(codeString)) return _1080; if ("1081".equals(codeString)) return _1081; if ("1082".equals(codeString)) return _1082; throw new FHIRException("Unknown V3ReligiousAffiliation code '"+codeString+"'"); } public String toCode() { switch (this) { case _1001: return "1001"; case _1002: return "1002"; case _1003: return "1003"; case _1004: return "1004"; case _1005: return "1005"; case _1006: return "1006"; case _1007: return "1007"; case _1008: return "1008"; case _1009: return "1009"; case _1010: return "1010"; case _1011: return "1011"; case _1012: return "1012"; case _1013: return "1013"; case _1014: return "1014"; case _1015: return "1015"; case _1016: return "1016"; case _1017: return "1017"; case _1018: return "1018"; case _1019: return "1019"; case _1020: return "1020"; case _1021: return "1021"; case _1022: return "1022"; case _1023: return "1023"; case _1024: return "1024"; case _1025: return "1025"; case _1026: return "1026"; case _1027: return "1027"; case _1028: return "1028"; case _1029: return "1029"; case _1030: return "1030"; case _1031: return "1031"; case _1032: return "1032"; case _1033: return "1033"; case _1034: return "1034"; case _1035: return "1035"; case _1036: return "1036"; case _1037: return "1037"; case _1038: return "1038"; case _1039: return "1039"; case _1040: return "1040"; case _1041: return "1041"; case _1042: return "1042"; case _1043: return "1043"; case _1044: return "1044"; case _1045: return "1045"; case _1046: return "1046"; case _1047: return "1047"; case _1048: return "1048"; case _1049: return "1049"; case _1050: return "1050"; case _1051: return "1051"; case _1052: return "1052"; case _1053: return "1053"; case _1054: return "1054"; case _1055: return "1055"; case _1056: return "1056"; case _1057: return "1057"; case _1058: return "1058"; case _1059: return "1059"; case _1060: return "1060"; case _1061: return "1061"; case _1062: return "1062"; case _1063: return "1063"; case _1064: return "1064"; case _1065: return "1065"; case _1066: return "1066"; case _1067: return "1067"; case _1068: return "1068"; case _1069: return "1069"; case _1070: return "1070"; case _1071: return "1071"; case _1072: return "1072"; case _1073: return "1073"; case _1074: return "1074"; case _1075: return "1075"; case _1076: return "1076"; case _1077: return "1077"; case _1078: return "1078"; case _1079: return "1079"; case _1080: return "1080"; case _1081: return "1081"; case _1082: return "1082"; default: return "?"; } } public String getSystem() { return "http://terminology.hl7.org/CodeSystem/v3-ReligiousAffiliation"; } public String getDefinition() { switch (this) { case _1001: return "Adventist"; case _1002: return "African Religions"; case _1003: return "Afro-Caribbean Religions"; case _1004: return "Agnosticism"; case _1005: return "Anglican"; case _1006: return "Animism"; case _1007: return "Atheism"; case _1008: return "Babi & Baha'I faiths"; case _1009: return "Baptist"; case _1010: return "Bon"; case _1011: return "Cao Dai"; case _1012: return "Celticism"; case _1013: return "Christian (non-Catholic, non-specific)"; case _1014: return "Confucianism"; case _1015: return "Cyberculture Religions"; case _1016: return "Divination"; case _1017: return "Fourth Way"; case _1018: return "Free Daism"; case _1019: return "Gnosis"; case _1020: return "Hinduism"; case _1021: return "Humanism"; case _1022: return "Independent"; case _1023: return "Islam"; case _1024: return "Jainism"; case _1025: return "Jehovah's Witnesses"; case _1026: return "Judaism"; case _1027: return "Latter Day Saints"; case _1028: return "Lutheran"; case _1029: return "Mahayana"; case _1030: return "Meditation"; case _1031: return "Messianic Judaism"; case _1032: return "Mitraism"; case _1033: return "New Age"; case _1034: return "non-Roman Catholic"; case _1035: return "Occult"; case _1036: return "Orthodox"; case _1037: return "Paganism"; case _1038: return "Pentecostal"; case _1039: return "Process, The"; case _1040: return "Reformed/Presbyterian"; case _1041: return "Roman Catholic Church"; case _1042: return "Satanism"; case _1043: return "Scientology"; case _1044: return "Shamanism"; case _1045: return "Shiite (Islam)"; case _1046: return "Shinto"; case _1047: return "Sikism"; case _1048: return "Spiritualism"; case _1049: return "Sunni (Islam)"; case _1050: return "Taoism"; case _1051: return "Theravada"; case _1052: return "Unitarian-Universalism"; case _1053: return "Universal Life Church"; case _1054: return "Vajrayana (Tibetan)"; case _1055: return "Veda"; case _1056: return "Voodoo"; case _1057: return "Wicca"; case _1058: return "Yaohushua"; case _1059: return "Zen Buddhism"; case _1060: return "Zoroastrianism"; case _1061: return "Assembly of God"; case _1062: return "Brethren"; case _1063: return "Christian Scientist"; case _1064: return "Church of Christ"; case _1065: return "Church of God"; case _1066: return "Congregational"; case _1067: return "Disciples of Christ"; case _1068: return "Eastern Orthodox"; case _1069: return "Episcopalian"; case _1070: return "Evangelical Covenant"; case _1071: return "Friends"; case _1072: return "Full Gospel"; case _1073: return "Methodist"; case _1074: return "Native American"; case _1075: return "Nazarene"; case _1076: return "Presbyterian"; case _1077: return "Protestant"; case _1078: return "Protestant, No Denomination"; case _1079: return "Reformed"; case _1080: return "Salvation Army"; case _1081: return "Unitarian Universalist"; case _1082: return "United Church of Christ"; default: return "?"; } } public String getDisplay() { switch (this) { case _1001: return "Adventist"; case _1002: return "African Religions"; case _1003: return "Afro-Caribbean Religions"; case _1004: return "Agnosticism"; case _1005: return "Anglican"; case _1006: return "Animism"; case _1007: return "Atheism"; case _1008: return "Babi & Baha'I faiths"; case _1009: return "Baptist"; case _1010: return "Bon"; case _1011: return "Cao Dai"; case _1012: return "Celticism"; case _1013: return "Christian (non-Catholic, non-specific)"; case _1014: return "Confucianism"; case _1015: return "Cyberculture Religions"; case _1016: return "Divination"; case _1017: return "Fourth Way"; case _1018: return "Free Daism"; case _1019: return "Gnosis"; case _1020: return "Hinduism"; case _1021: return "Humanism"; case _1022: return "Independent"; case _1023: return "Islam"; case _1024: return "Jainism"; case _1025: return "Jehovah's Witnesses"; case _1026: return "Judaism"; case _1027: return "Latter Day Saints"; case _1028: return "Lutheran"; case _1029: return "Mahayana"; case _1030: return "Meditation"; case _1031: return "Messianic Judaism"; case _1032: return "Mitraism"; case _1033: return "New Age"; case _1034: return "non-Roman Catholic"; case _1035: return "Occult"; case _1036: return "Orthodox"; case _1037: return "Paganism"; case _1038: return "Pentecostal"; case _1039: return "Process, The"; case _1040: return "Reformed/Presbyterian"; case _1041: return "Roman Catholic Church"; case _1042: return "Satanism"; case _1043: return "Scientology"; case _1044: return "Shamanism"; case _1045: return "Shiite (Islam)"; case _1046: return "Shinto"; case _1047: return "Sikism"; case _1048: return "Spiritualism"; case _1049: return "Sunni (Islam)"; case _1050: return "Taoism"; case _1051: return "Theravada"; case _1052: return "Unitarian-Universalism"; case _1053: return "Universal Life Church"; case _1054: return "Vajrayana (Tibetan)"; case _1055: return "Veda"; case _1056: return "Voodoo"; case _1057: return "Wicca"; case _1058: return "Yaohushua"; case _1059: return "Zen Buddhism"; case _1060: return "Zoroastrianism"; case _1061: return "Assembly of God"; case _1062: return "Brethren"; case _1063: return "Christian Scientist"; case _1064: return "Church of Christ"; case _1065: return "Church of God"; case _1066: return "Congregational"; case _1067: return "Disciples of Christ"; case _1068: return "Eastern Orthodox"; case _1069: return "Episcopalian"; case _1070: return "Evangelical Covenant"; case _1071: return "Friends"; case _1072: return "Full Gospel"; case _1073: return "Methodist"; case _1074: return "Native American"; case _1075: return "Nazarene"; case _1076: return "Presbyterian"; case _1077: return "Protestant"; case _1078: return "Protestant, No Denomination"; case _1079: return "Reformed"; case _1080: return "Salvation Army"; case _1081: return "Unitarian Universalist"; case _1082: return "United Church of Christ"; default: return "?"; } } }
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.gateway.filter; import reactor.core.publisher.Mono; import org.springframework.core.Ordered; import org.springframework.web.server.ServerWebExchange; /** * @author Spencer Gibb */ public class OrderedGatewayFilter implements GatewayFilter, Ordered { // 委托模式 private final GatewayFilter delegate; private final int order; public OrderedGatewayFilter(GatewayFilter delegate, int order) { this.delegate = delegate; this.order = order; } public GatewayFilter getDelegate() { return delegate; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { return this.delegate.filter(exchange, chain); } @Override public int getOrder() { return this.order; } @Override public String toString() { final StringBuilder sb = new StringBuilder("OrderedGatewayFilter{"); sb.append("delegate=").append(delegate); sb.append(", order=").append(order); sb.append('}'); return sb.toString(); } }
package io.github.zeroone3010.geogpxparser; import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static java.util.function.Function.identity; public enum CacheSize { Micro("Micro"), Small("Small"), Regular("Regular"), Large("Large"), Virtual("Virtual"), Other("Other"), Not_chosen("Not chosen"); private final String gpxDescription; private static final Map<String, CacheSize> gpxToSize; static { gpxToSize = Arrays.asList(CacheSize.values()).stream() .collect(Collectors.toMap(CacheSize::getGpxDescription, identity())); } private CacheSize(String gpxDescriptionParam) { this.gpxDescription = gpxDescriptionParam; } public String getGpxDescription() { return this.gpxDescription; } public static CacheSize getByGpxDescription(String description) { return Optional.ofNullable(gpxToSize.get(description)).orElse(Not_chosen); } };
package com.vitco.app.core.modes; import com.vitco.app.core.container.DrawContainer; /** * Manages the mouse events for voxel interaction depending on the currently selected tool. */ public class VoxelAdapter extends AbstractAdapter { // constructor public VoxelAdapter(DrawContainer container) { super(container); } }
package org.anddev.andengine.entity.particle.modifier; import static org.anddev.andengine.util.MathUtils.RANDOM; import org.anddev.andengine.entity.particle.Particle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:21:10 - 14.03.2010 */ public class ExpireModifier implements IParticleModifier { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mMinLifeTime; private float mMaxLifeTime; // =========================================================== // Constructors // =========================================================== public ExpireModifier(final float pLifeTime) { this(pLifeTime, pLifeTime); } public ExpireModifier(final float pMinLifeTime, final float pMaxLifeTime) { this.mMinLifeTime = pMinLifeTime; this.mMaxLifeTime = pMaxLifeTime; } // =========================================================== // Getter & Setter // =========================================================== public float getMinLifeTime() { return this.mMinLifeTime; } public float getMaxLifeTime() { return this.mMaxLifeTime; } public void setLifeTime(final float pLifeTime) { this.mMinLifeTime = pLifeTime; this.mMaxLifeTime = pLifeTime; } public void setLifeTime(final float pMinLifeTime, final float pMaxLifeTime) { this.mMinLifeTime = pMinLifeTime; this.mMaxLifeTime = pMaxLifeTime; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onInitializeParticle(final Particle pParticle) { pParticle.setDeathTime((RANDOM.nextFloat() * (this.mMaxLifeTime - this.mMinLifeTime) + this.mMinLifeTime)); } @Override public void onUpdateParticle(final Particle pParticle) { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE643_Xpath_Injection__getCookies_Servlet_71b.java Label Definition File: CWE643_Xpath_Injection.label.xml Template File: sources-sinks-71b.tmpl.java */ /* * @description * CWE: 643 Xpath Injection * BadSource: getCookies_Servlet Read data from the first cookie using getCookies() * GoodSource: A hardcoded string * Sinks: * GoodSink: validate input through StringEscapeUtils * BadSink : user input is used without validate * Flow Variant: 71 Data flow: data passed as an Object reference argument from one method to another in different classes in the same package * * */ import javax.servlet.http.*; import javax.xml.xpath.*; import org.xml.sax.InputSource; import org.apache.commons.lang.StringEscapeUtils; public class CWE643_Xpath_Injection__getCookies_Servlet_71b { public void badSink(Object dataObject , HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = (String)dataObject; String xmlFile = null; if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ xmlFile = "\\src\\testcases\\CWE643_Xpath Injection\\CWE643_Xpath_Injection__Helper.xml"; } else { /* running on non-Windows */ xmlFile = "./src/testcases/CWE643_Xpath Injection/CWE643_Xpath_Injection__Helper.xml"; } if (data != null) { /* assume username||password as source */ String [] tokens = data.split("||"); if (tokens.length < 2) { return; } String username = tokens[0]; String password = tokens[1]; /* build xpath */ XPath xPath = XPathFactory.newInstance().newXPath(); InputSource inputXml = new InputSource(xmlFile); /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize * The user input should be canonicalized before validation. */ /* POTENTIAL FLAW: user input is used without validate */ String query = "//users/user[name/text()='" + username + "' and pass/text()='" + password + "']" + "/secret/text()"; String secret = (String)xPath.evaluate(query, inputXml, XPathConstants.STRING); } } /* goodG2B() - use goodsource and badsink */ public void goodG2BSink(Object dataObject , HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = (String)dataObject; String xmlFile = null; if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ xmlFile = "\\src\\testcases\\CWE643_Xpath Injection\\CWE643_Xpath_Injection__Helper.xml"; } else { /* running on non-Windows */ xmlFile = "./src/testcases/CWE643_Xpath Injection/CWE643_Xpath_Injection__Helper.xml"; } if (data != null) { /* assume username||password as source */ String [] tokens = data.split("||"); if (tokens.length < 2) { return; } String username = tokens[0]; String password = tokens[1]; /* build xpath */ XPath xPath = XPathFactory.newInstance().newXPath(); InputSource inputXml = new InputSource(xmlFile); /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize * The user input should be canonicalized before validation. */ /* POTENTIAL FLAW: user input is used without validate */ String query = "//users/user[name/text()='" + username + "' and pass/text()='" + password + "']" + "/secret/text()"; String secret = (String)xPath.evaluate(query, inputXml, XPathConstants.STRING); } } /* goodB2G() - use badsource and goodsink */ public void goodB2GSink(Object dataObject , HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = (String)dataObject; String xmlFile = null; if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ xmlFile = "\\src\\testcases\\CWE643_Xpath Injection\\CWE643_Xpath_Injection__Helper.xml"; } else { /* running on non-Windows */ xmlFile = "./src/testcases/CWE643_Xpath Injection/CWE643_Xpath_Injection__Helper.xml"; } if (data != null) { /* assume username||password as source */ String [] tokens = data.split("||"); if( tokens.length < 2 ) { return; } /* FIX: validate input using StringEscapeUtils */ String username = StringEscapeUtils.escapeXml(tokens[0]); String password = StringEscapeUtils.escapeXml(tokens[1]); /* build xpath */ XPath xPath = XPathFactory.newInstance().newXPath(); InputSource inputXml = new InputSource(xmlFile); String query = "//users/user[name/text()='" + username + "' and pass/text()='" + password + "']" + "/secret/text()"; String secret = (String)xPath.evaluate(query, inputXml, XPathConstants.STRING); } } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class dragon here. * * @author (your name) * @version (a version number or a date) */ public class dragon extends Actor { private GreenfootImage d1 = new GreenfootImage("dragon1.png"); private GreenfootImage d2 = new GreenfootImage("dragon2.png"); private GreenfootImage d3 = new GreenfootImage("dragon3.png"); private int frame = 1; private int animationCounter = 0; private int timer = 0; /** * Act - do whatever the dragon wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(-4); if(animationCounter % 8 == 0) animateDragon(); animationCounter ++; if (isTouching(Player1.class)) getWorld().showText("GAME OVER!", 300,200); if (isTouching(dragon.class)) removeTouching(dragon.class); if (isTouching(Player1.class)) removeTouching(Player1.class); if (isTouching(Player1.class)) Greenfoot.stop(); if (isAtEdge()) getWorld().removeObject(this); } public void animateDragon() { if(frame == 1) { setImage(d1); } else if(frame == 2) { setImage(d2); } else if(frame == 3) { setImage(d3); frame = 1; return; } frame ++; } }
package com.bumptech.glide.request; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.bumptech.glide.request.target.SizeReadyCallback; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, sdk = 18) public class RequestFutureTargetTest { private int width; private int height; private RequestFutureTarget<Object> future; private Request request; private Handler handler; private RequestFutureTarget.Waiter waiter; @Before public void setUp() { width = 100; height = 100; handler = mock(Handler.class); waiter = mock(RequestFutureTarget.Waiter.class); future = new RequestFutureTarget<>(handler, width, height, false, waiter); request = mock(Request.class); future.setRequest(request); } @Test public void testCallsSizeReadyCallbackOnGetSize() { SizeReadyCallback cb = mock(SizeReadyCallback.class); future.getSize(cb); verify(cb).onSizeReady(eq(width), eq(height)); } @Test public void testReturnsFalseForDoneBeforeDone() { assertFalse(future.isDone()); } @Test public void testReturnsTrueFromIsDoneIfDone() { future.onResourceReady(new Object(), null); assertTrue(future.isDone()); } @Test public void testReturnsFalseForIsCancelledBeforeCancelled() { assertFalse(future.isCancelled()); } @Test public void testReturnsTrueFromCancelIfNotYetDone() { assertTrue(future.cancel(false)); } @Test public void testClearsRequestOnMainThreadIfNotYetDoneOnCancel() { future.cancel(true); verify(handler).post(eq(future)); } @Test public void testClearsOnMainThreadWhenClearCalled() { future.cancel(false); verify(handler).post(eq(future)); } @Test public void testDoesNotRepeatedlyClearRequestOnMainThreadIfCancelledRepeatedly() { future.cancel(true); future.cancel(true); verify(handler, times(1)).post(any(Runnable.class)); } @Test public void testClearsRequestOnRun() { future.run(); verify(request).clear(); } @Test public void testDoesNotClearRequestIfCancelledAfterDone() { future.onResourceReady(new Object(), null); future.cancel(true); verify(request, never()).clear(); } @Test public void testReturnsTrueFromDoneIfCancelled() { future.cancel(true); assertTrue(future.isDone()); } @Test public void testReturnsFalseFromIsCancelledIfCancelledAfterDone() { future.onResourceReady(new Object(), null); future.cancel(true); assertFalse(future.isCancelled()); } @Test public void testReturnsTrueFromCancelIfCancelled() { future.cancel(true); assertTrue(future.isCancelled()); } @Test public void testReturnsFalseFromCancelIfDone() { future.onResourceReady(new Object(), null); assertFalse(future.cancel(true)); } @Test public void testReturnsResourceOnGetIfAlreadyDone() throws ExecutionException, InterruptedException { Object expected = new Object(); future.onResourceReady(expected, null); assertEquals(expected, future.get()); } @Test public void testReturnsResourceOnGetWithTimeoutIfAlreadyDone() throws InterruptedException, ExecutionException, TimeoutException { Object expected = new Object(); future.onResourceReady(expected, null); assertEquals(expected, future.get(100, TimeUnit.MILLISECONDS)); } @Test(expected = CancellationException.class) public void testThrowsCancellationExceptionIfCancelledBeforeGet() throws ExecutionException, InterruptedException { future.cancel(true); future.get(); } @Test(expected = CancellationException.class) public void testThrowsCancellationExceptionIfCancelledBeforeGetWithTimeout() throws InterruptedException, ExecutionException, TimeoutException { future.cancel(true); future.get(100, TimeUnit.MILLISECONDS); } @Test(expected = ExecutionException.class) public void testThrowsExecutionExceptionOnGetIfExceptionBeforeGet() throws ExecutionException, InterruptedException { future.onLoadFailed(null); future.get(); } @Test(expected = ExecutionException.class) public void testThrowsExecutionExceptionOnGetIfExceptionWithNullValueBeforeGet() throws ExecutionException, InterruptedException, TimeoutException { future.onLoadFailed(null); future.get(100, TimeUnit.MILLISECONDS); } @Test(expected = ExecutionException.class) public void testThrowsExecutionExceptionOnGetIfExceptionBeforeGetWithTimeout() throws ExecutionException, InterruptedException, TimeoutException { future.onLoadFailed(null); future.get(100, TimeUnit.MILLISECONDS); } @Test(expected = TimeoutException.class) public void testThrowsTimeoutExceptionOnGetIfFailedToReceiveResourceInTime() throws InterruptedException, ExecutionException, TimeoutException { future.get(1, TimeUnit.MILLISECONDS); } @Test(expected = IllegalArgumentException.class) public void testThrowsExceptionIfGetCalledOnMainThread() throws ExecutionException, InterruptedException { future = new RequestFutureTarget<>(handler, width, height, true, waiter); future.get(); } @Test public void testGetSucceedsOnMainThreadIfDone() throws ExecutionException, InterruptedException { future = new RequestFutureTarget<>(handler, width, height, true, waiter); future.onResourceReady(new Object(), null); future.get(); } @Test(expected = InterruptedException.class) public void testThrowsInterruptedExceptionIfThreadInterruptedWhenDoneWaiting() throws InterruptedException, ExecutionException { doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { Thread.currentThread().interrupt(); return null; } }).when(waiter).waitForTimeout(eq(future), anyLong()); future.get(); } @Test(expected = ExecutionException.class) public void testThrowsExecutionExceptionIfLoadFailsWhileWaiting() throws ExecutionException, InterruptedException { doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { future.onLoadFailed(null); return null; } }).when(waiter).waitForTimeout(eq(future), anyLong()); future.get(); } @Test(expected = CancellationException.class) public void testThrowsCancellationExceptionIfCancelledWhileWaiting() throws ExecutionException, InterruptedException { doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { future.cancel(false); return null; } }).when(waiter).waitForTimeout(eq(future), anyLong()); future.get(); } @Test(expected = TimeoutException.class) public void testThrowsTimeoutExceptionIfFinishesWaitingWithTimeoutAndDoesNotReceiveResult() throws ExecutionException, InterruptedException, TimeoutException { future.get(1, TimeUnit.MILLISECONDS); } @Test(expected = AssertionError.class) public void testThrowsAssertionErrorIfFinishesWaitingWithoutTimeoutAndDoesNotReceiveResult() throws ExecutionException, InterruptedException { future.get(); } @Test public void testNotifiesAllWhenLoadFails() { future.onLoadFailed(null); verify(waiter).notifyAll(eq(future)); } @Test public void testNotifiesAllWhenResourceReady() { future.onResourceReady(null, null); verify(waiter).notifyAll(eq(future)); } @Test public void testNotifiesAllOnCancelIfNotCancelled() { future.cancel(false); verify(waiter).notifyAll(eq(future)); } @Test public void testDoesNotNotifyAllOnSecondCancel() { future.cancel(true); verify(waiter).notifyAll(eq(future)); future.cancel(true); verify(waiter, times(1)).notifyAll(eq(future)); } @Test public void testReturnsResourceIfReceivedWhileWaiting() throws ExecutionException, InterruptedException { final Object expected = new Object(); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) throws Throwable { future.onResourceReady(expected, null); return null; } }).when(waiter).waitForTimeout(eq(future), anyLong()); assertEquals(expected, future.get()); } @Test public void testWaitsForeverIfNoTimeoutSet() throws InterruptedException { try { future.get(); } catch (ExecutionException e) { throw new RuntimeException(e); } catch (AssertionError e) { // Expected. } verify(waiter).waitForTimeout(eq(future), eq(0L)); } @Test public void testWaitsForGivenTimeoutMillisIfTimeoutSet() throws InterruptedException { long timeout = 1234; try { future.get(1234, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } catch (TimeoutException e) { // Expected. } verify(waiter).waitForTimeout(eq(future), eq(timeout)); } @Test public void testConvertsOtherTimeUnitsToMillisForWaiter() throws InterruptedException { long timeoutSeconds = 10; try { future.get(timeoutSeconds, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } catch (TimeoutException e) { // Expected. } verify(waiter).waitForTimeout(eq(future), eq(TimeUnit.SECONDS.toMillis(timeoutSeconds))); } @Test public void testDoesNotWaitIfGivenTimeOutEqualToZero() throws InterruptedException { try { future.get(0, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } catch (TimeoutException e) { // Expected. } verify(waiter, never()).waitForTimeout(eq(future), anyLong()); } }
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jmx.export.metadata; import org.springframework.jmx.JmxException; /** * Thrown by the <code>JmxAttributeSource</code> when it encounters * incorrect metadata on a managed resource or one of its methods. * * @author Rob Harrop * @since 1.2 * @see JmxAttributeSource * @see org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler */ public class InvalidMetadataException extends JmxException { /** * Create a new <code>InvalidMetadataException</code> with the supplied * error message. * @param msg the detail message */ public InvalidMetadataException(String msg) { super(msg); } }
/* * Copyright (c) 2002-2016 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.javascript.configuration; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation to check of whether this getter read-only method allows to set the value, * ignore it, or throw an exception. * * @author Ahmed Ashour */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CanSetReadOnly { /** * The status. * @return the status */ CanSetReadOnlyStatus value() default CanSetReadOnlyStatus.YES; }
package module1188.a; import javax.naming.directory.*; import javax.net.ssl.*; import javax.rmi.ssl.*; /** * Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut * labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. * Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. * * @see javax.annotation.processing.Completion * @see javax.lang.model.AnnotatedConstruct * @see javax.management.Attribute */ @SuppressWarnings("all") public abstract class Foo1<T> extends module1188.a.Foo0<T> implements module1188.a.IFoo1<T> { javax.naming.directory.DirContext f0 = null; javax.net.ssl.ExtendedSSLSession f1 = null; javax.rmi.ssl.SslRMIClientSocketFactory f2 = null; public T element; public static Foo1 instance; public static Foo1 getInstance() { return instance; } public static <T> T create(java.util.List<T> input) { return module1188.a.Foo0.create(input); } public String getName() { return module1188.a.Foo0.getInstance().getName(); } public void setName(String string) { module1188.a.Foo0.getInstance().setName(getName()); return; } public T get() { return (T)module1188.a.Foo0.getInstance().get(); } public void set(Object element) { this.element = (T)element; module1188.a.Foo0.getInstance().set(this.element); } public T call() throws Exception { return (T)module1188.a.Foo0.getInstance().call(); } }
package kim.xiaom.blog.entity.queryObjects; import java.util.ArrayList; import java.util.Date; import java.util.List; public class CommentExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public CommentExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andCommentIdIsNull() { addCriterion("comment_id is null"); return (Criteria) this; } public Criteria andCommentIdIsNotNull() { addCriterion("comment_id is not null"); return (Criteria) this; } public Criteria andCommentIdEqualTo(String value) { addCriterion("comment_id =", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdNotEqualTo(String value) { addCriterion("comment_id <>", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdGreaterThan(String value) { addCriterion("comment_id >", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdGreaterThanOrEqualTo(String value) { addCriterion("comment_id >=", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdLessThan(String value) { addCriterion("comment_id <", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdLessThanOrEqualTo(String value) { addCriterion("comment_id <=", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdLike(String value) { addCriterion("comment_id like", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdNotLike(String value) { addCriterion("comment_id not like", value, "commentId"); return (Criteria) this; } public Criteria andCommentIdIn(List<String> values) { addCriterion("comment_id in", values, "commentId"); return (Criteria) this; } public Criteria andCommentIdNotIn(List<String> values) { addCriterion("comment_id not in", values, "commentId"); return (Criteria) this; } public Criteria andCommentIdBetween(String value1, String value2) { addCriterion("comment_id between", value1, value2, "commentId"); return (Criteria) this; } public Criteria andCommentIdNotBetween(String value1, String value2) { addCriterion("comment_id not between", value1, value2, "commentId"); return (Criteria) this; } public Criteria andTextIsNull() { addCriterion("text is null"); return (Criteria) this; } public Criteria andTextIsNotNull() { addCriterion("text is not null"); return (Criteria) this; } public Criteria andTextEqualTo(String value) { addCriterion("text =", value, "text"); return (Criteria) this; } public Criteria andTextNotEqualTo(String value) { addCriterion("text <>", value, "text"); return (Criteria) this; } public Criteria andTextGreaterThan(String value) { addCriterion("text >", value, "text"); return (Criteria) this; } public Criteria andTextGreaterThanOrEqualTo(String value) { addCriterion("text >=", value, "text"); return (Criteria) this; } public Criteria andTextLessThan(String value) { addCriterion("text <", value, "text"); return (Criteria) this; } public Criteria andTextLessThanOrEqualTo(String value) { addCriterion("text <=", value, "text"); return (Criteria) this; } public Criteria andTextLike(String value) { addCriterion("text like", value, "text"); return (Criteria) this; } public Criteria andTextNotLike(String value) { addCriterion("text not like", value, "text"); return (Criteria) this; } public Criteria andTextIn(List<String> values) { addCriterion("text in", values, "text"); return (Criteria) this; } public Criteria andTextNotIn(List<String> values) { addCriterion("text not in", values, "text"); return (Criteria) this; } public Criteria andTextBetween(String value1, String value2) { addCriterion("text between", value1, value2, "text"); return (Criteria) this; } public Criteria andTextNotBetween(String value1, String value2) { addCriterion("text not between", value1, value2, "text"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Integer value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Integer value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Integer value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Integer value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Integer value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Integer value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Integer> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Integer> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Integer value1, Integer value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Integer value1, Integer value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andActiveIsNull() { addCriterion("active is null"); return (Criteria) this; } public Criteria andActiveIsNotNull() { addCriterion("active is not null"); return (Criteria) this; } public Criteria andActiveEqualTo(Integer value) { addCriterion("active =", value, "active"); return (Criteria) this; } public Criteria andActiveNotEqualTo(Integer value) { addCriterion("active <>", value, "active"); return (Criteria) this; } public Criteria andActiveGreaterThan(Integer value) { addCriterion("active >", value, "active"); return (Criteria) this; } public Criteria andActiveGreaterThanOrEqualTo(Integer value) { addCriterion("active >=", value, "active"); return (Criteria) this; } public Criteria andActiveLessThan(Integer value) { addCriterion("active <", value, "active"); return (Criteria) this; } public Criteria andActiveLessThanOrEqualTo(Integer value) { addCriterion("active <=", value, "active"); return (Criteria) this; } public Criteria andActiveIn(List<Integer> values) { addCriterion("active in", values, "active"); return (Criteria) this; } public Criteria andActiveNotIn(List<Integer> values) { addCriterion("active not in", values, "active"); return (Criteria) this; } public Criteria andActiveBetween(Integer value1, Integer value2) { addCriterion("active between", value1, value2, "active"); return (Criteria) this; } public Criteria andActiveNotBetween(Integer value1, Integer value2) { addCriterion("active not between", value1, value2, "active"); return (Criteria) this; } public Criteria andVersionIsNull() { addCriterion("version is null"); return (Criteria) this; } public Criteria andVersionIsNotNull() { addCriterion("version is not null"); return (Criteria) this; } public Criteria andVersionEqualTo(Integer value) { addCriterion("version =", value, "version"); return (Criteria) this; } public Criteria andVersionNotEqualTo(Integer value) { addCriterion("version <>", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThan(Integer value) { addCriterion("version >", value, "version"); return (Criteria) this; } public Criteria andVersionGreaterThanOrEqualTo(Integer value) { addCriterion("version >=", value, "version"); return (Criteria) this; } public Criteria andVersionLessThan(Integer value) { addCriterion("version <", value, "version"); return (Criteria) this; } public Criteria andVersionLessThanOrEqualTo(Integer value) { addCriterion("version <=", value, "version"); return (Criteria) this; } public Criteria andVersionIn(List<Integer> values) { addCriterion("version in", values, "version"); return (Criteria) this; } public Criteria andVersionNotIn(List<Integer> values) { addCriterion("version not in", values, "version"); return (Criteria) this; } public Criteria andVersionBetween(Integer value1, Integer value2) { addCriterion("version between", value1, value2, "version"); return (Criteria) this; } public Criteria andVersionNotBetween(Integer value1, Integer value2) { addCriterion("version not between", value1, value2, "version"); return (Criteria) this; } public Criteria andGmtCreateIsNull() { addCriterion("gmt_create is null"); return (Criteria) this; } public Criteria andGmtCreateIsNotNull() { addCriterion("gmt_create is not null"); return (Criteria) this; } public Criteria andGmtCreateEqualTo(Date value) { addCriterion("gmt_create =", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotEqualTo(Date value) { addCriterion("gmt_create <>", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateGreaterThan(Date value) { addCriterion("gmt_create >", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateGreaterThanOrEqualTo(Date value) { addCriterion("gmt_create >=", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateLessThan(Date value) { addCriterion("gmt_create <", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateLessThanOrEqualTo(Date value) { addCriterion("gmt_create <=", value, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateIn(List<Date> values) { addCriterion("gmt_create in", values, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotIn(List<Date> values) { addCriterion("gmt_create not in", values, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateBetween(Date value1, Date value2) { addCriterion("gmt_create between", value1, value2, "gmtCreate"); return (Criteria) this; } public Criteria andGmtCreateNotBetween(Date value1, Date value2) { addCriterion("gmt_create not between", value1, value2, "gmtCreate"); return (Criteria) this; } public Criteria andGmtModifyIsNull() { addCriterion("gmt_modify is null"); return (Criteria) this; } public Criteria andGmtModifyIsNotNull() { addCriterion("gmt_modify is not null"); return (Criteria) this; } public Criteria andGmtModifyEqualTo(Date value) { addCriterion("gmt_modify =", value, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyNotEqualTo(Date value) { addCriterion("gmt_modify <>", value, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyGreaterThan(Date value) { addCriterion("gmt_modify >", value, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyGreaterThanOrEqualTo(Date value) { addCriterion("gmt_modify >=", value, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyLessThan(Date value) { addCriterion("gmt_modify <", value, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyLessThanOrEqualTo(Date value) { addCriterion("gmt_modify <=", value, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyIn(List<Date> values) { addCriterion("gmt_modify in", values, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyNotIn(List<Date> values) { addCriterion("gmt_modify not in", values, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyBetween(Date value1, Date value2) { addCriterion("gmt_modify between", value1, value2, "gmtModify"); return (Criteria) this; } public Criteria andGmtModifyNotBetween(Date value1, Date value2) { addCriterion("gmt_modify not between", value1, value2, "gmtModify"); return (Criteria) this; } public Criteria andCreatorIsNull() { addCriterion("creator is null"); return (Criteria) this; } public Criteria andCreatorIsNotNull() { addCriterion("creator is not null"); return (Criteria) this; } public Criteria andCreatorEqualTo(String value) { addCriterion("creator =", value, "creator"); return (Criteria) this; } public Criteria andCreatorNotEqualTo(String value) { addCriterion("creator <>", value, "creator"); return (Criteria) this; } public Criteria andCreatorGreaterThan(String value) { addCriterion("creator >", value, "creator"); return (Criteria) this; } public Criteria andCreatorGreaterThanOrEqualTo(String value) { addCriterion("creator >=", value, "creator"); return (Criteria) this; } public Criteria andCreatorLessThan(String value) { addCriterion("creator <", value, "creator"); return (Criteria) this; } public Criteria andCreatorLessThanOrEqualTo(String value) { addCriterion("creator <=", value, "creator"); return (Criteria) this; } public Criteria andCreatorLike(String value) { addCriterion("creator like", value, "creator"); return (Criteria) this; } public Criteria andCreatorNotLike(String value) { addCriterion("creator not like", value, "creator"); return (Criteria) this; } public Criteria andCreatorIn(List<String> values) { addCriterion("creator in", values, "creator"); return (Criteria) this; } public Criteria andCreatorNotIn(List<String> values) { addCriterion("creator not in", values, "creator"); return (Criteria) this; } public Criteria andCreatorBetween(String value1, String value2) { addCriterion("creator between", value1, value2, "creator"); return (Criteria) this; } public Criteria andCreatorNotBetween(String value1, String value2) { addCriterion("creator not between", value1, value2, "creator"); return (Criteria) this; } public Criteria andModifierIsNull() { addCriterion("modifier is null"); return (Criteria) this; } public Criteria andModifierIsNotNull() { addCriterion("modifier is not null"); return (Criteria) this; } public Criteria andModifierEqualTo(String value) { addCriterion("modifier =", value, "modifier"); return (Criteria) this; } public Criteria andModifierNotEqualTo(String value) { addCriterion("modifier <>", value, "modifier"); return (Criteria) this; } public Criteria andModifierGreaterThan(String value) { addCriterion("modifier >", value, "modifier"); return (Criteria) this; } public Criteria andModifierGreaterThanOrEqualTo(String value) { addCriterion("modifier >=", value, "modifier"); return (Criteria) this; } public Criteria andModifierLessThan(String value) { addCriterion("modifier <", value, "modifier"); return (Criteria) this; } public Criteria andModifierLessThanOrEqualTo(String value) { addCriterion("modifier <=", value, "modifier"); return (Criteria) this; } public Criteria andModifierLike(String value) { addCriterion("modifier like", value, "modifier"); return (Criteria) this; } public Criteria andModifierNotLike(String value) { addCriterion("modifier not like", value, "modifier"); return (Criteria) this; } public Criteria andModifierIn(List<String> values) { addCriterion("modifier in", values, "modifier"); return (Criteria) this; } public Criteria andModifierNotIn(List<String> values) { addCriterion("modifier not in", values, "modifier"); return (Criteria) this; } public Criteria andModifierBetween(String value1, String value2) { addCriterion("modifier between", value1, value2, "modifier"); return (Criteria) this; } public Criteria andModifierNotBetween(String value1, String value2) { addCriterion("modifier not between", value1, value2, "modifier"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package org.apache.maven.cli; /* * 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. */ import com.google.inject.AbstractModule; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.UnrecognizedOptionException; import org.apache.maven.BuildAbort; import org.apache.maven.InternalErrorException; import org.apache.maven.Maven; import org.apache.maven.building.FileSource; import org.apache.maven.building.Problem; import org.apache.maven.building.Source; import org.apache.maven.cli.configuration.ConfigurationProcessor; import org.apache.maven.cli.configuration.SettingsXmlConfigurationProcessor; import org.apache.maven.cli.event.DefaultEventSpyContext; import org.apache.maven.cli.event.ExecutionEventLogger; import org.apache.maven.cli.internal.BootstrapCoreExtensionManager; import org.apache.maven.cli.internal.extension.model.CoreExtension; import org.apache.maven.cli.internal.extension.model.io.xpp3.CoreExtensionsXpp3Reader; import org.apache.maven.cli.logging.Slf4jConfiguration; import org.apache.maven.cli.logging.Slf4jConfigurationFactory; import org.apache.maven.cli.logging.Slf4jLoggerManager; import org.apache.maven.cli.logging.Slf4jStdoutLogger; import org.apache.maven.cli.transfer.ConsoleMavenTransferListener; import org.apache.maven.cli.transfer.QuietMavenTransferListener; import org.apache.maven.cli.transfer.Slf4jMavenTransferListener; import org.apache.maven.eventspy.internal.EventSpyDispatcher; import org.apache.maven.exception.DefaultExceptionHandler; import org.apache.maven.exception.ExceptionHandler; import org.apache.maven.exception.ExceptionSummary; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.ExecutionListener; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequestPopulationException; import org.apache.maven.execution.MavenExecutionRequestPopulator; import org.apache.maven.execution.MavenExecutionResult; import org.apache.maven.execution.ProfileActivation; import org.apache.maven.execution.scope.internal.MojoExecutionScopeModule; import org.apache.maven.extension.internal.CoreExports; import org.apache.maven.extension.internal.CoreExtensionEntry; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.logwrapper.LogLevelRecorder; import org.apache.maven.logwrapper.MavenSlf4jWrapperFactory; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.project.MavenProject; import org.apache.maven.properties.internal.EnvironmentUtils; import org.apache.maven.properties.internal.SystemProperties; import org.apache.maven.session.scope.internal.SessionScopeModule; import org.apache.maven.shared.utils.logging.MessageBuilder; import org.apache.maven.shared.utils.logging.MessageUtils; import org.apache.maven.toolchain.building.DefaultToolchainsBuildingRequest; import org.apache.maven.toolchain.building.ToolchainsBuilder; import org.apache.maven.toolchain.building.ToolchainsBuildingResult; import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.DefaultContainerConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.NoSuchRealmException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.logging.LoggerManager; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.eclipse.aether.transfer.TransferListener; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.plexus.components.cipher.DefaultPlexusCipher; import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher; import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher; import org.sonatype.plexus.components.sec.dispatcher.SecUtil; import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity; import java.io.BufferedInputStream; import java.io.Console; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.Comparator.comparing; import static org.apache.maven.cli.ResolveFile.resolveFile; import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; // TODO push all common bits back to plexus cli and prepare for transition to Guice. We don't need 50 ways to make CLIs /** * @author Jason van Zyl */ public class MavenCli { public static final String LOCAL_REPO_PROPERTY = "maven.repo.local"; public static final String MULTIMODULE_PROJECT_DIRECTORY = "maven.multiModuleProjectDirectory"; public static final String USER_HOME = System.getProperty( "user.home" ); public static final File USER_MAVEN_CONFIGURATION_HOME = new File( USER_HOME, ".m2" ); public static final File DEFAULT_USER_TOOLCHAINS_FILE = new File( USER_MAVEN_CONFIGURATION_HOME, "toolchains.xml" ); public static final File DEFAULT_GLOBAL_TOOLCHAINS_FILE = new File( System.getProperty( "maven.conf" ), "toolchains.xml" ); private static final String EXT_CLASS_PATH = "maven.ext.class.path"; private static final String EXTENSIONS_FILENAME = ".mvn/extensions.xml"; private static final String MVN_MAVEN_CONFIG = ".mvn/maven.config"; public static final String STYLE_COLOR_PROPERTY = "style.color"; private ClassWorld classWorld; private LoggerManager plexusLoggerManager; private ILoggerFactory slf4jLoggerFactory; private Logger slf4jLogger; private EventSpyDispatcher eventSpyDispatcher; private ModelProcessor modelProcessor; private Maven maven; private MavenExecutionRequestPopulator executionRequestPopulator; private ToolchainsBuilder toolchainsBuilder; private DefaultSecDispatcher dispatcher; private Map<String, ConfigurationProcessor> configurationProcessors; public MavenCli() { this( null ); } // This supports painless invocation by the Verifier during embedded execution of the core ITs public MavenCli( ClassWorld classWorld ) { this.classWorld = classWorld; } public static void main( String[] args ) { int result = main( args, null ); System.exit( result ); } public static int main( String[] args, ClassWorld classWorld ) { MavenCli cli = new MavenCli(); MessageUtils.systemInstall(); MessageUtils.registerShutdownHook(); int result = cli.doMain( new CliRequest( args, classWorld ) ); MessageUtils.systemUninstall(); return result; } // TODO need to externalize CliRequest public static int doMain( String[] args, ClassWorld classWorld ) { MavenCli cli = new MavenCli(); return cli.doMain( new CliRequest( args, classWorld ) ); } /** * This supports painless invocation by the Verifier during embedded execution of the core ITs. * See <a href="http://maven.apache.org/shared/maven-verifier/xref/org/apache/maven/it/Embedded3xLauncher.html"> * <code>Embedded3xLauncher</code> in <code>maven-verifier</code></a> */ public int doMain( String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr ) { PrintStream oldout = System.out; PrintStream olderr = System.err; final Set<String> realms; if ( classWorld != null ) { realms = new HashSet<>(); for ( ClassRealm realm : classWorld.getRealms() ) { realms.add( realm.getId() ); } } else { realms = Collections.emptySet(); } try { if ( stdout != null ) { System.setOut( stdout ); } if ( stderr != null ) { System.setErr( stderr ); } CliRequest cliRequest = new CliRequest( args, classWorld ); cliRequest.workingDirectory = workingDirectory; return doMain( cliRequest ); } finally { if ( classWorld != null ) { for ( ClassRealm realm : new ArrayList<>( classWorld.getRealms() ) ) { String realmId = realm.getId(); if ( !realms.contains( realmId ) ) { try { classWorld.disposeRealm( realmId ); } catch ( NoSuchRealmException ignored ) { // can't happen } } } } System.setOut( oldout ); System.setErr( olderr ); } } // TODO need to externalize CliRequest public int doMain( CliRequest cliRequest ) { PlexusContainer localContainer = null; try { initialize( cliRequest ); cli( cliRequest ); properties( cliRequest ); logging( cliRequest ); version( cliRequest ); localContainer = container( cliRequest ); commands( cliRequest ); configure( cliRequest ); toolchains( cliRequest ); populateRequest( cliRequest ); encryption( cliRequest ); repository( cliRequest ); return execute( cliRequest ); } catch ( ExitException e ) { return e.exitCode; } catch ( UnrecognizedOptionException e ) { // pure user error, suppress stack trace return 1; } catch ( BuildAbort e ) { CLIReportingUtils.showError( slf4jLogger, "ABORTED", e, cliRequest.showErrors ); return 2; } catch ( Exception e ) { CLIReportingUtils.showError( slf4jLogger, "Error executing Maven.", e, cliRequest.showErrors ); return 1; } finally { if ( localContainer != null ) { localContainer.dispose(); } } } void initialize( CliRequest cliRequest ) throws ExitException { if ( cliRequest.workingDirectory == null ) { cliRequest.workingDirectory = System.getProperty( "user.dir" ); } if ( cliRequest.multiModuleProjectDirectory == null ) { String basedirProperty = System.getProperty( MULTIMODULE_PROJECT_DIRECTORY ); if ( basedirProperty == null ) { System.err.format( "-D%s system property is not set.", MULTIMODULE_PROJECT_DIRECTORY ); throw new ExitException( 1 ); } File basedir = new File( basedirProperty ); try { cliRequest.multiModuleProjectDirectory = basedir.getCanonicalFile(); } catch ( IOException e ) { cliRequest.multiModuleProjectDirectory = basedir.getAbsoluteFile(); } } // // Make sure the Maven home directory is an absolute path to save us from confusion with say drive-relative // Windows paths. // String mavenHome = System.getProperty( "maven.home" ); if ( mavenHome != null ) { System.setProperty( "maven.home", new File( mavenHome ).getAbsolutePath() ); } } void cli( CliRequest cliRequest ) throws Exception { // // Parsing errors can happen during the processing of the arguments and we prefer not having to check if // the logger is null and construct this so we can use an SLF4J logger everywhere. // slf4jLogger = new Slf4jStdoutLogger(); CLIManager cliManager = new CLIManager(); List<String> args = new ArrayList<>(); CommandLine mavenConfig = null; try { File configFile = new File( cliRequest.multiModuleProjectDirectory, MVN_MAVEN_CONFIG ); if ( configFile.isFile() ) { for ( String arg : new String( Files.readAllBytes( configFile.toPath() ) ).split( "\\s+" ) ) { if ( !arg.isEmpty() ) { args.add( arg ); } } mavenConfig = cliManager.parse( args.toArray( new String[0] ) ); List<?> unrecongized = mavenConfig.getArgList(); if ( !unrecongized.isEmpty() ) { throw new ParseException( "Unrecognized maven.config entries: " + unrecongized ); } } } catch ( ParseException e ) { System.err.println( "Unable to parse maven.config: " + e.getMessage() ); cliManager.displayHelp( System.out ); throw e; } try { if ( mavenConfig == null ) { cliRequest.commandLine = cliManager.parse( cliRequest.args ); } else { cliRequest.commandLine = cliMerge( cliManager.parse( cliRequest.args ), mavenConfig ); } } catch ( ParseException e ) { System.err.println( "Unable to parse command line options: " + e.getMessage() ); cliManager.displayHelp( System.out ); throw e; } if ( cliRequest.commandLine.hasOption( CLIManager.HELP ) ) { cliManager.displayHelp( System.out ); throw new ExitException( 0 ); } if ( cliRequest.commandLine.hasOption( CLIManager.VERSION ) ) { System.out.println( CLIReportingUtils.showVersion() ); throw new ExitException( 0 ); } } private CommandLine cliMerge( CommandLine mavenArgs, CommandLine mavenConfig ) { CommandLine.Builder commandLineBuilder = new CommandLine.Builder(); // the args are easy, cli first then config file for ( String arg : mavenArgs.getArgs() ) { commandLineBuilder.addArg( arg ); } for ( String arg : mavenConfig.getArgs() ) { commandLineBuilder.addArg( arg ); } // now add all options, except for -D with cli first then config file List<Option> setPropertyOptions = new ArrayList<>(); for ( Option opt : mavenArgs.getOptions() ) { if ( String.valueOf( CLIManager.SET_SYSTEM_PROPERTY ).equals( opt.getOpt() ) ) { setPropertyOptions.add( opt ); } else { commandLineBuilder.addOption( opt ); } } for ( Option opt : mavenConfig.getOptions() ) { commandLineBuilder.addOption( opt ); } // finally add the CLI system properties for ( Option opt : setPropertyOptions ) { commandLineBuilder.addOption( opt ); } return commandLineBuilder.build(); } /** * configure logging */ void logging( CliRequest cliRequest ) { // LOG LEVEL cliRequest.debug = cliRequest.commandLine.hasOption( CLIManager.DEBUG ); cliRequest.quiet = !cliRequest.debug && cliRequest.commandLine.hasOption( CLIManager.QUIET ); cliRequest.showErrors = cliRequest.debug || cliRequest.commandLine.hasOption( CLIManager.ERRORS ); slf4jLoggerFactory = LoggerFactory.getILoggerFactory(); Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration( slf4jLoggerFactory ); if ( cliRequest.debug ) { cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_DEBUG ); slf4jConfiguration.setRootLoggerLevel( Slf4jConfiguration.Level.DEBUG ); } else if ( cliRequest.quiet ) { cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_ERROR ); slf4jConfiguration.setRootLoggerLevel( Slf4jConfiguration.Level.ERROR ); } // else fall back to default log level specified in conf // see https://issues.apache.org/jira/browse/MNG-2570 // LOG COLOR String styleColor = cliRequest.getUserProperties().getProperty( STYLE_COLOR_PROPERTY, "auto" ); if ( "always".equals( styleColor ) ) { MessageUtils.setColorEnabled( true ); } else if ( "never".equals( styleColor ) ) { MessageUtils.setColorEnabled( false ); } else if ( !"auto".equals( styleColor ) ) { throw new IllegalArgumentException( "Invalid color configuration option [" + styleColor + "]. Supported values are (auto|always|never)." ); } else if ( cliRequest.commandLine.hasOption( CLIManager.BATCH_MODE ) || cliRequest.commandLine.hasOption( CLIManager.LOG_FILE ) ) { MessageUtils.setColorEnabled( false ); } // LOG STREAMS if ( cliRequest.commandLine.hasOption( CLIManager.LOG_FILE ) ) { File logFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.LOG_FILE ) ); logFile = resolveFile( logFile, cliRequest.workingDirectory ); // redirect stdout and stderr to file try { PrintStream ps = new PrintStream( new FileOutputStream( logFile ) ); System.setOut( ps ); System.setErr( ps ); } catch ( FileNotFoundException e ) { // // Ignore // } } slf4jConfiguration.activate(); plexusLoggerManager = new Slf4jLoggerManager(); slf4jLogger = slf4jLoggerFactory.getLogger( this.getClass().getName() ); if ( cliRequest.commandLine.hasOption( CLIManager.FAIL_ON_SEVERITY ) ) { String logLevelThreshold = cliRequest.commandLine.getOptionValue( CLIManager.FAIL_ON_SEVERITY ); if ( slf4jLoggerFactory instanceof MavenSlf4jWrapperFactory ) { LogLevelRecorder logLevelRecorder = new LogLevelRecorder( logLevelThreshold ); ( (MavenSlf4jWrapperFactory) slf4jLoggerFactory ).setLogLevelRecorder( logLevelRecorder ); slf4jLogger.info( "Enabled to break the build on log level {}.", logLevelThreshold ); } else { slf4jLogger.warn( "Expected LoggerFactory to be of type '{}', but found '{}' instead. " + "The --fail-on-severity flag will not take effect.", MavenSlf4jWrapperFactory.class.getName(), slf4jLoggerFactory.getClass().getName() ); } } } private void version( CliRequest cliRequest ) { if ( cliRequest.debug || cliRequest.commandLine.hasOption( CLIManager.SHOW_VERSION ) ) { System.out.println( CLIReportingUtils.showVersion() ); } } private void commands( CliRequest cliRequest ) { if ( cliRequest.showErrors ) { slf4jLogger.info( "Error stacktraces are turned on." ); } if ( MavenExecutionRequest.CHECKSUM_POLICY_WARN.equals( cliRequest.request.getGlobalChecksumPolicy() ) ) { slf4jLogger.info( "Disabling strict checksum verification on all artifact downloads." ); } else if ( MavenExecutionRequest.CHECKSUM_POLICY_FAIL.equals( cliRequest.request.getGlobalChecksumPolicy() ) ) { slf4jLogger.info( "Enabling strict checksum verification on all artifact downloads." ); } if ( slf4jLogger.isDebugEnabled() ) { slf4jLogger.debug( "Message scheme: {}", ( MessageUtils.isColorEnabled() ? "color" : "plain" ) ); if ( MessageUtils.isColorEnabled() ) { MessageBuilder buff = MessageUtils.buffer(); buff.a( "Message styles: " ); buff.a( MessageUtils.level().debug( "debug" ) ).a( ' ' ); buff.a( MessageUtils.level().info( "info" ) ).a( ' ' ); buff.a( MessageUtils.level().warning( "warning" ) ).a( ' ' ); buff.a( MessageUtils.level().error( "error" ) ).a( ' ' ); buff.success( "success" ).a( ' ' ); buff.failure( "failure" ).a( ' ' ); buff.strong( "strong" ).a( ' ' ); buff.mojo( "mojo" ).a( ' ' ); buff.project( "project" ); slf4jLogger.debug( buff.toString() ); } } } //Needed to make this method package visible to make writing a unit test possible //Maybe it's better to move some of those methods to separate class (SoC). void properties( CliRequest cliRequest ) { populateProperties( cliRequest.commandLine, cliRequest.systemProperties, cliRequest.userProperties ); } PlexusContainer container( CliRequest cliRequest ) throws Exception { if ( cliRequest.classWorld == null ) { cliRequest.classWorld = new ClassWorld( "plexus.core", Thread.currentThread().getContextClassLoader() ); } ClassRealm coreRealm = cliRequest.classWorld.getClassRealm( "plexus.core" ); if ( coreRealm == null ) { coreRealm = cliRequest.classWorld.getRealms().iterator().next(); } List<File> extClassPath = parseExtClasspath( cliRequest ); CoreExtensionEntry coreEntry = CoreExtensionEntry.discoverFrom( coreRealm ); List<CoreExtensionEntry> extensions = loadCoreExtensions( cliRequest, coreRealm, coreEntry.getExportedArtifacts() ); ClassRealm containerRealm = setupContainerRealm( cliRequest.classWorld, coreRealm, extClassPath, extensions ); ContainerConfiguration cc = new DefaultContainerConfiguration().setClassWorld( cliRequest.classWorld ) .setRealm( containerRealm ).setClassPathScanning( PlexusConstants.SCANNING_INDEX ).setAutoWiring( true ) .setJSR250Lifecycle( true ).setName( "maven" ); Set<String> exportedArtifacts = new HashSet<>( coreEntry.getExportedArtifacts() ); Set<String> exportedPackages = new HashSet<>( coreEntry.getExportedPackages() ); for ( CoreExtensionEntry extension : extensions ) { exportedArtifacts.addAll( extension.getExportedArtifacts() ); exportedPackages.addAll( extension.getExportedPackages() ); } final CoreExports exports = new CoreExports( containerRealm, exportedArtifacts, exportedPackages ); DefaultPlexusContainer container = new DefaultPlexusContainer( cc, new AbstractModule() { @Override protected void configure() { bind( ILoggerFactory.class ).toInstance( slf4jLoggerFactory ); bind( CoreExports.class ).toInstance( exports ); } } ); // NOTE: To avoid inconsistencies, we'll use the TCCL exclusively for lookups container.setLookupRealm( null ); Thread.currentThread().setContextClassLoader( container.getContainerRealm() ); container.setLoggerManager( plexusLoggerManager ); for ( CoreExtensionEntry extension : extensions ) { container.discoverComponents( extension.getClassRealm(), new SessionScopeModule( container ), new MojoExecutionScopeModule( container ) ); } customizeContainer( container ); container.getLoggerManager().setThresholds( cliRequest.request.getLoggingLevel() ); eventSpyDispatcher = container.lookup( EventSpyDispatcher.class ); DefaultEventSpyContext eventSpyContext = new DefaultEventSpyContext(); Map<String, Object> data = eventSpyContext.getData(); data.put( "plexus", container ); data.put( "workingDirectory", cliRequest.workingDirectory ); data.put( "systemProperties", cliRequest.systemProperties ); data.put( "userProperties", cliRequest.userProperties ); data.put( "versionProperties", CLIReportingUtils.getBuildProperties() ); eventSpyDispatcher.init( eventSpyContext ); // refresh logger in case container got customized by spy slf4jLogger = slf4jLoggerFactory.getLogger( this.getClass().getName() ); maven = container.lookup( Maven.class ); executionRequestPopulator = container.lookup( MavenExecutionRequestPopulator.class ); modelProcessor = createModelProcessor( container ); configurationProcessors = container.lookupMap( ConfigurationProcessor.class ); toolchainsBuilder = container.lookup( ToolchainsBuilder.class ); dispatcher = (DefaultSecDispatcher) container.lookup( SecDispatcher.class, "maven" ); return container; } private List<CoreExtensionEntry> loadCoreExtensions( CliRequest cliRequest, ClassRealm containerRealm, Set<String> providedArtifacts ) { if ( cliRequest.multiModuleProjectDirectory == null ) { return Collections.emptyList(); } File extensionsFile = new File( cliRequest.multiModuleProjectDirectory, EXTENSIONS_FILENAME ); if ( !extensionsFile.isFile() ) { return Collections.emptyList(); } try { List<CoreExtension> extensions = readCoreExtensionsDescriptor( extensionsFile ); if ( extensions.isEmpty() ) { return Collections.emptyList(); } ContainerConfiguration cc = new DefaultContainerConfiguration() // .setClassWorld( cliRequest.classWorld ) // .setRealm( containerRealm ) // .setClassPathScanning( PlexusConstants.SCANNING_INDEX ) // .setAutoWiring( true ) // .setJSR250Lifecycle( true ) // .setName( "maven" ); DefaultPlexusContainer container = new DefaultPlexusContainer( cc, new AbstractModule() { @Override protected void configure() { bind( ILoggerFactory.class ).toInstance( slf4jLoggerFactory ); } } ); try { container.setLookupRealm( null ); container.setLoggerManager( plexusLoggerManager ); container.getLoggerManager().setThresholds( cliRequest.request.getLoggingLevel() ); Thread.currentThread().setContextClassLoader( container.getContainerRealm() ); executionRequestPopulator = container.lookup( MavenExecutionRequestPopulator.class ); configurationProcessors = container.lookupMap( ConfigurationProcessor.class ); configure( cliRequest ); MavenExecutionRequest request = DefaultMavenExecutionRequest.copy( cliRequest.request ); populateRequest( cliRequest, request ); request = executionRequestPopulator.populateDefaults( request ); BootstrapCoreExtensionManager resolver = container.lookup( BootstrapCoreExtensionManager.class ); return Collections.unmodifiableList( resolver.loadCoreExtensions( request, providedArtifacts, extensions ) ); } finally { executionRequestPopulator = null; container.dispose(); } } catch ( RuntimeException e ) { // runtime exceptions are most likely bugs in maven, let them bubble up to the user throw e; } catch ( Exception e ) { slf4jLogger.warn( "Failed to read extensions descriptor from '{}'", extensionsFile, e ); } return Collections.emptyList(); } private List<CoreExtension> readCoreExtensionsDescriptor( File extensionsFile ) throws IOException, XmlPullParserException { CoreExtensionsXpp3Reader parser = new CoreExtensionsXpp3Reader(); try ( InputStream is = new BufferedInputStream( new FileInputStream( extensionsFile ) ) ) { return parser.read( is ).getExtensions(); } } private ClassRealm setupContainerRealm( ClassWorld classWorld, ClassRealm coreRealm, List<File> extClassPath, List<CoreExtensionEntry> extensions ) throws Exception { if ( !extClassPath.isEmpty() || !extensions.isEmpty() ) { ClassRealm extRealm = classWorld.newRealm( "maven.ext", null ); extRealm.setParentRealm( coreRealm ); slf4jLogger.debug( "Populating class realm '{}'", extRealm.getId() ); for ( File file : extClassPath ) { slf4jLogger.debug( " included '{}'", file ); extRealm.addURL( file.toURI().toURL() ); } for ( CoreExtensionEntry entry : reverse( extensions ) ) { Set<String> exportedPackages = entry.getExportedPackages(); ClassRealm realm = entry.getClassRealm(); for ( String exportedPackage : exportedPackages ) { extRealm.importFrom( realm, exportedPackage ); } if ( exportedPackages.isEmpty() ) { // sisu uses realm imports to establish component visibility extRealm.importFrom( realm, realm.getId() ); } } return extRealm; } return coreRealm; } private static <T> List<T> reverse( List<T> list ) { List<T> copy = new ArrayList<>( list ); Collections.reverse( copy ); return copy; } private List<File> parseExtClasspath( CliRequest cliRequest ) { String extClassPath = cliRequest.userProperties.getProperty( EXT_CLASS_PATH ); if ( extClassPath == null ) { extClassPath = cliRequest.systemProperties.getProperty( EXT_CLASS_PATH ); } List<File> jars = new ArrayList<>(); if ( StringUtils.isNotEmpty( extClassPath ) ) { for ( String jar : StringUtils.split( extClassPath, File.pathSeparator ) ) { File file = resolveFile( new File( jar ), cliRequest.workingDirectory ); slf4jLogger.debug( " included '{}'", file ); jars.add( file ); } } return jars; } // // This should probably be a separate tool and not be baked into Maven. // private void encryption( CliRequest cliRequest ) throws Exception { if ( cliRequest.commandLine.hasOption( CLIManager.ENCRYPT_MASTER_PASSWORD ) ) { String passwd = cliRequest.commandLine.getOptionValue( CLIManager.ENCRYPT_MASTER_PASSWORD ); if ( passwd == null ) { Console cons = System.console(); char[] password = ( cons == null ) ? null : cons.readPassword( "Master password: " ); if ( password != null ) { // Cipher uses Strings passwd = String.copyValueOf( password ); // Sun/Oracle advises to empty the char array java.util.Arrays.fill( password, ' ' ); } } DefaultPlexusCipher cipher = new DefaultPlexusCipher(); System.out.println( cipher.encryptAndDecorate( passwd, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ) ); throw new ExitException( 0 ); } else if ( cliRequest.commandLine.hasOption( CLIManager.ENCRYPT_PASSWORD ) ) { String passwd = cliRequest.commandLine.getOptionValue( CLIManager.ENCRYPT_PASSWORD ); if ( passwd == null ) { Console cons = System.console(); char[] password = ( cons == null ) ? null : cons.readPassword( "Password: " ); if ( password != null ) { // Cipher uses Strings passwd = String.copyValueOf( password ); // Sun/Oracle advises to empty the char array java.util.Arrays.fill( password, ' ' ); } } String configurationFile = dispatcher.getConfigurationFile(); if ( configurationFile.startsWith( "~" ) ) { configurationFile = System.getProperty( "user.home" ) + configurationFile.substring( 1 ); } String file = System.getProperty( DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile ); String master = null; SettingsSecurity sec = SecUtil.read( file, true ); if ( sec != null ) { master = sec.getMaster(); } if ( master == null ) { throw new IllegalStateException( "Master password is not set in the setting security file: " + file ); } DefaultPlexusCipher cipher = new DefaultPlexusCipher(); String masterPasswd = cipher.decryptDecorated( master, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ); System.out.println( cipher.encryptAndDecorate( passwd, masterPasswd ) ); throw new ExitException( 0 ); } } private void repository( CliRequest cliRequest ) throws Exception { if ( cliRequest.commandLine.hasOption( CLIManager.LEGACY_LOCAL_REPOSITORY ) || Boolean.getBoolean( "maven.legacyLocalRepo" ) ) { cliRequest.request.setUseLegacyLocalRepository( true ); } } private int execute( CliRequest cliRequest ) throws MavenExecutionRequestPopulationException { MavenExecutionRequest request = executionRequestPopulator.populateDefaults( cliRequest.request ); eventSpyDispatcher.onEvent( request ); MavenExecutionResult result = maven.execute( request ); eventSpyDispatcher.onEvent( result ); eventSpyDispatcher.close(); if ( result.hasExceptions() ) { ExceptionHandler handler = new DefaultExceptionHandler(); Map<String, String> references = new LinkedHashMap<>(); List<MavenProject> failedProjects = new ArrayList<>(); for ( Throwable exception : result.getExceptions() ) { ExceptionSummary summary = handler.handleException( exception ); logSummary( summary, references, "", cliRequest.showErrors ); if ( exception instanceof LifecycleExecutionException ) { failedProjects.add ( ( (LifecycleExecutionException) exception ).getProject() ); } } slf4jLogger.error( "" ); if ( !cliRequest.showErrors ) { slf4jLogger.error( "To see the full stack trace of the errors, re-run Maven with the '{}' switch.", buffer().strong( "-e" ) ); } if ( !slf4jLogger.isDebugEnabled() ) { slf4jLogger.error( "Re-run Maven using the '{}' switch to enable full debug logging.", buffer().strong( "-X" ) ); } if ( !references.isEmpty() ) { slf4jLogger.error( "" ); slf4jLogger.error( "For more information about the errors and possible solutions" + ", please read the following articles:" ); for ( Map.Entry<String, String> entry : references.entrySet() ) { slf4jLogger.error( "{} {}", buffer().strong( entry.getValue() ), entry.getKey() ); } } if ( result.canResume() ) { logBuildResumeHint( "mvn <args> -r" ); } else if ( !failedProjects.isEmpty() ) { List<MavenProject> sortedProjects = result.getTopologicallySortedProjects(); // Sort the failedProjects list in the topologically sorted order. failedProjects.sort( comparing( sortedProjects::indexOf ) ); MavenProject firstFailedProject = failedProjects.get( 0 ); if ( !firstFailedProject.equals( sortedProjects.get( 0 ) ) ) { String resumeFromSelector = getResumeFromSelector( sortedProjects, firstFailedProject ); logBuildResumeHint( "mvn <args> -rf " + resumeFromSelector ); } } if ( MavenExecutionRequest.REACTOR_FAIL_NEVER.equals( cliRequest.request.getReactorFailureBehavior() ) ) { slf4jLogger.info( "Build failures were ignored." ); return 0; } else { return 1; } } else { return 0; } } private void logBuildResumeHint( String resumeBuildHint ) { slf4jLogger.error( "" ); slf4jLogger.error( "After correcting the problems, you can resume the build with the command" ); slf4jLogger.error( buffer().a( " " ).strong( resumeBuildHint ).toString() ); } /** * A helper method to determine the value to resume the build with {@code -rf} taking into account the edge case * where multiple modules in the reactor have the same artifactId. * <p> * {@code -rf :artifactId} will pick up the first module which matches, but when multiple modules in the reactor * have the same artifactId, effective failed module might be later in build reactor. * This means that developer will either have to type groupId or wait for build execution of all modules which * were fine, but they are still before one which reported errors. * <p>Then the returned value is {@code groupId:artifactId} when there is a name clash and * {@code :artifactId} if there is no conflict. * This method is made package-private for testing purposes. * * @param mavenProjects Maven projects which are part of build execution. * @param firstFailedProject The first project which has failed. * @return Value for -rf flag to resume build exactly from place where it failed ({@code :artifactId} in general * and {@code groupId:artifactId} when there is a name clash). */ String getResumeFromSelector( List<MavenProject> mavenProjects, MavenProject firstFailedProject ) { boolean hasOverlappingArtifactId = mavenProjects.stream() .filter( project -> firstFailedProject.getArtifactId().equals( project.getArtifactId() ) ) .count() > 1; if ( hasOverlappingArtifactId ) { return firstFailedProject.getGroupId() + ":" + firstFailedProject.getArtifactId(); } return ":" + firstFailedProject.getArtifactId(); } private void logSummary( ExceptionSummary summary, Map<String, String> references, String indent, boolean showErrors ) { String referenceKey = ""; if ( StringUtils.isNotEmpty( summary.getReference() ) ) { referenceKey = references.get( summary.getReference() ); if ( referenceKey == null ) { referenceKey = "[Help " + ( references.size() + 1 ) + "]"; references.put( summary.getReference(), referenceKey ); } } String msg = summary.getMessage(); if ( StringUtils.isNotEmpty( referenceKey ) ) { if ( msg.indexOf( '\n' ) < 0 ) { msg += " -> " + buffer().strong( referenceKey ); } else { msg += "\n-> " + buffer().strong( referenceKey ); } } String[] lines = msg.split( "(\r\n)|(\r)|(\n)" ); String currentColor = ""; for ( int i = 0; i < lines.length; i++ ) { // add eventual current color inherited from previous line String line = currentColor + lines[i]; // look for last ANSI escape sequence to check if nextColor Matcher matcher = LAST_ANSI_SEQUENCE.matcher( line ); String nextColor = ""; if ( matcher.find() ) { nextColor = matcher.group( 1 ); if ( ANSI_RESET.equals( nextColor ) ) { // last ANSI escape code is reset: no next color nextColor = ""; } } // effective line, with indent and reset if end is colored line = indent + line + ( "".equals( nextColor ) ? "" : ANSI_RESET ); if ( ( i == lines.length - 1 ) && ( showErrors || ( summary.getException() instanceof InternalErrorException ) ) ) { slf4jLogger.error( line, summary.getException() ); } else { slf4jLogger.error( line ); } currentColor = nextColor; } indent += " "; for ( ExceptionSummary child : summary.getChildren() ) { logSummary( child, references, indent, showErrors ); } } private static final Pattern LAST_ANSI_SEQUENCE = Pattern.compile( "(\u001B\\[[;\\d]*[ -/]*[@-~])[^\u001B]*$" ); private static final String ANSI_RESET = "\u001B\u005Bm"; private void configure( CliRequest cliRequest ) throws Exception { // // This is not ideal but there are events specifically for configuration from the CLI which I don't // believe are really valid but there are ITs which assert the right events are published so this // needs to be supported so the EventSpyDispatcher needs to be put in the CliRequest so that // it can be accessed by configuration processors. // cliRequest.request.setEventSpyDispatcher( eventSpyDispatcher ); // // We expect at most 2 implementations to be available. The SettingsXmlConfigurationProcessor implementation // is always available in the core and likely always will be, but we may have another ConfigurationProcessor // present supplied by the user. The rule is that we only allow the execution of one ConfigurationProcessor. // If there is more than one then we execute the one supplied by the user, otherwise we execute the // the default SettingsXmlConfigurationProcessor. // int userSuppliedConfigurationProcessorCount = configurationProcessors.size() - 1; if ( userSuppliedConfigurationProcessorCount == 0 ) { // // Our settings.xml source is historically how we have configured Maven from the CLI so we are going to // have to honour its existence forever. So let's run it. // configurationProcessors.get( SettingsXmlConfigurationProcessor.HINT ).process( cliRequest ); } else if ( userSuppliedConfigurationProcessorCount == 1 ) { // // Run the user supplied ConfigurationProcessor // for ( Entry<String, ConfigurationProcessor> entry : configurationProcessors.entrySet() ) { String hint = entry.getKey(); if ( !hint.equals( SettingsXmlConfigurationProcessor.HINT ) ) { ConfigurationProcessor configurationProcessor = entry.getValue(); configurationProcessor.process( cliRequest ); } } } else if ( userSuppliedConfigurationProcessorCount > 1 ) { // // There are too many ConfigurationProcessors so we don't know which one to run so report the error. // StringBuilder sb = new StringBuilder( String.format( "%nThere can only be one user supplied ConfigurationProcessor, there are %s:%n%n", userSuppliedConfigurationProcessorCount ) ); for ( Entry<String, ConfigurationProcessor> entry : configurationProcessors.entrySet() ) { String hint = entry.getKey(); if ( !hint.equals( SettingsXmlConfigurationProcessor.HINT ) ) { ConfigurationProcessor configurationProcessor = entry.getValue(); sb.append( String.format( "%s%n", configurationProcessor.getClass().getName() ) ); } } throw new Exception( sb.toString() ); } } void toolchains( CliRequest cliRequest ) throws Exception { File userToolchainsFile; if ( cliRequest.commandLine.hasOption( CLIManager.ALTERNATE_USER_TOOLCHAINS ) ) { userToolchainsFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.ALTERNATE_USER_TOOLCHAINS ) ); userToolchainsFile = resolveFile( userToolchainsFile, cliRequest.workingDirectory ); if ( !userToolchainsFile.isFile() ) { throw new FileNotFoundException( "The specified user toolchains file does not exist: " + userToolchainsFile ); } } else { userToolchainsFile = DEFAULT_USER_TOOLCHAINS_FILE; } File globalToolchainsFile; if ( cliRequest.commandLine.hasOption( CLIManager.ALTERNATE_GLOBAL_TOOLCHAINS ) ) { globalToolchainsFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.ALTERNATE_GLOBAL_TOOLCHAINS ) ); globalToolchainsFile = resolveFile( globalToolchainsFile, cliRequest.workingDirectory ); if ( !globalToolchainsFile.isFile() ) { throw new FileNotFoundException( "The specified global toolchains file does not exist: " + globalToolchainsFile ); } } else { globalToolchainsFile = DEFAULT_GLOBAL_TOOLCHAINS_FILE; } cliRequest.request.setGlobalToolchainsFile( globalToolchainsFile ); cliRequest.request.setUserToolchainsFile( userToolchainsFile ); DefaultToolchainsBuildingRequest toolchainsRequest = new DefaultToolchainsBuildingRequest(); if ( globalToolchainsFile.isFile() ) { toolchainsRequest.setGlobalToolchainsSource( new FileSource( globalToolchainsFile ) ); } if ( userToolchainsFile.isFile() ) { toolchainsRequest.setUserToolchainsSource( new FileSource( userToolchainsFile ) ); } eventSpyDispatcher.onEvent( toolchainsRequest ); slf4jLogger.debug( "Reading global toolchains from '{}'", getLocation( toolchainsRequest.getGlobalToolchainsSource(), globalToolchainsFile ) ); slf4jLogger.debug( "Reading user toolchains from '{}'", getLocation( toolchainsRequest.getUserToolchainsSource(), userToolchainsFile ) ); ToolchainsBuildingResult toolchainsResult = toolchainsBuilder.build( toolchainsRequest ); eventSpyDispatcher.onEvent( toolchainsResult ); executionRequestPopulator.populateFromToolchains( cliRequest.request, toolchainsResult.getEffectiveToolchains() ); if ( !toolchainsResult.getProblems().isEmpty() && slf4jLogger.isWarnEnabled() ) { slf4jLogger.warn( "" ); slf4jLogger.warn( "Some problems were encountered while building the effective toolchains" ); for ( Problem problem : toolchainsResult.getProblems() ) { slf4jLogger.warn( "{} @ {}", problem.getMessage(), problem.getLocation() ); } slf4jLogger.warn( "" ); } } private Object getLocation( Source source, File defaultLocation ) { if ( source != null ) { return source.getLocation(); } return defaultLocation; } protected MavenExecutionRequest populateRequest( CliRequest cliRequest ) { return populateRequest( cliRequest, cliRequest.request ); } private MavenExecutionRequest populateRequest( CliRequest cliRequest, MavenExecutionRequest request ) { slf4jLoggerFactory = LoggerFactory.getILoggerFactory(); CommandLine commandLine = cliRequest.commandLine; String workingDirectory = cliRequest.workingDirectory; boolean quiet = cliRequest.quiet; request.setShowErrors( cliRequest.showErrors ); // default: false File baseDirectory = new File( workingDirectory, "" ).getAbsoluteFile(); disableOnPresentOption( commandLine, CLIManager.BATCH_MODE, request::setInteractiveMode ); enableOnPresentOption( commandLine, CLIManager.SUPRESS_SNAPSHOT_UPDATES, request::setNoSnapshotUpdates ); request.setGoals( commandLine.getArgList() ); request.setReactorFailureBehavior( determineReactorFailureBehaviour ( commandLine ) ); disableOnPresentOption( commandLine, CLIManager.NON_RECURSIVE, request::setRecursive ); enableOnPresentOption( commandLine, CLIManager.OFFLINE, request::setOffline ); enableOnPresentOption( commandLine, CLIManager.UPDATE_SNAPSHOTS, request::setUpdateSnapshots ); request.setGlobalChecksumPolicy( determineGlobalCheckPolicy( commandLine ) ); request.setBaseDirectory( baseDirectory ); request.setSystemProperties( cliRequest.systemProperties ); request.setUserProperties( cliRequest.userProperties ); request.setMultiModuleProjectDirectory( cliRequest.multiModuleProjectDirectory ); request.setPom( determinePom( commandLine, workingDirectory, baseDirectory ) ); request.setTransferListener( determineTransferListener( quiet, commandLine, request ) ); request.setExecutionListener( determineExecutionListener() ); if ( ( request.getPom() != null ) && ( request.getPom().getParentFile() != null ) ) { request.setBaseDirectory( request.getPom().getParentFile() ); } request.setResumeFrom( commandLine.getOptionValue( CLIManager.RESUME_FROM ) ); enableOnPresentOption( commandLine, CLIManager.RESUME, request::setResume ); request.setMakeBehavior( determineMakeBehavior( commandLine ) ); request.setCacheNotFound( true ); request.setCacheTransferError( false ); final ProjectActivation projectActivation = determineProjectActivation( commandLine ); request.setSelectedProjects( projectActivation.activeProjects ); request.setExcludedProjects( projectActivation.inactiveProjects ); performProfileActivation( commandLine, request.getProfileActivation() ); final String localRepositoryPath = determineLocalRepositoryPath( request ); if ( localRepositoryPath != null ) { request.setLocalRepositoryPath( localRepositoryPath ); } // // Builder, concurrency and parallelism // // We preserve the existing methods for builder selection which is to look for various inputs in the threading // configuration. We don't have an easy way to allow a pluggable builder to provide its own configuration // parameters but this is sufficient for now. Ultimately we want components like Builders to provide a way to // extend the command line to accept its own configuration parameters. // final String threadConfiguration = commandLine.getOptionValue( CLIManager.THREADS ); if ( threadConfiguration != null ) { // // Default to the standard multithreaded builder // request.setBuilderId( "multithreaded" ); if ( threadConfiguration.contains( "C" ) ) { request.setDegreeOfConcurrency( calculateDegreeOfConcurrencyWithCoreMultiplier( threadConfiguration ) ); } else { request.setDegreeOfConcurrency( Integer.parseInt( threadConfiguration ) ); } } // // Allow the builder to be overridden by the user if requested. The builders are now pluggable. // request.setBuilderId( commandLine.getOptionValue( CLIManager.BUILDER, request.getBuilderId() ) ); return request; } private String determineLocalRepositoryPath( final MavenExecutionRequest request ) { String userDefinedLocalRepo = request.getUserProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY ); if ( userDefinedLocalRepo != null ) { return userDefinedLocalRepo; } return request.getSystemProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY ); } private File determinePom( final CommandLine commandLine, final String workingDirectory, final File baseDirectory ) { String alternatePomFile = null; if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) { alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); } if ( alternatePomFile != null ) { File pom = resolveFile( new File( alternatePomFile ), workingDirectory ); if ( pom.isDirectory() ) { pom = new File( pom, "pom.xml" ); } return pom; } else if ( modelProcessor != null ) { File pom = modelProcessor.locatePom( baseDirectory ); if ( pom.isFile() ) { return pom; } } return null; } // Visible for testing static ProjectActivation determineProjectActivation ( final CommandLine commandLine ) { final ProjectActivation projectActivation = new ProjectActivation(); if ( commandLine.hasOption( CLIManager.PROJECT_LIST ) ) { String[] projectOptionValues = commandLine.getOptionValues( CLIManager.PROJECT_LIST ); if ( projectOptionValues != null ) { for ( String projectOptionValue : projectOptionValues ) { StringTokenizer projectTokens = new StringTokenizer( projectOptionValue, "," ); while ( projectTokens.hasMoreTokens() ) { String projectAction = projectTokens.nextToken().trim(); if ( projectAction.startsWith( "-" ) || projectAction.startsWith( "!" ) ) { projectActivation.deactivate( projectAction.substring( 1 ) ); } else if ( projectAction.startsWith( "+" ) ) { projectActivation.activate( projectAction.substring( 1 ) ); } else { projectActivation.activate( projectAction ); } } } } } return projectActivation; } // Visible for testing static void performProfileActivation( final CommandLine commandLine, final ProfileActivation profileActivation ) { if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { final String[] optionValues = commandLine.getOptionValues( CLIManager.ACTIVATE_PROFILES ); if ( optionValues == null || optionValues.length == 0 ) { return; } for ( final String optionValue : optionValues ) { for ( String token : optionValue.split( "," ) ) { String profileId = token.trim(); boolean active = true; if ( profileId.charAt( 0 ) == '-' || profileId.charAt( 0 ) == '!' ) { active = false; profileId = profileId.substring( 1 ); } else if ( token.charAt( 0 ) == '+' ) { profileId = profileId.substring( 1 ); } boolean optional = profileId.charAt( 0 ) == '?'; profileId = profileId.substring( optional ? 1 : 0 ); profileActivation.addProfileActivation( profileId, active, optional ); } } } } private ExecutionListener determineExecutionListener() { ExecutionListener executionListener = new ExecutionEventLogger(); if ( eventSpyDispatcher != null ) { return eventSpyDispatcher.chainListener( executionListener ); } else { return executionListener; } } private String determineReactorFailureBehaviour( final CommandLine commandLine ) { if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) { return MavenExecutionRequest.REACTOR_FAIL_FAST; } else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) { return MavenExecutionRequest.REACTOR_FAIL_AT_END; } else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) { return MavenExecutionRequest.REACTOR_FAIL_NEVER; } else { // this is the default behavior. return MavenExecutionRequest.REACTOR_FAIL_FAST; } } private TransferListener determineTransferListener( final boolean quiet, final CommandLine commandLine, final MavenExecutionRequest request ) { if ( quiet || commandLine.hasOption( CLIManager.NO_TRANSFER_PROGRESS ) ) { return new QuietMavenTransferListener(); } else if ( request.isInteractiveMode() && !commandLine.hasOption( CLIManager.LOG_FILE ) ) { // // If we're logging to a file then we don't want the console transfer listener as it will spew // download progress all over the place // return getConsoleTransferListener( commandLine.hasOption( CLIManager.DEBUG ) ); } else { // default: batch mode which goes along with interactive return getBatchTransferListener(); } } private String determineMakeBehavior( final CommandLine cl ) { if ( cl.hasOption( CLIManager.ALSO_MAKE ) && !cl.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) { return MavenExecutionRequest.REACTOR_MAKE_UPSTREAM; } else if ( !cl.hasOption( CLIManager.ALSO_MAKE ) && cl.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) { return MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM; } else if ( cl.hasOption( CLIManager.ALSO_MAKE ) && cl.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) { return MavenExecutionRequest.REACTOR_MAKE_BOTH; } else { return null; } } private String determineGlobalCheckPolicy( final CommandLine commandLine ) { if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) { return MavenExecutionRequest.CHECKSUM_POLICY_FAIL; } else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) { return MavenExecutionRequest.CHECKSUM_POLICY_WARN; } else { return null; } } private void disableOnPresentOption( final CommandLine commandLine, final String option, final Consumer<Boolean> setting ) { if ( commandLine.hasOption( option ) ) { setting.accept( false ); } } private void disableOnPresentOption( final CommandLine commandLine, final char option, final Consumer<Boolean> setting ) { disableOnPresentOption( commandLine, String.valueOf( option ), setting ); } private void enableOnPresentOption( final CommandLine commandLine, final String option, final Consumer<Boolean> setting ) { if ( commandLine.hasOption( option ) ) { setting.accept( true ); } } private void enableOnPresentOption( final CommandLine commandLine, final char option, final Consumer<Boolean> setting ) { enableOnPresentOption( commandLine, String.valueOf( option ), setting ); } private void enableOnAbsentOption( final CommandLine commandLine, final char option, final Consumer<Boolean> setting ) { if ( !commandLine.hasOption( option ) ) { setting.accept( true ); } } int calculateDegreeOfConcurrencyWithCoreMultiplier( String threadConfiguration ) { int procs = Runtime.getRuntime().availableProcessors(); return (int) ( Float.parseFloat( threadConfiguration.replace( "C", "" ) ) * procs ); } // ---------------------------------------------------------------------- // System properties handling // ---------------------------------------------------------------------- static void populateProperties( CommandLine commandLine, Properties systemProperties, Properties userProperties ) { EnvironmentUtils.addEnvVars( systemProperties ); // ---------------------------------------------------------------------- // Options that are set on the command line become system properties // and therefore are set in the session properties. System properties // are most dominant. // ---------------------------------------------------------------------- if ( commandLine.hasOption( CLIManager.SET_SYSTEM_PROPERTY ) ) { String[] defStrs = commandLine.getOptionValues( CLIManager.SET_SYSTEM_PROPERTY ); if ( defStrs != null ) { for ( String defStr : defStrs ) { setCliProperty( defStr, userProperties ); } } } SystemProperties.addSystemProperties( systemProperties ); // ---------------------------------------------------------------------- // Properties containing info about the currently running version of Maven // These override any corresponding properties set on the command line // ---------------------------------------------------------------------- Properties buildProperties = CLIReportingUtils.getBuildProperties(); String mavenVersion = buildProperties.getProperty( CLIReportingUtils.BUILD_VERSION_PROPERTY ); systemProperties.setProperty( "maven.version", mavenVersion ); String mavenBuildVersion = CLIReportingUtils.createMavenVersionString( buildProperties ); systemProperties.setProperty( "maven.build.version", mavenBuildVersion ); } private static void setCliProperty( String property, Properties properties ) { String name; String value; int i = property.indexOf( '=' ); if ( i <= 0 ) { name = property.trim(); value = "true"; } else { name = property.substring( 0, i ).trim(); value = property.substring( i + 1 ); } properties.setProperty( name, value ); // ---------------------------------------------------------------------- // I'm leaving the setting of system properties here as not to break // the SystemPropertyProfileActivator. This won't harm embedding. jvz. // ---------------------------------------------------------------------- System.setProperty( name, value ); } static class ExitException extends Exception { int exitCode; ExitException( int exitCode ) { this.exitCode = exitCode; } } // // Customizations available via the CLI // protected TransferListener getConsoleTransferListener( boolean printResourceNames ) { return new ConsoleMavenTransferListener( System.out, printResourceNames ); } protected TransferListener getBatchTransferListener() { return new Slf4jMavenTransferListener(); } protected void customizeContainer( PlexusContainer container ) { } protected ModelProcessor createModelProcessor( PlexusContainer container ) throws ComponentLookupException { return container.lookup( ModelProcessor.class ); } // Visible for testing static class ProjectActivation { List<String> activeProjects; List<String> inactiveProjects; public void deactivate( final String project ) { if ( inactiveProjects == null ) { inactiveProjects = new ArrayList<>(); } inactiveProjects.add( project ); } public void activate( final String project ) { if ( activeProjects == null ) { activeProjects = new ArrayList<>(); } activeProjects.add( project ); } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.android.datatransport.runtime.scheduling; import com.google.android.datatransport.runtime.EventInternal; import com.google.android.datatransport.runtime.TransportContext; import com.google.android.datatransport.runtime.TransportRuntime; import com.google.android.datatransport.runtime.backends.BackendRegistry; import com.google.android.datatransport.runtime.backends.BackendRequest; import com.google.android.datatransport.runtime.backends.TransportBackend; import java.util.Collections; import java.util.concurrent.Executor; import java.util.logging.Logger; import javax.inject.Inject; /** * Simple scheduler implementation that tries to transmit event immediately. * * <p>It does not respect QoS of the event, network conditions, backend wait time millis. */ public class ImmediateScheduler implements Scheduler { private static final Logger LOGGER = Logger.getLogger(TransportRuntime.class.getName()); private final Executor executor; private final BackendRegistry backendRegistry; @Inject public ImmediateScheduler(Executor executor, BackendRegistry backendRegistry) { this.executor = executor; this.backendRegistry = backendRegistry; } @Override public void schedule(TransportContext transportContext, EventInternal event) { executor.execute( () -> { TransportBackend backend = backendRegistry.get(transportContext.getBackendName()); if (backend == null) { LOGGER.warning( String.format( "Transport backend '%s' is not registered", transportContext.getBackendName())); return; } backend.send(BackendRequest.create(Collections.singleton(backend.decorate(event)))); }); } }
/* * Copyright 2012-2013 eBay Software Foundation and ios-driver committers * * 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.uiautomation.ios.client.uiamodels.impl; import com.google.common.collect.ImmutableMap; import org.openqa.selenium.Alert; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.security.Credentials; import org.uiautomation.ios.UIAModels.UIAAlert; import org.uiautomation.ios.UIAModels.UIAButton; import org.uiautomation.ios.UIAModels.UIAElement; import org.uiautomation.ios.UIAModels.UIAStaticText; import org.uiautomation.ios.UIAModels.predicate.TypeCriteria; import org.uiautomation.ios.communication.WebDriverLikeCommand; import org.uiautomation.ios.communication.WebDriverLikeRequest; import java.util.List; public class RemoteUIAAlert extends RemoteUIAElement implements UIAAlert, Alert { public RemoteUIAAlert(RemoteWebDriver driver, String reference) { super(driver, reference); } @Override public UIAButton getCancelButton() { WebDriverLikeRequest request = buildRequest(WebDriverLikeCommand.ALERT_CANCEL_BUTTON); return commandExecutor.execute(request); } @Override public UIAButton getDefaultButton() { WebDriverLikeRequest request = buildRequest(WebDriverLikeCommand.ALERT_DEFAULT_BUTTON); UIAButton butt = commandExecutor.execute(request); return butt; } @Override public void dismiss() { WebDriverLikeRequest request = buildRequest(WebDriverLikeCommand.DISMISS_ALERT); commandExecutor.execute(request); } @Override public void accept() { WebDriverLikeRequest request = buildRequest(WebDriverLikeCommand.ACCEPT_ALERT); commandExecutor.execute(request); } @Override public void sendKeys(String keysToSend) { WebDriverLikeRequest request = buildRequest(WebDriverLikeCommand.SET_ALERT_TEXT, ImmutableMap.of("text", keysToSend)); commandExecutor.execute(request); } @Override public void setCredentials(Credentials credentials) { // TODO freynaud throw new RuntimeException("NI"); } @Override public void authenticateUsing(Credentials credentials) { //To change body of implemented methods use File | Settings | File Templates. } @Override public String getText() { WebDriverLikeRequest request = buildRequest(WebDriverLikeCommand.GET_ALERT_TEXT); return commandExecutor.execute(request); } }
package com.skytala.eCommerce.domain.marketing.relations.trackingCode.model; import java.util.Map; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Map; import java.io.Serializable; import com.skytala.eCommerce.domain.marketing.relations.trackingCode.mapper.TrackingCodeMapper; public class TrackingCode implements Serializable{ private static final long serialVersionUID = 1L; private String trackingCodeId; private String trackingCodeTypeId; private String marketingCampaignId; private String redirectUrl; private String overrideLogo; private String overrideCss; private String prodCatalogId; private String comments; private String description; private Long trackableLifetime; private Long billableLifetime; private Timestamp fromDate; private Timestamp thruDate; private String groupId; private String subgroupId; private Timestamp createdDate; private String createdByUserLogin; private Timestamp lastModifiedDate; private String lastModifiedByUserLogin; public String getTrackingCodeId() { return trackingCodeId; } public void setTrackingCodeId(String trackingCodeId) { this.trackingCodeId = trackingCodeId; } public String getTrackingCodeTypeId() { return trackingCodeTypeId; } public void setTrackingCodeTypeId(String trackingCodeTypeId) { this.trackingCodeTypeId = trackingCodeTypeId; } public String getMarketingCampaignId() { return marketingCampaignId; } public void setMarketingCampaignId(String marketingCampaignId) { this.marketingCampaignId = marketingCampaignId; } public String getRedirectUrl() { return redirectUrl; } public void setRedirectUrl(String redirectUrl) { this.redirectUrl = redirectUrl; } public String getOverrideLogo() { return overrideLogo; } public void setOverrideLogo(String overrideLogo) { this.overrideLogo = overrideLogo; } public String getOverrideCss() { return overrideCss; } public void setOverrideCss(String overrideCss) { this.overrideCss = overrideCss; } public String getProdCatalogId() { return prodCatalogId; } public void setProdCatalogId(String prodCatalogId) { this.prodCatalogId = prodCatalogId; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getTrackableLifetime() { return trackableLifetime; } public void setTrackableLifetime(Long trackableLifetime) { this.trackableLifetime = trackableLifetime; } public Long getBillableLifetime() { return billableLifetime; } public void setBillableLifetime(Long billableLifetime) { this.billableLifetime = billableLifetime; } public Timestamp getFromDate() { return fromDate; } public void setFromDate(Timestamp fromDate) { this.fromDate = fromDate; } public Timestamp getThruDate() { return thruDate; } public void setThruDate(Timestamp thruDate) { this.thruDate = thruDate; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getSubgroupId() { return subgroupId; } public void setSubgroupId(String subgroupId) { this.subgroupId = subgroupId; } public Timestamp getCreatedDate() { return createdDate; } public void setCreatedDate(Timestamp createdDate) { this.createdDate = createdDate; } public String getCreatedByUserLogin() { return createdByUserLogin; } public void setCreatedByUserLogin(String createdByUserLogin) { this.createdByUserLogin = createdByUserLogin; } public Timestamp getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Timestamp lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public String getLastModifiedByUserLogin() { return lastModifiedByUserLogin; } public void setLastModifiedByUserLogin(String lastModifiedByUserLogin) { this.lastModifiedByUserLogin = lastModifiedByUserLogin; } public Map<String, Object> mapAttributeField() { return TrackingCodeMapper.map(this); } }
package de.vogella.rcp.jfreechart.barchart; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { layout.setEditorAreaVisible(false); layout.setFixed(true); } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package org.apache.kafka.common.record; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.errors.CorruptRecordException; import org.apache.kafka.common.utils.AbstractIterator; import org.apache.kafka.common.utils.Utils; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.Iterator; /** * An iterator which handles both the shallow and deep iteration of record sets. */ public class RecordsIterator extends AbstractIterator<LogEntry> { private final boolean shallow; private final boolean ensureMatchingMagic; private final int maxRecordSize; private final ShallowRecordsIterator<?> shallowIter; private DeepRecordsIterator innerIter; public RecordsIterator(LogInputStream<?> logInputStream, boolean shallow, boolean ensureMatchingMagic, int maxRecordSize) { this.shallowIter = new ShallowRecordsIterator<>(logInputStream); this.shallow = shallow; this.ensureMatchingMagic = ensureMatchingMagic; this.maxRecordSize = maxRecordSize; } /** * Get a shallow iterator over the given input stream. * @param logInputStream The log input stream to read the entries from * @param <T> The type of the log entry * @return The shallow iterator. */ public static <T extends LogEntry> Iterator<T> shallowIterator(LogInputStream<T> logInputStream) { return new ShallowRecordsIterator<>(logInputStream); } @Override protected LogEntry makeNext() { if (innerDone()) { if (!shallowIter.hasNext()) return allDone(); LogEntry entry = shallowIter.next(); // decide whether to go shallow or deep iteration if it is compressed if (shallow || !entry.isCompressed()) { return entry; } else { // init the inner iterator with the value payload of the message, // which will de-compress the payload to a set of messages; // since we assume nested compression is not allowed, the deep iterator // would not try to further decompress underlying messages // There will be at least one element in the inner iterator, so we don't // need to call hasNext() here. innerIter = new DeepRecordsIterator(entry, ensureMatchingMagic, maxRecordSize); return innerIter.next(); } } else { return innerIter.next(); } } private boolean innerDone() { return innerIter == null || !innerIter.hasNext(); } private static final class DataLogInputStream implements LogInputStream<LogEntry> { private final DataInputStream stream; protected final int maxMessageSize; DataLogInputStream(DataInputStream stream, int maxMessageSize) { this.stream = stream; this.maxMessageSize = maxMessageSize; } public LogEntry nextEntry() throws IOException { try { long offset = stream.readLong(); int size = stream.readInt(); if (size < Record.RECORD_OVERHEAD_V0) throw new CorruptRecordException(String.format("Record size is less than the minimum record overhead (%d)", Record.RECORD_OVERHEAD_V0)); if (size > maxMessageSize) throw new CorruptRecordException(String.format("Record size exceeds the largest allowable message size (%d).", maxMessageSize)); byte[] recordBuffer = new byte[size]; stream.readFully(recordBuffer, 0, size); ByteBuffer buf = ByteBuffer.wrap(recordBuffer); return LogEntry.create(offset, new Record(buf)); } catch (EOFException e) { return null; } } } private static class ShallowRecordsIterator<T extends LogEntry> extends AbstractIterator<T> { private final LogInputStream<T> logStream; public ShallowRecordsIterator(LogInputStream<T> logStream) { this.logStream = logStream; } @Override protected T makeNext() { try { T entry = logStream.nextEntry(); if (entry == null) return allDone(); return entry; } catch (IOException e) { throw new KafkaException(e); } } } public static class DeepRecordsIterator extends AbstractIterator<LogEntry> { private final ArrayDeque<LogEntry> logEntries; private final long absoluteBaseOffset; private final byte wrapperMagic; public DeepRecordsIterator(LogEntry wrapperEntry, boolean ensureMatchingMagic, int maxMessageSize) { Record wrapperRecord = wrapperEntry.record(); this.wrapperMagic = wrapperRecord.magic(); CompressionType compressionType = wrapperRecord.compressionType(); ByteBuffer buffer = wrapperRecord.value(); DataInputStream stream = MemoryRecordsBuilder.wrapForInput(new ByteBufferInputStream(buffer), compressionType, wrapperRecord.magic()); LogInputStream logStream = new DataLogInputStream(stream, maxMessageSize); long wrapperRecordOffset = wrapperEntry.offset(); long wrapperRecordTimestamp = wrapperRecord.timestamp(); this.logEntries = new ArrayDeque<>(); // If relative offset is used, we need to decompress the entire message first to compute // the absolute offset. For simplicity and because it's a format that is on its way out, we // do the same for message format version 0 try { while (true) { LogEntry logEntry = logStream.nextEntry(); if (logEntry == null) break; Record record = logEntry.record(); byte magic = record.magic(); if (ensureMatchingMagic && magic != wrapperMagic) throw new InvalidRecordException("Compressed message magic does not match wrapper magic"); if (magic > Record.MAGIC_VALUE_V0) { Record recordWithTimestamp = new Record( record.buffer(), wrapperRecordTimestamp, wrapperRecord.timestampType() ); logEntry = LogEntry.create(logEntry.offset(), recordWithTimestamp); } logEntries.addLast(logEntry); } if (wrapperMagic > Record.MAGIC_VALUE_V0) this.absoluteBaseOffset = wrapperRecordOffset - logEntries.getLast().offset(); else this.absoluteBaseOffset = -1; } catch (IOException e) { throw new KafkaException(e); } finally { Utils.closeQuietly(stream, "records iterator stream"); } } @Override protected LogEntry makeNext() { if (logEntries.isEmpty()) return allDone(); LogEntry entry = logEntries.remove(); // Convert offset to absolute offset if needed. if (absoluteBaseOffset >= 0) { long absoluteOffset = absoluteBaseOffset + entry.offset(); entry = LogEntry.create(absoluteOffset, entry.record()); } if (entry.isCompressed()) throw new InvalidRecordException("Inner messages must not be compressed"); return entry; } } }
/* * Copyright 2016 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.encryptionsdk.internal; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; public class TestIOUtils { private static final SecureRandom rng_ = new SecureRandom(); public static byte[] generateRandomPlaintext(final int size) { return RandomBytesGenerator.generate(size); } /** * Generates and returns a string of the given {@code length}. * <p> * This function can be replaced by the RandomStringUtil class * from Apache Commons. * <p> * This method re-implemented here to keep this library's dependency * to a minimum which would reduce friction when it's consumed * by other packages. */ public static String generateRandomString(final int size) { StringBuilder sb = new StringBuilder(); Random rand = new Random(); for (int i = 0; i < size; i++) { int c = rand.nextInt(Byte.MAX_VALUE); c = c == 0 ? (c + 1) : c; sb.append((char)c); } return sb.toString(); } public static byte[] computeFileDigest(final String fileName) throws IOException { try { final FileInputStream fis = new FileInputStream(fileName); final MessageDigest md = MessageDigest.getInstance("SHA-256"); final DigestInputStream dis = new DigestInputStream(fis, md); final int readLen = 128; final byte[] readBytes = new byte[readLen]; while (dis.read(readBytes) != -1) { } dis.close(); return md.digest(); } catch (NoSuchAlgorithmException e) { // shouldn't get here since we hardcode the algorithm. } return null; } public static byte[] getSha256Hash(final byte[] input) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { // should never get here. } return md.digest(input); } public static void generateFile(final String fileName, final long fileSize) throws IOException { final FileOutputStream fs = new FileOutputStream(fileName); final byte[] fileBytes = new byte[(int) fileSize]; rng_.nextBytes(fileBytes); fs.write(fileBytes); fs.close(); } public static void copyInStreamToOutStream(final InputStream inStream, final OutputStream outStream, final int readLen) throws IOException { final byte[] readBuffer = new byte[readLen]; int actualRead = 0; while (actualRead >= 0) { outStream.write(readBuffer, 0, actualRead); actualRead = inStream.read(readBuffer); } inStream.close(); outStream.close(); } public static void deleteDir(final File filePath) { if (filePath.exists()) { File[] files = filePath.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { files[i].delete(); } else { deleteDir(files[i]); } } } filePath.delete(); } public static void copyInStreamToOutStream(final InputStream inStream, final OutputStream outStream) throws IOException { final int readLen = 1024; // 1KB copyInStreamToOutStream(inStream, outStream, readLen); } }
/* * 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.ec2.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Details about the Dedicated Host Reservation and associated Dedicated Hosts. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/HostReservation" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class HostReservation implements Serializable, Cloneable { /** * <p> * The number of Dedicated Hosts the reservation is associated with. * </p> */ private Integer count; /** * <p> * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At this * time, the only supported currency is <code>USD</code>. * </p> */ private String currencyCode; /** * <p> * The length of the reservation's term, specified in seconds. Can be <code>31536000 (1 year)</code> | * <code>94608000 (3 years)</code>. * </p> */ private Integer duration; /** * <p> * The date and time that the reservation ends. * </p> */ private java.util.Date end; /** * <p> * The IDs of the Dedicated Hosts associated with the reservation. * </p> */ private com.amazonaws.internal.SdkInternalList<String> hostIdSet; /** * <p> * The ID of the reservation that specifies the associated Dedicated Hosts. * </p> */ private String hostReservationId; /** * <p> * The hourly price of the reservation. * </p> */ private String hourlyPrice; /** * <p> * The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be the same * in order for it to benefit from the reservation. * </p> */ private String instanceFamily; /** * <p> * The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with it. * </p> */ private String offeringId; /** * <p> * The payment option selected for this reservation. * </p> */ private String paymentOption; /** * <p> * The date and time that the reservation started. * </p> */ private java.util.Date start; /** * <p> * The state of the reservation. * </p> */ private String state; /** * <p> * The upfront price of the reservation. * </p> */ private String upfrontPrice; /** * <p> * Any tags assigned to the Dedicated Host Reservation. * </p> */ private com.amazonaws.internal.SdkInternalList<Tag> tags; /** * <p> * The number of Dedicated Hosts the reservation is associated with. * </p> * * @param count * The number of Dedicated Hosts the reservation is associated with. */ public void setCount(Integer count) { this.count = count; } /** * <p> * The number of Dedicated Hosts the reservation is associated with. * </p> * * @return The number of Dedicated Hosts the reservation is associated with. */ public Integer getCount() { return this.count; } /** * <p> * The number of Dedicated Hosts the reservation is associated with. * </p> * * @param count * The number of Dedicated Hosts the reservation is associated with. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withCount(Integer count) { setCount(count); return this; } /** * <p> * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At this * time, the only supported currency is <code>USD</code>. * </p> * * @param currencyCode * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At * this time, the only supported currency is <code>USD</code>. * @see CurrencyCodeValues */ public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } /** * <p> * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At this * time, the only supported currency is <code>USD</code>. * </p> * * @return The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. * At this time, the only supported currency is <code>USD</code>. * @see CurrencyCodeValues */ public String getCurrencyCode() { return this.currencyCode; } /** * <p> * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At this * time, the only supported currency is <code>USD</code>. * </p> * * @param currencyCode * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At * this time, the only supported currency is <code>USD</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see CurrencyCodeValues */ public HostReservation withCurrencyCode(String currencyCode) { setCurrencyCode(currencyCode); return this; } /** * <p> * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At this * time, the only supported currency is <code>USD</code>. * </p> * * @param currencyCode * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At * this time, the only supported currency is <code>USD</code>. * @see CurrencyCodeValues */ public void setCurrencyCode(CurrencyCodeValues currencyCode) { withCurrencyCode(currencyCode); } /** * <p> * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At this * time, the only supported currency is <code>USD</code>. * </p> * * @param currencyCode * The currency in which the <code>upfrontPrice</code> and <code>hourlyPrice</code> amounts are specified. At * this time, the only supported currency is <code>USD</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see CurrencyCodeValues */ public HostReservation withCurrencyCode(CurrencyCodeValues currencyCode) { this.currencyCode = currencyCode.toString(); return this; } /** * <p> * The length of the reservation's term, specified in seconds. Can be <code>31536000 (1 year)</code> | * <code>94608000 (3 years)</code>. * </p> * * @param duration * The length of the reservation's term, specified in seconds. Can be <code>31536000 (1 year)</code> | * <code>94608000 (3 years)</code>. */ public void setDuration(Integer duration) { this.duration = duration; } /** * <p> * The length of the reservation's term, specified in seconds. Can be <code>31536000 (1 year)</code> | * <code>94608000 (3 years)</code>. * </p> * * @return The length of the reservation's term, specified in seconds. Can be <code>31536000 (1 year)</code> | * <code>94608000 (3 years)</code>. */ public Integer getDuration() { return this.duration; } /** * <p> * The length of the reservation's term, specified in seconds. Can be <code>31536000 (1 year)</code> | * <code>94608000 (3 years)</code>. * </p> * * @param duration * The length of the reservation's term, specified in seconds. Can be <code>31536000 (1 year)</code> | * <code>94608000 (3 years)</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withDuration(Integer duration) { setDuration(duration); return this; } /** * <p> * The date and time that the reservation ends. * </p> * * @param end * The date and time that the reservation ends. */ public void setEnd(java.util.Date end) { this.end = end; } /** * <p> * The date and time that the reservation ends. * </p> * * @return The date and time that the reservation ends. */ public java.util.Date getEnd() { return this.end; } /** * <p> * The date and time that the reservation ends. * </p> * * @param end * The date and time that the reservation ends. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withEnd(java.util.Date end) { setEnd(end); return this; } /** * <p> * The IDs of the Dedicated Hosts associated with the reservation. * </p> * * @return The IDs of the Dedicated Hosts associated with the reservation. */ public java.util.List<String> getHostIdSet() { if (hostIdSet == null) { hostIdSet = new com.amazonaws.internal.SdkInternalList<String>(); } return hostIdSet; } /** * <p> * The IDs of the Dedicated Hosts associated with the reservation. * </p> * * @param hostIdSet * The IDs of the Dedicated Hosts associated with the reservation. */ public void setHostIdSet(java.util.Collection<String> hostIdSet) { if (hostIdSet == null) { this.hostIdSet = null; return; } this.hostIdSet = new com.amazonaws.internal.SdkInternalList<String>(hostIdSet); } /** * <p> * The IDs of the Dedicated Hosts associated with the reservation. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setHostIdSet(java.util.Collection)} or {@link #withHostIdSet(java.util.Collection)} if you want to * override the existing values. * </p> * * @param hostIdSet * The IDs of the Dedicated Hosts associated with the reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withHostIdSet(String... hostIdSet) { if (this.hostIdSet == null) { setHostIdSet(new com.amazonaws.internal.SdkInternalList<String>(hostIdSet.length)); } for (String ele : hostIdSet) { this.hostIdSet.add(ele); } return this; } /** * <p> * The IDs of the Dedicated Hosts associated with the reservation. * </p> * * @param hostIdSet * The IDs of the Dedicated Hosts associated with the reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withHostIdSet(java.util.Collection<String> hostIdSet) { setHostIdSet(hostIdSet); return this; } /** * <p> * The ID of the reservation that specifies the associated Dedicated Hosts. * </p> * * @param hostReservationId * The ID of the reservation that specifies the associated Dedicated Hosts. */ public void setHostReservationId(String hostReservationId) { this.hostReservationId = hostReservationId; } /** * <p> * The ID of the reservation that specifies the associated Dedicated Hosts. * </p> * * @return The ID of the reservation that specifies the associated Dedicated Hosts. */ public String getHostReservationId() { return this.hostReservationId; } /** * <p> * The ID of the reservation that specifies the associated Dedicated Hosts. * </p> * * @param hostReservationId * The ID of the reservation that specifies the associated Dedicated Hosts. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withHostReservationId(String hostReservationId) { setHostReservationId(hostReservationId); return this; } /** * <p> * The hourly price of the reservation. * </p> * * @param hourlyPrice * The hourly price of the reservation. */ public void setHourlyPrice(String hourlyPrice) { this.hourlyPrice = hourlyPrice; } /** * <p> * The hourly price of the reservation. * </p> * * @return The hourly price of the reservation. */ public String getHourlyPrice() { return this.hourlyPrice; } /** * <p> * The hourly price of the reservation. * </p> * * @param hourlyPrice * The hourly price of the reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withHourlyPrice(String hourlyPrice) { setHourlyPrice(hourlyPrice); return this; } /** * <p> * The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be the same * in order for it to benefit from the reservation. * </p> * * @param instanceFamily * The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be * the same in order for it to benefit from the reservation. */ public void setInstanceFamily(String instanceFamily) { this.instanceFamily = instanceFamily; } /** * <p> * The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be the same * in order for it to benefit from the reservation. * </p> * * @return The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be * the same in order for it to benefit from the reservation. */ public String getInstanceFamily() { return this.instanceFamily; } /** * <p> * The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be the same * in order for it to benefit from the reservation. * </p> * * @param instanceFamily * The instance family of the Dedicated Host Reservation. The instance family on the Dedicated Host must be * the same in order for it to benefit from the reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withInstanceFamily(String instanceFamily) { setInstanceFamily(instanceFamily); return this; } /** * <p> * The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with it. * </p> * * @param offeringId * The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with * it. */ public void setOfferingId(String offeringId) { this.offeringId = offeringId; } /** * <p> * The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with it. * </p> * * @return The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with * it. */ public String getOfferingId() { return this.offeringId; } /** * <p> * The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with it. * </p> * * @param offeringId * The ID of the reservation. This remains the same regardless of which Dedicated Hosts are associated with * it. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withOfferingId(String offeringId) { setOfferingId(offeringId); return this; } /** * <p> * The payment option selected for this reservation. * </p> * * @param paymentOption * The payment option selected for this reservation. * @see PaymentOption */ public void setPaymentOption(String paymentOption) { this.paymentOption = paymentOption; } /** * <p> * The payment option selected for this reservation. * </p> * * @return The payment option selected for this reservation. * @see PaymentOption */ public String getPaymentOption() { return this.paymentOption; } /** * <p> * The payment option selected for this reservation. * </p> * * @param paymentOption * The payment option selected for this reservation. * @return Returns a reference to this object so that method calls can be chained together. * @see PaymentOption */ public HostReservation withPaymentOption(String paymentOption) { setPaymentOption(paymentOption); return this; } /** * <p> * The payment option selected for this reservation. * </p> * * @param paymentOption * The payment option selected for this reservation. * @see PaymentOption */ public void setPaymentOption(PaymentOption paymentOption) { withPaymentOption(paymentOption); } /** * <p> * The payment option selected for this reservation. * </p> * * @param paymentOption * The payment option selected for this reservation. * @return Returns a reference to this object so that method calls can be chained together. * @see PaymentOption */ public HostReservation withPaymentOption(PaymentOption paymentOption) { this.paymentOption = paymentOption.toString(); return this; } /** * <p> * The date and time that the reservation started. * </p> * * @param start * The date and time that the reservation started. */ public void setStart(java.util.Date start) { this.start = start; } /** * <p> * The date and time that the reservation started. * </p> * * @return The date and time that the reservation started. */ public java.util.Date getStart() { return this.start; } /** * <p> * The date and time that the reservation started. * </p> * * @param start * The date and time that the reservation started. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withStart(java.util.Date start) { setStart(start); return this; } /** * <p> * The state of the reservation. * </p> * * @param state * The state of the reservation. * @see ReservationState */ public void setState(String state) { this.state = state; } /** * <p> * The state of the reservation. * </p> * * @return The state of the reservation. * @see ReservationState */ public String getState() { return this.state; } /** * <p> * The state of the reservation. * </p> * * @param state * The state of the reservation. * @return Returns a reference to this object so that method calls can be chained together. * @see ReservationState */ public HostReservation withState(String state) { setState(state); return this; } /** * <p> * The state of the reservation. * </p> * * @param state * The state of the reservation. * @see ReservationState */ public void setState(ReservationState state) { withState(state); } /** * <p> * The state of the reservation. * </p> * * @param state * The state of the reservation. * @return Returns a reference to this object so that method calls can be chained together. * @see ReservationState */ public HostReservation withState(ReservationState state) { this.state = state.toString(); return this; } /** * <p> * The upfront price of the reservation. * </p> * * @param upfrontPrice * The upfront price of the reservation. */ public void setUpfrontPrice(String upfrontPrice) { this.upfrontPrice = upfrontPrice; } /** * <p> * The upfront price of the reservation. * </p> * * @return The upfront price of the reservation. */ public String getUpfrontPrice() { return this.upfrontPrice; } /** * <p> * The upfront price of the reservation. * </p> * * @param upfrontPrice * The upfront price of the reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withUpfrontPrice(String upfrontPrice) { setUpfrontPrice(upfrontPrice); return this; } /** * <p> * Any tags assigned to the Dedicated Host Reservation. * </p> * * @return Any tags assigned to the Dedicated Host Reservation. */ public java.util.List<Tag> getTags() { if (tags == null) { tags = new com.amazonaws.internal.SdkInternalList<Tag>(); } return tags; } /** * <p> * Any tags assigned to the Dedicated Host Reservation. * </p> * * @param tags * Any tags assigned to the Dedicated Host Reservation. */ public void setTags(java.util.Collection<Tag> tags) { if (tags == null) { this.tags = null; return; } this.tags = new com.amazonaws.internal.SdkInternalList<Tag>(tags); } /** * <p> * Any tags assigned to the Dedicated Host Reservation. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * Any tags assigned to the Dedicated Host Reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withTags(Tag... tags) { if (this.tags == null) { setTags(new com.amazonaws.internal.SdkInternalList<Tag>(tags.length)); } for (Tag ele : tags) { this.tags.add(ele); } return this; } /** * <p> * Any tags assigned to the Dedicated Host Reservation. * </p> * * @param tags * Any tags assigned to the Dedicated Host Reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public HostReservation withTags(java.util.Collection<Tag> tags) { setTags(tags); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCount() != null) sb.append("Count: ").append(getCount()).append(","); if (getCurrencyCode() != null) sb.append("CurrencyCode: ").append(getCurrencyCode()).append(","); if (getDuration() != null) sb.append("Duration: ").append(getDuration()).append(","); if (getEnd() != null) sb.append("End: ").append(getEnd()).append(","); if (getHostIdSet() != null) sb.append("HostIdSet: ").append(getHostIdSet()).append(","); if (getHostReservationId() != null) sb.append("HostReservationId: ").append(getHostReservationId()).append(","); if (getHourlyPrice() != null) sb.append("HourlyPrice: ").append(getHourlyPrice()).append(","); if (getInstanceFamily() != null) sb.append("InstanceFamily: ").append(getInstanceFamily()).append(","); if (getOfferingId() != null) sb.append("OfferingId: ").append(getOfferingId()).append(","); if (getPaymentOption() != null) sb.append("PaymentOption: ").append(getPaymentOption()).append(","); if (getStart() != null) sb.append("Start: ").append(getStart()).append(","); if (getState() != null) sb.append("State: ").append(getState()).append(","); if (getUpfrontPrice() != null) sb.append("UpfrontPrice: ").append(getUpfrontPrice()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof HostReservation == false) return false; HostReservation other = (HostReservation) obj; if (other.getCount() == null ^ this.getCount() == null) return false; if (other.getCount() != null && other.getCount().equals(this.getCount()) == false) return false; if (other.getCurrencyCode() == null ^ this.getCurrencyCode() == null) return false; if (other.getCurrencyCode() != null && other.getCurrencyCode().equals(this.getCurrencyCode()) == false) return false; if (other.getDuration() == null ^ this.getDuration() == null) return false; if (other.getDuration() != null && other.getDuration().equals(this.getDuration()) == false) return false; if (other.getEnd() == null ^ this.getEnd() == null) return false; if (other.getEnd() != null && other.getEnd().equals(this.getEnd()) == false) return false; if (other.getHostIdSet() == null ^ this.getHostIdSet() == null) return false; if (other.getHostIdSet() != null && other.getHostIdSet().equals(this.getHostIdSet()) == false) return false; if (other.getHostReservationId() == null ^ this.getHostReservationId() == null) return false; if (other.getHostReservationId() != null && other.getHostReservationId().equals(this.getHostReservationId()) == false) return false; if (other.getHourlyPrice() == null ^ this.getHourlyPrice() == null) return false; if (other.getHourlyPrice() != null && other.getHourlyPrice().equals(this.getHourlyPrice()) == false) return false; if (other.getInstanceFamily() == null ^ this.getInstanceFamily() == null) return false; if (other.getInstanceFamily() != null && other.getInstanceFamily().equals(this.getInstanceFamily()) == false) return false; if (other.getOfferingId() == null ^ this.getOfferingId() == null) return false; if (other.getOfferingId() != null && other.getOfferingId().equals(this.getOfferingId()) == false) return false; if (other.getPaymentOption() == null ^ this.getPaymentOption() == null) return false; if (other.getPaymentOption() != null && other.getPaymentOption().equals(this.getPaymentOption()) == false) return false; if (other.getStart() == null ^ this.getStart() == null) return false; if (other.getStart() != null && other.getStart().equals(this.getStart()) == false) return false; if (other.getState() == null ^ this.getState() == null) return false; if (other.getState() != null && other.getState().equals(this.getState()) == false) return false; if (other.getUpfrontPrice() == null ^ this.getUpfrontPrice() == null) return false; if (other.getUpfrontPrice() != null && other.getUpfrontPrice().equals(this.getUpfrontPrice()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCount() == null) ? 0 : getCount().hashCode()); hashCode = prime * hashCode + ((getCurrencyCode() == null) ? 0 : getCurrencyCode().hashCode()); hashCode = prime * hashCode + ((getDuration() == null) ? 0 : getDuration().hashCode()); hashCode = prime * hashCode + ((getEnd() == null) ? 0 : getEnd().hashCode()); hashCode = prime * hashCode + ((getHostIdSet() == null) ? 0 : getHostIdSet().hashCode()); hashCode = prime * hashCode + ((getHostReservationId() == null) ? 0 : getHostReservationId().hashCode()); hashCode = prime * hashCode + ((getHourlyPrice() == null) ? 0 : getHourlyPrice().hashCode()); hashCode = prime * hashCode + ((getInstanceFamily() == null) ? 0 : getInstanceFamily().hashCode()); hashCode = prime * hashCode + ((getOfferingId() == null) ? 0 : getOfferingId().hashCode()); hashCode = prime * hashCode + ((getPaymentOption() == null) ? 0 : getPaymentOption().hashCode()); hashCode = prime * hashCode + ((getStart() == null) ? 0 : getStart().hashCode()); hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode()); hashCode = prime * hashCode + ((getUpfrontPrice() == null) ? 0 : getUpfrontPrice().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public HostReservation clone() { try { return (HostReservation) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package io.github.woodenbell.blix; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.regex.*; /** * Internal utilities class. * @author WoodenBell * @version 0.3 * @since 0.3 */ public class Util { /** * Converts a string object to an array of integers. * @param str The string to be converted. * @return An array of integers representing the string. */ public static int[] strToIntArray(String str) { int[] intArray = new int[str.length()]; for(int i = 0; i < intArray.length; i ++) { intArray[i] = str.charAt(i); } return intArray; } /** * URLEncodes the essential characters string (excluding a-z, A-Z, 0-9 and other characters). * @param UrlStr The string to be URLEncoded * @return The URLEncoded String */ static String basicUrlEncode(String urlStr) { StringBuilder bd = new StringBuilder(); for(char c : urlStr.toCharArray()) { if(URLEncodingReference.urlDecoded.containsKey(c)) bd.append(URLEncodingReference.urlDecoded.get(c)); else bd.append(c); } return bd.toString(); } /** * Decodes an URL encoded string. * @param urlEncStr The URL encoded string. * @return The decoded string. */ public static String decodeURLEncoded(String urlEncStr) { Matcher m = Pattern.compile("%[0-9a-f-A-F]{2}").matcher(urlEncStr); String decStr = urlEncStr; String curr; while(m.find()) { curr = m.group(); System.out.print(curr + ":::" + URLEncodingReference.urlEncoded.get(curr.toUpperCase()) + "\n"); decStr = decStr.replaceAll(curr, "" + URLEncodingReference.urlEncoded.get(curr.toUpperCase())); } return decStr; } /** * Converts an array of integers to a string. * @param intArray The array of integers to be converted. * @return The string. */ public static String intArrayToStr(int[] intArray) { StringBuilder builder = new StringBuilder(); for(int i : intArray) builder.append((char) i); return builder.toString(); } public static HashMap<String, String> parseQueryString(String queryString) { HashMap<String, String> parsed = new HashMap<String, String>(); String[] kv; if(queryString.contains("\n")) { for(String s : queryString.split("\\n")) { kv = s.split("="); parsed.put(decodeURLEncoded(kv[0]), decodeURLEncoded(kv[1])); } } else { kv = queryString.split("\\="); parsed.put(decodeURLEncoded(kv[0]), decodeURLEncoded(kv[1])); } return parsed; } /** * Gets the current working directory. * @return The current working directory. */ public static String getCWD() { return Paths.get("").toAbsolutePath().toString().replaceAll("\\\\", "/"); } /** * Creates a HTML page for directory view. * @param p The path that will be viewed. * @param serverPath The requested URL. * @param rootDir The root directory of the server (used to fix path relativity). * @return The string containing the HTML for the directory view. * @throws IOException Errors when creating a new DirectoryStream * @see DirectoryStream */ public static String htmlDirView(Path p, String serverPath, String rootDir) throws IOException { DirectoryStream<Path> dirStream = Files.newDirectoryStream(p); StringBuilder htmlBuilder = new StringBuilder(); htmlBuilder.append("<!DOCTYPE html\r\n" + "<html>\r\n" + "<head>\r\n" + "<title>\r\n" + p.getFileName().toString() + "</title>\r\n" + "</head>\r\n" + "<body>\r\n" + "<b>\r\n" + p.toAbsolutePath().toString().replaceAll("\\\\", "/").replaceAll("\\.", "") + "\r\n" + "</b>\r\n" + "<br />\r\n" ); if(serverPath.split("\\/").length > 1) { htmlBuilder.append("<a href=..>..</a>\r\n<br />\r\n"); } for(Path entry : dirStream) { System.out.println("File name: " + entry.getFileName().toString().replace(rootDir.replaceAll("[\\.\\/]", ""), "")); htmlBuilder.append("<a href=" + basicUrlEncode(p.getFileName().toString().replace(rootDir.replaceAll("[\\.\\/]", ""), "") + "/" + entry.getFileName().toString()) + ">" + entry.getFileName().toString() + "</a>\r\n" + "<br />\r\n"); } htmlBuilder.append("</body>\r\n" + "</html>"); return htmlBuilder.toString(); } /** * Wrapper for an array of bytes used to store it's content in a HashMap. * @author WoodenBell * @version 0.3 * @since 0.3 */ public static class ByteArray { public byte[] content; public ByteArray(byte[] content) { this.content = content; } } /** * Reverses the keys and values of the HashMap. * @param hm The HashMap of Strings and Characters to have it's keys and values reversed. * @return The HashMap with reversed keys and values. */ public static HashMap<Character, String> reverseKeyVals(HashMap<String, Character> hm) { HashMap<Character, String> rhm = new HashMap<>(); Iterator<String> iter = hm.keySet().iterator(); String curr = null; while(iter.hasNext()) { curr = iter.next(); rhm.put(hm.get(curr), curr); } return rhm; } /** * Checks if the HTTP request is valid. * @param request THe HTTP request body. * @return If the request is valid. */ public static boolean checkValidHTTPRequest(String request) { if(request.trim().equals("")) return false; String[] headers = request.split("\n"); String[] pathAndMethod = headers[0].split(" "); if(pathAndMethod.length != 3) return false; if(!pathAndMethod[0].equals("GET") && !pathAndMethod[0].equals("POST") && !pathAndMethod[0].equals("HEAD") && !pathAndMethod[0].equals("PUT") && !pathAndMethod[0].equals("DELETE") && !pathAndMethod[0].equals("CONNECT") && !pathAndMethod[0].equals("OPTIONS") && !pathAndMethod[0].equals("TRACE") && !pathAndMethod[0].equals("PATCH")) return false; if(!pathAndMethod[1].startsWith("/")) return false; if(!pathAndMethod[2].startsWith("HTTP/1.1") && !pathAndMethod[2].startsWith("HTTP/1.0")) return false; if(!pathAndMethod[2].startsWith("HTTP/1.1")) { boolean foundHost = false; if(headers.length == 1) return false; for(int i = 1; i < headers.length; i++) { if(headers[i].startsWith("Host")) foundHost = true; } if(!foundHost) return false; } return true; } }
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.common.images; import android.net.Uri; import android.os.Parcel; import com.google.android.gms.common.internal.Objects; import com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable; import com.google.android.gms.common.internal.safeparcel.SafeParcelWriter; import java.util.Locale; import org.json.JSONException; import org.json.JSONObject; // Referenced classes of package com.google.android.gms.common.images: // zae public final class WebImage extends AbstractSafeParcelable { WebImage(int i, Uri uri, int j, int k) { // 0 0:aload_0 // 1 1:invokespecial #41 <Method void AbstractSafeParcelable()> zale = i; // 2 4:aload_0 // 3 5:iload_1 // 4 6:putfield #43 <Field int zale> zanf = uri; // 5 9:aload_0 // 6 10:aload_2 // 7 11:putfield #45 <Field Uri zanf> zand = j; // 8 14:aload_0 // 9 15:iload_3 // 10 16:putfield #47 <Field int zand> zane = k; // 11 19:aload_0 // 12 20:iload 4 // 13 22:putfield #49 <Field int zane> // 14 25:return } public WebImage(Uri uri) throws IllegalArgumentException { this(uri, 0, 0); // 0 0:aload_0 // 1 1:aload_1 // 2 2:iconst_0 // 3 3:iconst_0 // 4 4:invokespecial #57 <Method void WebImage(Uri, int, int)> // 5 7:return } public WebImage(Uri uri, int i, int j) throws IllegalArgumentException { this(1, uri, i, j); // 0 0:aload_0 // 1 1:iconst_1 // 2 2:aload_1 // 3 3:iload_2 // 4 4:iload_3 // 5 5:invokespecial #60 <Method void WebImage(int, Uri, int, int)> if(uri != null) //* 6 8:aload_1 //* 7 9:ifnull 31 { if(i >= 0 && j >= 0) //* 8 12:iload_2 //* 9 13:iflt 21 //* 10 16:iload_3 //* 11 17:iflt 21 return; // 12 20:return else throw new IllegalArgumentException("width and height must not be negative"); // 13 21:new #54 <Class IllegalArgumentException> // 14 24:dup // 15 25:ldc1 #62 <String "width and height must not be negative"> // 16 27:invokespecial #65 <Method void IllegalArgumentException(String)> // 17 30:athrow } else { throw new IllegalArgumentException("url cannot be null"); // 18 31:new #54 <Class IllegalArgumentException> // 19 34:dup // 20 35:ldc1 #67 <String "url cannot be null"> // 21 37:invokespecial #65 <Method void IllegalArgumentException(String)> // 22 40:athrow } } public WebImage(JSONObject jsonobject) throws IllegalArgumentException { this(zaa(jsonobject), jsonobject.optInt("width", 0), jsonobject.optInt("height", 0)); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokestatic #73 <Method Uri zaa(JSONObject)> // 3 5:aload_1 // 4 6:ldc1 #75 <String "width"> // 5 8:iconst_0 // 6 9:invokevirtual #81 <Method int JSONObject.optInt(String, int)> // 7 12:aload_1 // 8 13:ldc1 #83 <String "height"> // 9 15:iconst_0 // 10 16:invokevirtual #81 <Method int JSONObject.optInt(String, int)> // 11 19:invokespecial #57 <Method void WebImage(Uri, int, int)> // 12 22:return } private static Uri zaa(JSONObject jsonobject) { if(!jsonobject.has("url")) break MISSING_BLOCK_LABEL_21; // 0 0:aload_0 // 1 1:ldc1 #87 <String "url"> // 2 3:invokevirtual #91 <Method boolean JSONObject.has(String)> // 3 6:ifeq 21 jsonobject = ((JSONObject) (Uri.parse(jsonobject.getString("url")))); // 4 9:aload_0 // 5 10:ldc1 #87 <String "url"> // 6 12:invokevirtual #95 <Method String JSONObject.getString(String)> // 7 15:invokestatic #101 <Method Uri Uri.parse(String)> // 8 18:astore_0 return ((Uri) (jsonobject)); // 9 19:aload_0 // 10 20:areturn _L2: return null; // 11 21:aconst_null // 12 22:areturn jsonobject; // 13 23:astore_0 if(true) goto _L2; else goto _L1 _L1: //* 14 24:goto 21 } public final boolean equals(Object obj) { if(this == obj) //* 0 0:aload_0 //* 1 1:aload_1 //* 2 2:if_acmpne 7 return true; // 3 5:iconst_1 // 4 6:ireturn if(obj != null) //* 5 7:aload_1 //* 6 8:ifnull 65 { if(!(obj instanceof WebImage)) //* 7 11:aload_1 //* 8 12:instanceof #2 <Class WebImage> //* 9 15:ifne 20 return false; // 10 18:iconst_0 // 11 19:ireturn obj = ((Object) ((WebImage)obj)); // 12 20:aload_1 // 13 21:checkcast #2 <Class WebImage> // 14 24:astore_1 return Objects.equal(((Object) (zanf)), ((Object) (((WebImage) (obj)).zanf))) && zand == ((WebImage) (obj)).zand && zane == ((WebImage) (obj)).zane; // 15 25:aload_0 // 16 26:getfield #45 <Field Uri zanf> // 17 29:aload_1 // 18 30:getfield #45 <Field Uri zanf> // 19 33:invokestatic #109 <Method boolean Objects.equal(Object, Object)> // 20 36:ifeq 63 // 21 39:aload_0 // 22 40:getfield #47 <Field int zand> // 23 43:aload_1 // 24 44:getfield #47 <Field int zand> // 25 47:icmpne 63 // 26 50:aload_0 // 27 51:getfield #49 <Field int zane> // 28 54:aload_1 // 29 55:getfield #49 <Field int zane> // 30 58:icmpne 63 // 31 61:iconst_1 // 32 62:ireturn // 33 63:iconst_0 // 34 64:ireturn } else { return false; // 35 65:iconst_0 // 36 66:ireturn } } public final int getHeight() { return zane; // 0 0:aload_0 // 1 1:getfield #49 <Field int zane> // 2 4:ireturn } public final Uri getUrl() { return zanf; // 0 0:aload_0 // 1 1:getfield #45 <Field Uri zanf> // 2 4:areturn } public final int getWidth() { return zand; // 0 0:aload_0 // 1 1:getfield #47 <Field int zand> // 2 4:ireturn } public final int hashCode() { return Objects.hashCode(new Object[] { zanf, Integer.valueOf(zand), Integer.valueOf(zane) }); // 0 0:iconst_3 // 1 1:anewarray Object[] // 2 4:dup // 3 5:iconst_0 // 4 6:aload_0 // 5 7:getfield #45 <Field Uri zanf> // 6 10:aastore // 7 11:dup // 8 12:iconst_1 // 9 13:aload_0 // 10 14:getfield #47 <Field int zand> // 11 17:invokestatic #120 <Method Integer Integer.valueOf(int)> // 12 20:aastore // 13 21:dup // 14 22:iconst_2 // 15 23:aload_0 // 16 24:getfield #49 <Field int zane> // 17 27:invokestatic #120 <Method Integer Integer.valueOf(int)> // 18 30:aastore // 19 31:invokestatic #123 <Method int Objects.hashCode(Object[])> // 20 34:ireturn } public final JSONObject toJson() { JSONObject jsonobject = new JSONObject(); // 0 0:new #77 <Class JSONObject> // 1 3:dup // 2 4:invokespecial #126 <Method void JSONObject()> // 3 7:astore_1 try { jsonobject.put("url", ((Object) (zanf.toString()))); // 4 8:aload_1 // 5 9:ldc1 #87 <String "url"> // 6 11:aload_0 // 7 12:getfield #45 <Field Uri zanf> // 8 15:invokevirtual #130 <Method String Uri.toString()> // 9 18:invokevirtual #134 <Method JSONObject JSONObject.put(String, Object)> // 10 21:pop jsonobject.put("width", zand); // 11 22:aload_1 // 12 23:ldc1 #75 <String "width"> // 13 25:aload_0 // 14 26:getfield #47 <Field int zand> // 15 29:invokevirtual #137 <Method JSONObject JSONObject.put(String, int)> // 16 32:pop jsonobject.put("height", zane); // 17 33:aload_1 // 18 34:ldc1 #83 <String "height"> // 19 36:aload_0 // 20 37:getfield #49 <Field int zane> // 21 40:invokevirtual #137 <Method JSONObject JSONObject.put(String, int)> // 22 43:pop } //* 23 44:aload_1 //* 24 45:areturn catch(JSONException jsonexception) //* 25 46:astore_2 { return jsonobject; // 26 47:aload_1 // 27 48:areturn } return jsonobject; } public final String toString() { return String.format(Locale.US, "Image %dx%d %s", new Object[] { Integer.valueOf(zand), Integer.valueOf(zane), zanf.toString() }); // 0 0:getstatic #143 <Field Locale Locale.US> // 1 3:ldc1 #145 <String "Image %dx%d %s"> // 2 5:iconst_3 // 3 6:anewarray Object[] // 4 9:dup // 5 10:iconst_0 // 6 11:aload_0 // 7 12:getfield #47 <Field int zand> // 8 15:invokestatic #120 <Method Integer Integer.valueOf(int)> // 9 18:aastore // 10 19:dup // 11 20:iconst_1 // 12 21:aload_0 // 13 22:getfield #49 <Field int zane> // 14 25:invokestatic #120 <Method Integer Integer.valueOf(int)> // 15 28:aastore // 16 29:dup // 17 30:iconst_2 // 18 31:aload_0 // 19 32:getfield #45 <Field Uri zanf> // 20 35:invokevirtual #130 <Method String Uri.toString()> // 21 38:aastore // 22 39:invokestatic #151 <Method String String.format(Locale, String, Object[])> // 23 42:areturn } public final void writeToParcel(Parcel parcel, int i) { int j = SafeParcelWriter.beginObjectHeader(parcel); // 0 0:aload_1 // 1 1:invokestatic #159 <Method int SafeParcelWriter.beginObjectHeader(Parcel)> // 2 4:istore_3 SafeParcelWriter.writeInt(parcel, 1, zale); // 3 5:aload_1 // 4 6:iconst_1 // 5 7:aload_0 // 6 8:getfield #43 <Field int zale> // 7 11:invokestatic #163 <Method void SafeParcelWriter.writeInt(Parcel, int, int)> SafeParcelWriter.writeParcelable(parcel, 2, ((android.os.Parcelable) (getUrl())), i, false); // 8 14:aload_1 // 9 15:iconst_2 // 10 16:aload_0 // 11 17:invokevirtual #165 <Method Uri getUrl()> // 12 20:iload_2 // 13 21:iconst_0 // 14 22:invokestatic #169 <Method void SafeParcelWriter.writeParcelable(Parcel, int, android.os.Parcelable, int, boolean)> SafeParcelWriter.writeInt(parcel, 3, getWidth()); // 15 25:aload_1 // 16 26:iconst_3 // 17 27:aload_0 // 18 28:invokevirtual #171 <Method int getWidth()> // 19 31:invokestatic #163 <Method void SafeParcelWriter.writeInt(Parcel, int, int)> SafeParcelWriter.writeInt(parcel, 4, getHeight()); // 20 34:aload_1 // 21 35:iconst_4 // 22 36:aload_0 // 23 37:invokevirtual #173 <Method int getHeight()> // 24 40:invokestatic #163 <Method void SafeParcelWriter.writeInt(Parcel, int, int)> SafeParcelWriter.finishObjectHeader(parcel, j); // 25 43:aload_1 // 26 44:iload_3 // 27 45:invokestatic #176 <Method void SafeParcelWriter.finishObjectHeader(Parcel, int)> // 28 48:return } public static final android.os.Parcelable.Creator CREATOR = new zae(); private final int zale; private final int zand; private final int zane; private final Uri zanf; static { // 0 0:new #31 <Class zae> // 1 3:dup // 2 4:invokespecial #34 <Method void zae()> // 3 7:putstatic #36 <Field android.os.Parcelable$Creator CREATOR> //* 4 10:return } }
package extracells.gui; import appeng.api.storage.data.IAEFluidStack; import extracells.Extracells; import extracells.api.ECApi; import extracells.container.ContainerFluidStorage; import extracells.gui.widget.FluidWidgetComparator; import extracells.gui.widget.fluid.AbstractFluidWidget; import extracells.gui.widget.fluid.IFluidSelectorContainer; import extracells.gui.widget.fluid.IFluidSelectorGui; import extracells.gui.widget.fluid.WidgetFluidSelector; import extracells.network.packet.part.PacketFluidStorage; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class GuiFluidStorage extends GuiContainer implements IFluidSelectorGui { private EntityPlayer player; private int currentScroll = 0; private GuiTextField searchbar; private List<AbstractFluidWidget> fluidWidgets = new ArrayList<AbstractFluidWidget>(); private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/terminalfluid.png"); public IAEFluidStack currentFluid; private ContainerFluidStorage containerFluidStorage; private final String guiName; public GuiFluidStorage(EntityPlayer _player, String _guiName) { super(new ContainerFluidStorage(_player)); this.containerFluidStorage = (ContainerFluidStorage) this.inventorySlots; this.containerFluidStorage.setGui(this); this.player = _player; this.xSize = 176; this.ySize = 204; this.guiName = _guiName; new PacketFluidStorage(this.player).sendPacketToServer(); } @Override protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); this.searchbar.drawTextBox(); new PacketFluidStorage(this.player).sendPacketToServer(); } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { this.fontRendererObj .drawString(StatCollector.translateToLocal(this.guiName) .replace("ME ", ""), 5, 6, 0x000000); drawWidgets(mouseX, mouseY); if (this.currentFluid != null) { long currentFluidAmount = this.currentFluid.getStackSize(); String amountToText = Long.toString(currentFluidAmount) + "mB"; if (Extracells.shortenedBuckets()) { if (currentFluidAmount > 1000000000L) amountToText = Long .toString(currentFluidAmount / 1000000000L) + "MegaB"; else if (currentFluidAmount > 1000000L) amountToText = Long.toString(currentFluidAmount / 1000000L) + "KiloB"; else if (currentFluidAmount > 9999L) { amountToText = Long.toString(currentFluidAmount / 1000L) + "B"; } } this.fontRendererObj.drawString( StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + amountToText, 45, 91, 0x000000); this.fontRendererObj.drawString( StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + this.currentFluid.getFluid().getLocalizedName( this.currentFluid.getFluidStack()), 45, 101, 0x000000); } } public void drawWidgets(int mouseX, int mouseY) { int listSize = this.fluidWidgets.size(); if (!this.containerFluidStorage.getFluidStackList().isEmpty()) { outerLoop: for (int y = 0; y < 4; y++) { for (int x = 0; x < 9; x++) { int widgetIndex = y * 9 + x + this.currentScroll * 9; if (0 <= widgetIndex && widgetIndex < listSize) { AbstractFluidWidget widget = this.fluidWidgets .get(widgetIndex); widget.drawWidget(x * 18 + 7, y * 18 + 17); } else { break outerLoop; } } } for (int x = 0; x < 9; x++) { for (int y = 0; y < 4; y++) { int widgetIndex = y * 9 + x; if (0 <= widgetIndex && widgetIndex < listSize) { this.fluidWidgets.get(widgetIndex).drawTooltip( x * 18 + 7, y * 18 - 1, mouseX, mouseY); } else { break; } } } int deltaWheel = Mouse.getDWheel(); if (deltaWheel > 0) { this.currentScroll++; } else if (deltaWheel < 0) { this.currentScroll--; } if (this.currentScroll < 0) this.currentScroll = 0; if (listSize / 9 < 4 && this.currentScroll < listSize / 9 + 4) this.currentScroll = 0; } } @Override public IFluidSelectorContainer getContainer() { return this.containerFluidStorage; } @Override public IAEFluidStack getCurrentFluid() { return this.containerFluidStorage.getSelectedFluidStack(); } @Override public int guiLeft() { return this.guiLeft; } @Override public int guiTop() { return this.guiTop; } @Override public void initGui() { super.initGui(); Mouse.getDWheel(); updateFluids(); Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); this.searchbar = new GuiTextField(this.fontRendererObj, this.guiLeft + 81, this.guiTop + 6, 88, 10) { private int xPos = 0; private int yPos = 0; private int width = 0; private int height = 0; @Override public void mouseClicked(int x, int y, int mouseBtn) { boolean flag = x >= this.xPos && x < this.xPos + this.width && y >= this.yPos && y < this.yPos + this.height; if (flag && mouseBtn == 3) setText(""); } }; this.searchbar.setEnableBackgroundDrawing(false); this.searchbar.setFocused(true); this.searchbar.setMaxStringLength(15); } @Override protected void keyTyped(char key, int keyID) { if (keyID == Keyboard.KEY_ESCAPE) this.mc.thePlayer.closeScreen(); this.searchbar.textboxKeyTyped(key, keyID); updateFluids(); } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { super.mouseClicked(mouseX, mouseY, mouseBtn); this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); int listSize = this.fluidWidgets.size(); for (int x = 0; x < 9; x++) { for (int y = 0; y < 4; y++) { int index = y * 9 + x; if (0 <= index && index < listSize) { AbstractFluidWidget widget = this.fluidWidgets.get(index); widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); } } } } public void updateFluids() { this.fluidWidgets = new ArrayList<AbstractFluidWidget>(); for (IAEFluidStack fluidStack : this.containerFluidStorage .getFluidStackList()) { if (fluidStack.getFluid() .getLocalizedName(fluidStack.getFluidStack()).toLowerCase() .contains(this.searchbar.getText().toLowerCase()) && ECApi.instance().canFluidSeeInTerminal( fluidStack.getFluid())) { this.fluidWidgets .add(new WidgetFluidSelector(this, fluidStack)); } } updateSelectedFluid(); } public void updateSelectedFluid() { this.currentFluid = null; for (IAEFluidStack stack : this.containerFluidStorage .getFluidStackList()) { if (stack.getFluid() == this.containerFluidStorage .getSelectedFluid()) this.currentFluid = stack; } } }
package com.dogigiri.datastructures.linear.hashtables.exercise; import java.util.LinkedList; public class MoshHashTable { private class Entry { private int key; private String value; public Entry(int key, String value) { this.key = key; this.value = value; } } private LinkedList<Entry>[] entries = new LinkedList[5]; public void put(int key, String value) { var entry = getEntry(key); if (entry != null) { entry.value = value; return; } getOrCreateBucket(key).add(new Entry(key, value)); } public String get(int key) { var entry = getEntry(key); return (entry == null) ? null : entry.value; } public void remove(int key) { var entry = getEntry(key); if (entry == null) throw new IllegalStateException(); getBucket(key).remove(entry); } private LinkedList<Entry> getBucket(int key) { return entries[hash(key)]; } private LinkedList<Entry> getOrCreateBucket(int key) { var index = hash(key); var bucket = entries[index]; if (bucket == null) entries[index] = new LinkedList<>(); return bucket; } private Entry getEntry(int key) { var bucket = getBucket(key); if (bucket != null) { for (var entry : bucket) { if (entry.key == key) return entry; } } return null; } private int hash(int key) { return key % entries.length; } }
/** * Response to a Probe Request. * * @author ajfc * @date 22032016 */ package pdu; import java.sql.Timestamp; public class ProbeResponsePDU extends PDU { Timestamp timestamp; /** * Parametrized constructor. * @param timestamp Timestamp of when the PDU is created. */ public ProbeResponsePDU(Timestamp timestamp) { super(PDUType.PROBE_RESPONSE, new int[] {0,0,0,0}); this.timestamp = (Timestamp) timestamp.clone(); } /** * Parametrized constructor. * @param version The PDU version number. * @param security If the PDU is to have security (1) or not (0). * @param options PDU options. * @param message Message to be sent with the PDU. * @param timestamp Timestamp of when the PDU is created. */ public ProbeResponsePDU(int version, int security, int[] options, Timestamp timestamp) { super(version, security, PDUType.PROBE_RESPONSE, options); this.timestamp = (Timestamp) timestamp.clone(); } // Getters. /** @return The PDU timestamp. */ public Timestamp getTimestamp() { return (Timestamp) this.timestamp.clone(); } // Setters. /** * Change the PDU timestamp. * @param timestamp The new timestamp to be used. */ public void setTimestamp(Timestamp ts) { this.timestamp = ts; } }
package com.nowcoder.seckill; import com.nowcoder.seckill.dao.ItemMapper; import com.nowcoder.seckill.dao.ItemStockMapper; import com.nowcoder.seckill.dao.PromotionMapper; import com.nowcoder.seckill.entity.Item; import com.nowcoder.seckill.entity.ItemStock; import com.nowcoder.seckill.entity.Promotion; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import java.math.BigDecimal; import java.sql.Timestamp; //@SpringBootTest public class SimulateBackendData { @Autowired private ItemMapper itemMapper; @Autowired private ItemStockMapper itemStockMapper; @Autowired private PromotionMapper promotionMapper; @Test public void initItems() { for (int i = 0; i < 30; i++) { Item item = new Item(); item.setTitle("伊利 安慕希 常温希腊风味酸牛奶 原味230g*10瓶/箱(新年年货礼盒装)高端畅饮 迪丽热巴同款"); item.setPrice(new BigDecimal((i + 1) * 10)); item.setSales((i + 1) * 100); item.setImageUrl("http://img13.360buyimg.com/seckillcms/s500x500_jfs/t1/170165/16/3762/83664/600a6ae7E854b96d1/2135d5e2b052f37c.jpg"); String description = "<div class=\"row goods-parameter\">" + "<div class=\"col-sm-12 brand\">品牌:伊利</div>" + "<div class=\"col-sm-3\">商品名称:伊利安慕希</div>" + "<div class=\"col-sm-3\">商品编号:4790297</div>" + "<div class=\"col-sm-3\">商品毛重:2.945kg</div>" + "<div class=\"col-sm-3\">商品产地:中国大陆</div>" + "<div class=\"col-sm-3\">是否含果肉:无果肉</div>" + "<div class=\"col-sm-3\">适用人群:成人</div>" + "<div class=\"col-sm-3\">脂肪含量:全脂</div>" + "<div class=\"col-sm-3\">净含量:其它</div>" + "<div class=\"col-sm-3\">是否添加糖:添加糖</div>" + "<div class=\"col-sm-3\">口味:原味</div>" + "<div class=\"col-sm-3\">包装:整箱装</div>" + "<div class=\"col-sm-3\">是否有机:非有机</div>" + "</div>" + "<div class=\"row goods-pictures\">" + "<div class=\"col-sm-12\"><img src=\"http://img30.360buyimg.com/jgsq-productsoa/jfs/t1/163023/15/3412/115466/600b994eEc1507c70/d3b3c5c3f38dd38e.jpg\"/></div>" + "<div class=\"col-sm-12\"><img src=\"http://img30.360buyimg.com/sku/jfs/t1/153362/3/12954/94425/5fef3a91E0e76b821/d7c7094abf9eb5c0.jpg\"/></div>" + "<div class=\"col-sm-12\"><img src=\"http://img30.360buyimg.com/sku/jfs/t1/140813/29/4024/84987/5f1f9b21E67a55958/d860fb1ea09c7c5d.jpg\"/></div>" + "<div class=\"col-sm-12\"><img src=\"http://img30.360buyimg.com/sku/jfs/t1/112319/11/13417/115512/5f1f9b22E42819010/215b184c1c74220b.jpg\"/></div>" + "<div class=\"col-sm-12\"><img src=\"http://img30.360buyimg.com/sku/jfs/t1/117116/11/13309/151047/5f1f9b22E90e4f251/503917d2d87c3d9f.jpg\"/></div>" + "<div class=\"col-sm-12\"><img src=\"http://img30.360buyimg.com/sku/jfs/t1/112780/22/13557/74246/5f1f9b21Ee0a2f5ae/b49d75ce59180823.jpg\"/></div>" + "<div class=\"col-sm-12\"><img src=\"http://img30.360buyimg.com/sku/jfs/t1/111141/9/13367/97512/5f1f9b22E4c20c016/75bc1c2f9b2950a8.jpg\"/></div>" + "</div>"; item.setDescription(description); itemMapper.insert(item); ItemStock stock = new ItemStock(); stock.setItemId(item.getId()); stock.setStock((i + 1) * 20); itemStockMapper.insert(stock); Promotion promotion = new Promotion(); promotion.setName("2021年货节"); promotion.setStartTime(new Timestamp(System.currentTimeMillis())); promotion.setEndTime(new Timestamp(System.currentTimeMillis() + (long) 365 * 24 * 3600 * 1000)); promotion.setItemId(item.getId()); promotion.setPromotionPrice(new BigDecimal((i + 1) * 5)); promotionMapper.insert(promotion); } } }
/** * Copyright (c) 2016, The National Archives <pronom@nationalarchives.gov.uk> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the The National Archives nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.gov.nationalarchives.droid.export; import java.io.Writer; import java.net.URI; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.FastDateFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.univocity.parsers.csv.CsvFormat; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; import com.univocity.parsers.common.TextWritingException; import uk.gov.nationalarchives.droid.core.interfaces.config.DroidGlobalConfig; import uk.gov.nationalarchives.droid.core.interfaces.util.DroidUrlFormat; import uk.gov.nationalarchives.droid.export.interfaces.ExportOptions; import uk.gov.nationalarchives.droid.export.interfaces.ItemWriter; import uk.gov.nationalarchives.droid.profile.NodeMetaData; import uk.gov.nationalarchives.droid.profile.ProfileResourceNode; import uk.gov.nationalarchives.droid.profile.referencedata.Format; /** * @author rflitcroft * */ public class CsvItemWriter implements ItemWriter<ProfileResourceNode> { /** * Headers used in the CSV output */ static final String[] HEADERS = { "ID", "PARENT_ID", "URI", "FILE_PATH", "NAME", "METHOD", "STATUS", "SIZE", "TYPE", "EXT", "LAST_MODIFIED", "EXTENSION_MISMATCH", "HASH", "FORMAT_COUNT", "PUID", "MIME_TYPE", "FORMAT_NAME", "FORMAT_VERSION", }; private static final String FILE_URI_SCHEME = "file"; private static final int HASH_ARRAY_INDEX = 12; private final Logger log = LoggerFactory.getLogger(getClass()); private CsvWriter csvWriter; private FastDateFormat dateFormat = DateFormatUtils.ISO_DATETIME_FORMAT; private ExportOptions options = ExportOptions.ONE_ROW_PER_FILE; private String[] headers; /** * Empty bean constructor. */ public CsvItemWriter() { } /** * Constructor taking parameters. * @param writer The CsvWriter to use. */ public CsvItemWriter(CsvWriter writer) { this.csvWriter = writer; } @Override public void write(List<? extends ProfileResourceNode> nodes) { switch (options) { case ONE_ROW_PER_FILE: { writeOneRowPerFile(nodes); break; } case ONE_ROW_PER_FORMAT: { writeOneRowPerFormat(nodes); break; } default: { writeOneRowPerFile(nodes); } } } private void writeOneRowPerFile(List<? extends ProfileResourceNode> nodes) { try { for (ProfileResourceNode node : nodes) { NodeMetaData metaData = node.getMetaData(); List<String> nodeEntries = new ArrayList<String>(); nodeEntries.add(nullSafeNumber(node.getId())); //ProfileResourceNode parent = node.getParent(); //nodeEntries.add(parent != null ? nullSafeNumber(parent.getId()) : ""); nodeEntries.add(nullSafeNumber(node.getParentId())); nodeEntries.add(DroidUrlFormat.format(node.getUri())); nodeEntries.add(toFilePath(node.getUri())); nodeEntries.add(toFileName(metaData.getName())); nodeEntries.add(nullSafeName(metaData.getIdentificationMethod())); nodeEntries.add(metaData.getNodeStatus().getStatus()); nodeEntries.add(nullSafeNumber(metaData.getSize())); nodeEntries.add(metaData.getResourceType().getResourceType()); nodeEntries.add(metaData.getExtension()); nodeEntries.add(nullSafeDate(metaData.getLastModifiedDate(), dateFormat)); nodeEntries.add(node.getExtensionMismatch().toString()); nodeEntries.add(metaData.getHash()); nodeEntries.add(nullSafeNumber(node.getIdentificationCount())); for (Format format : node.getFormatIdentifications()) { nodeEntries.add(format.getPuid()); nodeEntries.add(format.getMimeType()); nodeEntries.add(format.getName()); nodeEntries.add(format.getVersion()); } csvWriter.writeRow(nodeEntries.toArray(new String[0])); } csvWriter.flush(); } catch (final TextWritingException e) { log.error(e.getRecordCharacters(), e); throw new RuntimeException(e.getMessage(), e); } } private void writeOneRowPerFormat(List<? extends ProfileResourceNode> nodes) { try { for (ProfileResourceNode node : nodes) { NodeMetaData metaData = node.getMetaData(); //ProfileResourceNode parent = node.getParent(); for (Format format : node.getFormatIdentifications()) { String[] nodeEntries = new String[] { nullSafeNumber(node.getId()), //parent != null ? nullSafeNumber(parent.getId()) : "", nullSafeNumber(node.getParentId()), DroidUrlFormat.format(node.getUri()), toFilePath(node.getUri()), toFileName(metaData.getName()), nullSafeName(metaData.getIdentificationMethod()), metaData.getNodeStatus().getStatus(), nullSafeNumber(metaData.getSize()), metaData.getResourceType().getResourceType(), metaData.getExtension(), nullSafeDate(metaData.getLastModifiedDate(), dateFormat), node.getExtensionMismatch().toString(), metaData.getHash(), nullSafeNumber(node.getIdentificationCount()), format.getPuid(), format.getMimeType(), format.getName(), format.getVersion(), }; csvWriter.writeRow(nodeEntries); } } csvWriter.flush(); } catch (final TextWritingException e) { log.error(e.getRecordCharacters(), e); throw new RuntimeException(e.getMessage(), e); } } /** * @param csvWriter the csvWriter to write to. */ void setCsvWriter(CsvWriter csvWriter) { this.csvWriter = csvWriter; } @Override public void open(final Writer writer) { final CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); csvWriterSettings.setQuoteAllFields(true); CsvFormat format = new CsvFormat(); // following Unix convention on line separators as previously format.setLineSeparator("\n"); csvWriterSettings.setFormat(format); csvWriter = new CsvWriter(writer, csvWriterSettings); if (headers == null) { headers = HEADERS; } csvWriter.writeHeaders(headers); } @Override public void setOptions(ExportOptions options) { this.options = options; } /** * Closes the CSV writer. */ @Override public void close() { csvWriter.close(); } private static String nullSafeName(Enum<?> value) { return value == null ? "" : value.toString(); } private static String nullSafeNumber(Number number) { return number == null ? "" : number.toString(); } private static String nullSafeDate(Date date, FastDateFormat format) { return date == null ? "" : format.format(date); } private static String toFilePath(URI uri) { if (FILE_URI_SCHEME.equals(uri.getScheme())) { return Paths.get(uri).toAbsolutePath().toString(); } return null; } private static String toFileName(String name) { return FilenameUtils.getName(name); } /** * No config is needed by this class, but it's retained temporarily for backwards compatibility purposes. * @param config the config to set */ public void setConfig(DroidGlobalConfig config) { } /** * @param headersToSet the headers to set */ @Override public void setHeaders(Map<String, String> headersToSet) { if (this.headers == null) { this.headers = HEADERS; } String hashHeader = headersToSet.get("hash"); if (hashHeader != null) { this.headers[HASH_ARRAY_INDEX] = hashHeader; } } }
/* * Copyright 2021 Shulie Technology, Co.Ltd * Email: shulie@shulie.io * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * See the License for the specific language governing permissions and * limitations under the License. */ package io.shulie.surge.data.suppliers.nettyremoting; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.name.Named; import com.pamirs.pradar.log.parser.packet.Request; import com.pamirs.pradar.log.parser.packet.Response; import com.pamirs.pradar.remoting.RemotingServer; import com.pamirs.pradar.remoting.netty.NettyCommandProcessor; import com.pamirs.pradar.remoting.netty.NettyRemotingServer; import com.pamirs.pradar.remoting.netty.NettyServerConfigurator; import com.pamirs.pradar.remoting.protocol.*; import com.pamirs.pradar.remoting.utils.RemotingThreadFactory; import io.netty.channel.ChannelHandlerContext; import io.shulie.surge.data.common.lifecycle.LifecycleObserver; import io.shulie.surge.data.common.pool.DataPoolExecutors; import io.shulie.surge.data.common.utils.IpAddressUtils; import io.shulie.surge.data.runtime.common.utils.ApiProcessor; import io.shulie.surge.data.runtime.disruptor.RingBufferIllegalStateException; import io.shulie.surge.data.runtime.processor.DataQueue; import io.shulie.surge.data.runtime.supplier.DefaultMultiProcessorSupplier; import io.shulie.surge.data.runtime.supplier.Supplier; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; /** * @author vincent */ public final class NettyRemotingSupplier extends DefaultMultiProcessorSupplier { private static final Logger logger = LoggerFactory.getLogger(NettyRemotingSupplier.class); private int port; private static final String MIN = "MIN"; private static final String MAX = "MAX"; @Inject private ApiProcessor apiProcessor; @Inject @Named("netty.remoting.server.ports") protected String pradarServerPorts; @Inject @Named("netty.remoting.server.processCores") private int coreSize = 4; private RemotingServer remotingServer; // 外部设置的端口段映射 private Map<String, String> inputPortMap = Maps.newHashMap(); /** * 开始获取数据 * * @throws IllegalStateException Queue 尚未设置时抛出此异常 * @throws Exception */ @Override public void start() throws Exception { // 获取启动的端口 Map<String, Integer> parsePortRange = parsePort(); for (int index = parsePortRange.get(MIN); index <= parsePortRange.get(MAX); index++) { try { port = index; remotingServer = getRemotingServer(port); } catch (Throwable e) { logger.error("next port start " + index); continue; } // 启动成功以后就停止掉 break; } super.start(); apiProcessor.init(); } /** * 初始化remoting server * * @return */ private RemotingServer getRemotingServer(int port) { ProtocolFactorySelector selector = new DefaultProtocolFactorySelector(); NettyServerConfigurator config = new NettyServerConfigurator(); config.setListenPort(port); config.setServerSocketRcvBufSize(32 * 1024); config.setServerSocketSndBufSize(32 * 1024); ProtocolFactorySelector protocolFactorySelector = new DefaultProtocolFactorySelector(); RemotingServer remotingServer = new NettyRemotingServer(protocolFactorySelector, config); remotingServer.registerDefaultProcessor(new NettyCommandProcessor() { @Override public RemotingCommand processCommand(ChannelHandlerContext ctx, RemotingCommand req) { RemotingCommand responseCommand = new RemotingCommand(); /** * 设置response */ responseCommand.setCode(CommandCode.SUCCESS); responseCommand.setVersion(req.getVersion()); responseCommand.setProtocolCode(ProtocolCode.KRYO); Response response = new Response(); response.setSuccess(true); ProtocolFactory factory = selector.select(req.getProtocolCode()); try { Request request = factory.decode(Request.class, req); if (request == null) { logger.warn("agent push version is error " + req.toString()); responseCommand.setVersion(CommandVersion.V1); return responseCommand; } String content = new String(request.getBody()); String hostIp = request.getHostIp(); String dataVersion = request.getVersion(); Byte dataType = request.getDataType(); DataQueue queue = queueMap.get(String.valueOf(dataType)); Map<String, Object> header = Maps.newHashMap(); header.put("hostIp", hostIp); header.put("dataVersion", dataVersion); header.put("dataType", dataType); queue.publish(header, queue.splitLog(content, dataType)); } catch (RingBufferIllegalStateException e) { logger.error(e.getMessage()); response.setSuccess(false); response.setErrorMsg(e.getMessage()); responseCommand.setCode(CommandCode.SYSTEM_BUSY); } catch (Throwable e) { logger.error("logProcessor fail " + ExceptionUtils.getStackTrace(e)); response.setSuccess(false); response.setErrorMsg(e.getMessage()); responseCommand.setCode(CommandCode.SYSTEM_ERROR); } return responseCommand; } @Override public boolean reject() { try { for (DataQueue dataQueue : queueMap.values()) { dataQueue.canPublish(1000); } return false; } catch (RingBufferIllegalStateException e) { logger.error(e.getMessage()); return true; } } }, Executors.newCachedThreadPool()); remotingServer.start(); return remotingServer; } private ExecutorService getDefaultExecutors(int coreSize, AtomicBoolean rejector) { return DataPoolExecutors.newDefaultNoQueueExecutors(coreSize, coreSize * 2, 3, TimeUnit.SECONDS, RemotingThreadFactory. newThreadFactory("RemotingServerProcessThreadPoolExecutor-%d", false), new NettyRejectPolicy(rejector)); } public class NettyRejectPolicy implements RejectedExecutionHandler { private AtomicBoolean rejector; public NettyRejectPolicy(AtomicBoolean rejector) { this.rejector = rejector; } @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { rejector.set(true); } } /** * 停止获取数据 * * @throws Exception */ @Override public void stop() throws Exception { super.stop(); remotingServer.shutdown(); } /** * 检查当前是否在运行状态 */ @Override public boolean isRunning() { return super.isRunning(); } /** * 获取开放的端口信息 * * @return */ private Map<String, Integer> parsePort() { Map<String, Integer> parseMap = Maps.newHashMap(); try { String host = IpAddressUtils.getLocalAddress(); String rangeStr = inputPortMap != null ? inputPortMap.getOrDefault(host, pradarServerPorts) : pradarServerPorts; rangeStr = rangeStr.substring(rangeStr.indexOf("[") + 1, rangeStr.lastIndexOf("]")); logger.info("当前主机ip为 " + host + "发布的端口段为 " + rangeStr); String[] rangeSplit = rangeStr.split(","); parseMap.put(MIN, Integer.parseInt(rangeSplit[0])); parseMap.put(MAX, Integer.parseInt(rangeSplit[1])); } catch (Throwable e) { logger.error("parse port fail" + ExceptionUtils.getStackTrace(e)); throw new RuntimeException("解析端口失败"); } return parseMap; } @Override public void addObserver(LifecycleObserver<Supplier> observer) { super.addObserver(observer); } public void setPort(int port) { this.port = port; } public int getPort() { return port; } public void setInputPortMap(Map<String, String> inputPortMap) { this.inputPortMap = inputPortMap; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.tool; import java.util.TreeSet; import junit.framework.TestCase; import org.apache.hadoop.hive.ql.tools.LineageInfo; /** * TestLineageInfo. * */ public class TestLineageInfo extends TestCase { /** * Checks whether the test outputs match the expected outputs. * * @param lep * The LineageInfo extracted from the test * @param i * The set of input tables * @param o * The set of output tables */ private void checkOutput(LineageInfo lep, TreeSet<String> i, TreeSet<String> o) { if (!i.equals(lep.getInputTableList())) { fail("Input table not same"); } if (!o.equals(lep.getOutputTableList())) { fail("Output table not same"); } } public void testSimpleQuery() { LineageInfo lep = new LineageInfo(); try { lep.getLineageInfo("INSERT OVERWRITE TABLE dest1 partition (ds = '111') " + "SELECT s.* FROM srcpart TABLESAMPLE (BUCKET 1 OUT OF 1) s " + "WHERE s.ds='2008-04-08' and s.hr='11'"); TreeSet<String> i = new TreeSet<String>(); TreeSet<String> o = new TreeSet<String>(); i.add("srcpart"); o.add("dest1"); checkOutput(lep, i, o); } catch (Exception e) { e.printStackTrace(); fail("Failed"); } } public void testSimpleQuery2() { LineageInfo lep = new LineageInfo(); try { lep.getLineageInfo("FROM (FROM src select src.key, src.value " + "WHERE src.key < 10 UNION ALL FROM src SELECT src.* WHERE src.key > 10 ) unioninput " + "INSERT OVERWRITE DIRECTORY '../../../../build/contrib/hive/ql/test/data/warehouse/union.out' " + "SELECT unioninput.*"); TreeSet<String> i = new TreeSet<String>(); TreeSet<String> o = new TreeSet<String>(); i.add("src"); checkOutput(lep, i, o); } catch (Exception e) { e.printStackTrace(); fail("Failed"); } } public void testSimpleQuery3() { LineageInfo lep = new LineageInfo(); try { lep.getLineageInfo("FROM (FROM src select src.key, src.value " + "WHERE src.key < 10 UNION ALL FROM src1 SELECT src1.* WHERE src1.key > 10 ) unioninput " + "INSERT OVERWRITE DIRECTORY '../../../../build/contrib/hive/ql/test/data/warehouse/union.out' " + "SELECT unioninput.*"); TreeSet<String> i = new TreeSet<String>(); TreeSet<String> o = new TreeSet<String>(); i.add("src"); i.add("src1"); checkOutput(lep, i, o); } catch (Exception e) { e.printStackTrace(); fail("Failed"); } } public void testSimpleQuery4() { LineageInfo lep = new LineageInfo(); try { lep.getLineageInfo("FROM ( FROM ( FROM src1 src1 SELECT src1.key AS c1, src1.value AS c2 WHERE src1.key > 10 and src1.key < 20) a RIGHT OUTER JOIN ( FROM src2 src2 SELECT src2.key AS c3, src2.value AS c4 WHERE src2.key > 15 and src2.key < 25) b ON (a.c1 = b.c3) SELECT a.c1 AS c1, a.c2 AS c2, b.c3 AS c3, b.c4 AS c4) c SELECT c.c1, c.c2, c.c3, c.c4"); TreeSet<String> i = new TreeSet<String>(); TreeSet<String> o = new TreeSet<String>(); i.add("src1"); i.add("src2"); checkOutput(lep, i, o); } catch (Exception e) { e.printStackTrace(); fail("Failed"); } } public void testSimpleQuery5() { LineageInfo lep = new LineageInfo(); try { lep.getLineageInfo("insert overwrite table x select a.y, b.y " + "from a a full outer join b b on (a.x = b.y)"); TreeSet<String> i = new TreeSet<String>(); TreeSet<String> o = new TreeSet<String>(); i.add("a"); i.add("b"); o.add("x"); checkOutput(lep, i, o); } catch (Exception e) { e.printStackTrace(); fail("Failed"); } } }
/* * Copyright 2022.1-2022 * starwhale.ai All right reserved. This software is the confidential and proprietary information of * starwhale.ai ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into with starwhale.ai. */ package ai.starwhale.mlops.domain.swmp; import lombok.Builder; import lombok.Data; /** * Star Whale Model Package */ @Data @Builder public class SWModelPackage { Long id; /** * The storage path of the swmp, it could be a directory or a single file */ String path; }
/** */ package de.uka.ipd.sdq.dsexplore.qml.dimensions.presentation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.MissingResourceException; import java.util.StringTokenizer; import org.eclipse.emf.common.CommonPlugin; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.WizardNewFileCreationPage; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.ISetSelectionTarget; import de.uka.ipd.sdq.dsexplore.qml.dimensions.DimensionsFactory; import de.uka.ipd.sdq.dsexplore.qml.dimensions.DimensionsPackage; import de.uka.ipd.sdq.dsexplore.qml.dimensions.provider.DimensionsEditPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; /** * This is a simple wizard for creating a new model file. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class DimensionsModelWizard extends Wizard implements INewWizard { /** * The supported extensions for created files. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<String> FILE_EXTENSIONS = Collections.unmodifiableList(Arrays.asList(DimensionsEditorPlugin.INSTANCE.getString("_UI_DimensionsEditorFilenameExtensions").split("\\s*,\\s*"))); /** * A formatted list of supported file extensions, suitable for display. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final String FORMATTED_FILE_EXTENSIONS = DimensionsEditorPlugin.INSTANCE.getString("_UI_DimensionsEditorFilenameExtensions").replaceAll("\\s*,\\s*", ", "); /** * This caches an instance of the model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DimensionsPackage dimensionsPackage = DimensionsPackage.eINSTANCE; /** * This caches an instance of the model factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DimensionsFactory dimensionsFactory = dimensionsPackage.getDimensionsFactory(); /** * This is the file creation page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DimensionsModelWizardNewFileCreationPage newFileCreationPage; /** * This is the initial object creation page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DimensionsModelWizardInitialObjectCreationPage initialObjectCreationPage; /** * Remember the selection during initialization for populating the default container. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IStructuredSelection selection; /** * Remember the workbench during initialization. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IWorkbench workbench; /** * Caches the names of the types that can be created as the root object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected List<String> initialObjectNames; /** * This just records the information. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void init(IWorkbench workbench, IStructuredSelection selection) { this.workbench = workbench; this.selection = selection; setWindowTitle(DimensionsEditorPlugin.INSTANCE.getString("_UI_Wizard_label")); setDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE.getImageDescriptor(DimensionsEditorPlugin.INSTANCE.getImage("full/wizban/NewDimensions"))); } /** * Returns the names of the types that can be created as the root object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<String> getInitialObjectNames() { if (initialObjectNames == null) { initialObjectNames = new ArrayList<String>(); for (EClassifier eClassifier : dimensionsPackage.getEClassifiers()) { if (eClassifier instanceof EClass) { EClass eClass = (EClass)eClassifier; if (!eClass.isAbstract()) { initialObjectNames.add(eClass.getName()); } } } Collections.sort(initialObjectNames, CommonPlugin.INSTANCE.getComparator()); } return initialObjectNames; } /** * Create a new model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EObject createInitialModel() { EClass eClass = (EClass)dimensionsPackage.getEClassifier(initialObjectCreationPage.getInitialObjectName()); EObject rootObject = dimensionsFactory.create(eClass); return rootObject; } /** * Do the work after everything is specified. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean performFinish() { try { // Remember the file. // final IFile modelFile = getModelFile(); // Do the work within an operation. // WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { @Override protected void execute(IProgressMonitor progressMonitor) { try { // Create a resource set // ResourceSet resourceSet = new ResourceSetImpl(); // Get the URI of the model file. // URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true); // Create a resource for this file. // Resource resource = resourceSet.createResource(fileURI); // Add the initial model object to the contents. // EObject rootObject = createInitialModel(); if (rootObject != null) { resource.getContents().add(rootObject); } // Save the contents of the resource to the file system. // Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding()); resource.save(options); } catch (Exception exception) { DimensionsEditorPlugin.INSTANCE.log(exception); } finally { progressMonitor.done(); } } }; getContainer().run(false, false, operation); // Select the new file resource in the current view. // IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = workbenchWindow.getActivePage(); final IWorkbenchPart activePart = page.getActivePart(); if (activePart instanceof ISetSelectionTarget) { final ISelection targetSelection = new StructuredSelection(modelFile); getShell().getDisplay().asyncExec (new Runnable() { public void run() { ((ISetSelectionTarget)activePart).selectReveal(targetSelection); } }); } // Open an editor on the new file. // try { page.openEditor (new FileEditorInput(modelFile), workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId()); } catch (PartInitException exception) { MessageDialog.openError(workbenchWindow.getShell(), DimensionsEditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage()); return false; } return true; } catch (Exception exception) { DimensionsEditorPlugin.INSTANCE.log(exception); return false; } } /** * This is the one page of the wizard. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class DimensionsModelWizardNewFileCreationPage extends WizardNewFileCreationPage { /** * Pass in the selection. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DimensionsModelWizardNewFileCreationPage(String pageId, IStructuredSelection selection) { super(pageId, selection); } /** * The framework calls this to see if the file is correct. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected boolean validatePage() { if (super.validatePage()) { String extension = new Path(getFileName()).getFileExtension(); if (extension == null || !FILE_EXTENSIONS.contains(extension)) { String key = FILE_EXTENSIONS.size() > 1 ? "_WARN_FilenameExtensions" : "_WARN_FilenameExtension"; setErrorMessage(DimensionsEditorPlugin.INSTANCE.getString(key, new Object [] { FORMATTED_FILE_EXTENSIONS })); return false; } return true; } return false; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IFile getModelFile() { return ResourcesPlugin.getWorkspace().getRoot().getFile(getContainerFullPath().append(getFileName())); } } /** * This is the page where the type of object to create is selected. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class DimensionsModelWizardInitialObjectCreationPage extends WizardPage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Combo initialObjectField; /** * @generated * <!-- begin-user-doc --> * <!-- end-user-doc --> */ protected List<String> encodings; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Combo encodingField; /** * Pass in the selection. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DimensionsModelWizardInitialObjectCreationPage(String pageId) { super(pageId); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); { GridLayout layout = new GridLayout(); layout.numColumns = 1; layout.verticalSpacing = 12; composite.setLayout(layout); GridData data = new GridData(); data.verticalAlignment = GridData.FILL; data.grabExcessVerticalSpace = true; data.horizontalAlignment = GridData.FILL; composite.setLayoutData(data); } Label containerLabel = new Label(composite, SWT.LEFT); { containerLabel.setText(DimensionsEditorPlugin.INSTANCE.getString("_UI_ModelObject")); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; containerLabel.setLayoutData(data); } initialObjectField = new Combo(composite, SWT.BORDER); { GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; initialObjectField.setLayoutData(data); } for (String objectName : getInitialObjectNames()) { initialObjectField.add(getLabel(objectName)); } if (initialObjectField.getItemCount() == 1) { initialObjectField.select(0); } initialObjectField.addModifyListener(validator); Label encodingLabel = new Label(composite, SWT.LEFT); { encodingLabel.setText(DimensionsEditorPlugin.INSTANCE.getString("_UI_XMLEncoding")); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; encodingLabel.setLayoutData(data); } encodingField = new Combo(composite, SWT.BORDER); { GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; encodingField.setLayoutData(data); } for (String encoding : getEncodings()) { encodingField.add(encoding); } encodingField.select(0); encodingField.addModifyListener(validator); setPageComplete(validatePage()); setControl(composite); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ModifyListener validator = new ModifyListener() { public void modifyText(ModifyEvent e) { setPageComplete(validatePage()); } }; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected boolean validatePage() { return getInitialObjectName() != null && getEncodings().contains(encodingField.getText()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { if (initialObjectField.getItemCount() == 1) { initialObjectField.clearSelection(); encodingField.setFocus(); } else { encodingField.clearSelection(); initialObjectField.setFocus(); } } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getInitialObjectName() { String label = initialObjectField.getText(); for (String name : getInitialObjectNames()) { if (getLabel(name).equals(label)) { return name; } } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getEncoding() { return encodingField.getText(); } /** * Returns the label for the specified type name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected String getLabel(String typeName) { try { return DimensionsEditPlugin.INSTANCE.getString("_UI_" + typeName + "_type"); } catch(MissingResourceException mre) { DimensionsEditorPlugin.INSTANCE.log(mre); } return typeName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<String> getEncodings() { if (encodings == null) { encodings = new ArrayList<String>(); for (StringTokenizer stringTokenizer = new StringTokenizer(DimensionsEditorPlugin.INSTANCE.getString("_UI_XMLEncodingChoices")); stringTokenizer.hasMoreTokens(); ) { encodings.add(stringTokenizer.nextToken()); } } return encodings; } } /** * The framework calls this to create the contents of the wizard. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void addPages() { // Create a page, set the title, and the initial model file name. // newFileCreationPage = new DimensionsModelWizardNewFileCreationPage("Whatever", selection); newFileCreationPage.setTitle(DimensionsEditorPlugin.INSTANCE.getString("_UI_DimensionsModelWizard_label")); newFileCreationPage.setDescription(DimensionsEditorPlugin.INSTANCE.getString("_UI_DimensionsModelWizard_description")); newFileCreationPage.setFileName(DimensionsEditorPlugin.INSTANCE.getString("_UI_DimensionsEditorFilenameDefaultBase") + "." + FILE_EXTENSIONS.get(0)); addPage(newFileCreationPage); // Try and get the resource selection to determine a current directory for the file dialog. // if (selection != null && !selection.isEmpty()) { // Get the resource... // Object selectedElement = selection.iterator().next(); if (selectedElement instanceof IResource) { // Get the resource parent, if its a file. // IResource selectedResource = (IResource)selectedElement; if (selectedResource.getType() == IResource.FILE) { selectedResource = selectedResource.getParent(); } // This gives us a directory... // if (selectedResource instanceof IFolder || selectedResource instanceof IProject) { // Set this for the container. // newFileCreationPage.setContainerFullPath(selectedResource.getFullPath()); // Make up a unique new name here. // String defaultModelBaseFilename = DimensionsEditorPlugin.INSTANCE.getString("_UI_DimensionsEditorFilenameDefaultBase"); String defaultModelFilenameExtension = FILE_EXTENSIONS.get(0); String modelFilename = defaultModelBaseFilename + "." + defaultModelFilenameExtension; for (int i = 1; ((IContainer)selectedResource).findMember(modelFilename) != null; ++i) { modelFilename = defaultModelBaseFilename + i + "." + defaultModelFilenameExtension; } newFileCreationPage.setFileName(modelFilename); } } } initialObjectCreationPage = new DimensionsModelWizardInitialObjectCreationPage("Whatever2"); initialObjectCreationPage.setTitle(DimensionsEditorPlugin.INSTANCE.getString("_UI_DimensionsModelWizard_label")); initialObjectCreationPage.setDescription(DimensionsEditorPlugin.INSTANCE.getString("_UI_Wizard_initial_object_description")); addPage(initialObjectCreationPage); } /** * Get the file from the page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IFile getModelFile() { return newFileCreationPage.getModelFile(); } }
package garbagetown.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.inject.Inject; /** * Created by garbagetown on 10/25/15. */ @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Inject UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/tours/*/reserve", "/reservations/**") .authenticated(); http.formLogin() .loginPage("/login") .loginProcessingUrl("/login/authenticate") .usernameParameter("username") .passwordParameter("password"); http.logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/") .deleteCookies("JSESSIONID") .invalidateHttpSession(true); http.csrf().disable(); http.headers().frameOptions().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService) .passwordEncoder(new BCryptPasswordEncoder()); } }
package com.neverpile.common.condition; import com.neverpile.common.specifier.Specifier; /** * An {@link ConditionContext} provides access to contextual information that can be used in * access decisions. The context information is managed as a tree of values addressed by keys which * follow the naming conventions used by Java properties, i.e. using dots as level separators. * <p> * The sole responsibility of this interface is the resolution of value keys into context values. * The details of this resolution process are implementation-dependent. */ public interface ConditionContext { /** * Return the value associated with the given key or <code>null</code> if the value cannot be * resolved. * * @param key the value key * @return the value or <code>null</code> */ Object resolveValue(Specifier key); /** * Mainly for unit testing: resolve a value from a string-based key instead of a parsed specifier. * * @param key the value key * @return the value or <code>null</code> */ default Object resolveValue(final String key) { return resolveValue(Specifier.from(key)); } }
/* * 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.flink.training.exercises.longrides; import org.apache.flink.api.common.JobExecutionResult; import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration; import org.apache.flink.streaming.api.functions.source.SourceFunction; import org.apache.flink.test.util.MiniClusterWithClientResource; import org.apache.flink.training.exercises.common.datatypes.TaxiRide; import org.apache.flink.training.exercises.testing.ComposedPipeline; import org.apache.flink.training.exercises.testing.ExecutablePipeline; import org.apache.flink.training.exercises.testing.ParallelTestSource; import org.apache.flink.training.exercises.testing.TestSink; import org.apache.flink.training.solutions.longrides.LongRidesSolution; import org.junit.ClassRule; import org.junit.Test; import java.util.List; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; public class LongRidesIntegrationTest extends LongRidesTestBase { private static final int PARALLELISM = 2; /** This isn't necessary, but speeds up the tests. */ @ClassRule public static MiniClusterWithClientResource flinkCluster = new MiniClusterWithClientResource( new MiniClusterResourceConfiguration.Builder() .setNumberSlotsPerTaskManager(PARALLELISM) .setNumberTaskManagers(1) .build()); @Test public void shortRide() throws Exception { TaxiRide rideStarted = startRide(1, BEGINNING); TaxiRide endedOneMinLater = endRide(rideStarted, ONE_MINUTE_LATER); ParallelTestSource<TaxiRide> source = new ParallelTestSource<>(rideStarted, endedOneMinLater); assertThat(results(source)).isEmpty(); } @Test public void shortRideOutOfOrder() throws Exception { TaxiRide rideStarted = startRide(1, BEGINNING); TaxiRide endedOneMinLater = endRide(rideStarted, ONE_MINUTE_LATER); ParallelTestSource<TaxiRide> source = new ParallelTestSource<>(endedOneMinLater, rideStarted); assertThat(results(source)).isEmpty(); } @Test public void multipleRides() throws Exception { TaxiRide longRideWithoutEnd = startRide(1, BEGINNING); TaxiRide twoHourRide = startRide(2, BEGINNING); TaxiRide otherLongRide = startRide(3, ONE_MINUTE_LATER); TaxiRide shortRide = startRide(4, ONE_HOUR_LATER); TaxiRide shortRideEnded = endRide(shortRide, TWO_HOURS_LATER); TaxiRide twoHourRideEnded = endRide(twoHourRide, BEGINNING); TaxiRide otherLongRideEnded = endRide(otherLongRide, THREE_HOURS_LATER); ParallelTestSource<TaxiRide> source = new ParallelTestSource<>( longRideWithoutEnd, twoHourRide, otherLongRide, shortRide, shortRideEnded, twoHourRideEnded, otherLongRideEnded); assertThat(results(source)) .containsExactlyInAnyOrder(longRideWithoutEnd.rideId, otherLongRide.rideId); } private static final ExecutablePipeline<TaxiRide, Long> exercise = (source, sink) -> new LongRidesExercise(source, sink).execute(); private static final ExecutablePipeline<TaxiRide, Long> solution = (source, sink) -> new LongRidesSolution(source, sink).execute(); protected List<Long> results(SourceFunction<TaxiRide> source) throws Exception { TestSink<Long> sink = new TestSink<>(); ComposedPipeline<TaxiRide, Long> longRidesPipeline = new ComposedPipeline<>(exercise, solution); JobExecutionResult jobResult = longRidesPipeline.execute(source, sink); return sink.getResults(jobResult); } }
package io.cloudevents.kafka.impl; import io.cloudevents.SpecVersion; import org.apache.kafka.common.header.Headers; public final class KafkaSerializerMessageVisitorImpl extends BaseKafkaMessageVisitorImpl<KafkaSerializerMessageVisitorImpl, byte[]> { public KafkaSerializerMessageVisitorImpl(Headers headers) { super(headers); } @Override public KafkaSerializerMessageVisitorImpl createBinaryMessageVisitor(SpecVersion version) { this.setAttribute("specversion", version.toString()); return this; } @Override public byte[] end() { return this.value; } }
/* * Licensed to Diennea S.r.l. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Diennea S.r.l. 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 blazingcache.metrics; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import blazingcache.client.CacheClient; import blazingcache.network.ServerHostData; import blazingcache.network.netty.NettyCacheServerLocator; import blazingcache.server.CacheServer; import java.nio.charset.StandardCharsets; import org.junit.Test; /** * * @author dennis.mercuriali */ public class MetricsTest { @Test public void basicTest() throws Exception { TestMetricsManager metricsMan1 = new TestMetricsManager(); TestMetricsManager metricsMan2 = new TestMetricsManager(); byte[] data = "testdata".getBytes(StandardCharsets.UTF_8); ServerHostData serverHostData = new ServerHostData("localhost", 1234, "test", false, null); try (CacheServer cacheServer = new CacheServer("mysecret", serverHostData)) { cacheServer.setClientFetchTimeout(1000); cacheServer.start(); try (CacheClient client1 = CacheClient.newBuilder() .serverLocator(new NettyCacheServerLocator(serverHostData)) .clientId("client1") .sharedSecret("mysecret") .metricsProvider(metricsMan1.getProvider()) .build(); CacheClient client2 = CacheClient.newBuilder() .serverLocator(new NettyCacheServerLocator(serverHostData)) .clientId("client2") .sharedSecret("mysecret") .metricsProvider(metricsMan2.getProvider()) .build();) { client1.start(); client2.start(); assertTrue(client1.waitForConnection(10000)); assertTrue(client2.waitForConnection(10000)); assertNull(client1.get("foo")); assertNull(client2.get("foo")); assertThat(metricsMan1.getGauges().get("blazingcache.client.hits").get(), is(0L)); assertThat(metricsMan1.getGauges().get("blazingcache.client.gets").get(), is(1L)); assertThat(metricsMan2.getGauges().get("blazingcache.client.hits").get(), is(0L)); assertThat(metricsMan2.getGauges().get("blazingcache.client.gets").get(), is(1L)); client1.load("foo", data, 0); assertNotNull(client2.fetch("foo")); assertThat(metricsMan1.getGauges().get("blazingcache.client.hits").get(), is(0L)); assertThat(metricsMan1.getGauges().get("blazingcache.client.gets").get(), is(1L)); assertThat(metricsMan1.getGauges().get("blazingcache.client.loads").get(), is(1L)); assertThat(metricsMan1.getGauges().get("blazingcache.client.memory.actualusage").get(), is((long) data.length)); assertThat(metricsMan2.getGauges().get("blazingcache.client.hits").get(), is(1L)); assertThat(metricsMan2.getGauges().get("blazingcache.client.gets").get(), is(1L)); assertThat(metricsMan2.getGauges().get("blazingcache.client.fetches").get(), is(1L)); assertThat(metricsMan2.getGauges().get("blazingcache.client.memory.actualusage").get(), is((long) data.length)); client1.load("bar", data, 0); assertThat(metricsMan1.getGauges().get("blazingcache.client.loads").get(), is(2L)); assertThat(metricsMan1.getGauges().get("blazingcache.client.loads").get("foo"), is(1L)); assertThat(metricsMan1.getGauges().get("blazingcache.client.loads").get("bar"), is(1L)); assertThat(metricsMan1.getGauges().get("blazingcache.client.memory.actualusage").get(), is((long) data.length * 2)); assertThat(metricsMan1.getGauges().get("blazingcache.client.memory.actualusage").get("foo"), is((long) data.length)); assertThat(metricsMan1.getGauges().get("blazingcache.client.memory.actualusage").get("bar"), is((long) data.length)); } } } }
import java.util.Random; public class Ex32array { public static void main(String[] args) { // TODO Auto-generated method stub Random ran=new Random(); int a[][]=new int[5][7]; int a1[][]=new int[7][5]; for(int i=0;i<5;i++){ for(int j=0;j<7;j++){ a[i][j]=ran.nextInt(101); a1[j][i]=a[i][j]; System.out.print(a1[j][i]+" "); }System.out.println(); } } }
package io.onedev.server.web.editable.servicelocator; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.event.IEvent; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable; import org.apache.wicket.extensions.markup.html.repeater.data.table.HeadersToolbar; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.NoRecordsToolbar; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.IDataProvider; import org.apache.wicket.markup.repeater.data.ListDataProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.util.convert.ConversionException; import io.onedev.server.buildspec.BuildSpec; import io.onedev.server.buildspec.BuildSpecAware; import io.onedev.server.buildspec.job.Job; import io.onedev.server.buildspec.job.JobAware; import io.onedev.server.buildspec.param.spec.ParamSpec; import io.onedev.server.model.support.administration.jobexecutor.ServiceLocator; import io.onedev.server.web.behavior.NoRecordsBehavior; import io.onedev.server.web.behavior.sortable.SortBehavior; import io.onedev.server.web.behavior.sortable.SortPosition; import io.onedev.server.web.component.modal.ModalLink; import io.onedev.server.web.component.modal.ModalPanel; import io.onedev.server.web.component.svg.SpriteImage; import io.onedev.server.web.editable.EmptyValueLabel; import io.onedev.server.web.editable.PropertyDescriptor; import io.onedev.server.web.editable.PropertyEditor; import io.onedev.server.web.editable.PropertyUpdating; @SuppressWarnings("serial") class ServiceLocatorListEditPanel extends PropertyEditor<List<Serializable>> { private final List<ServiceLocator> locators; public ServiceLocatorListEditPanel(String id, PropertyDescriptor propertyDescriptor, IModel<List<Serializable>> model) { super(id, propertyDescriptor, model); locators = new ArrayList<>(); for (Serializable each: model.getObject()) { locators.add((ServiceLocator) each); } } private BuildSpec getBuildSpec() { BuildSpecAware buildSpecAware = findParent(BuildSpecAware.class); if (buildSpecAware != null) return buildSpecAware.getBuildSpec(); else return null; } private Job getJob() { JobAware jobAware = findParent(JobAware.class); if (jobAware != null) return jobAware.getJob(); else return null; } @Override protected void onInitialize() { super.onInitialize(); add(new ModalLink("addNew") { @Override protected Component newContent(String id, ModalPanel modal) { return new ServiceLocatorEditPanel(id, locators, -1) { @Override protected void onCancel(AjaxRequestTarget target) { modal.close(); } @Override protected void onSave(AjaxRequestTarget target) { markFormDirty(target); modal.close(); onPropertyUpdating(target); target.add(ServiceLocatorListEditPanel.this); } @Override public BuildSpec getBuildSpec() { return ServiceLocatorListEditPanel.this.getBuildSpec(); } @Override public Job getJob() { return ServiceLocatorListEditPanel.this.getJob(); } @Override public List<ParamSpec> getParamSpecs() { return getJob()!=null? getJob().getParamSpecs(): null; } }; } }); List<IColumn<ServiceLocator, Void>> columns = new ArrayList<>(); columns.add(new AbstractColumn<ServiceLocator, Void>(Model.of("")) { @Override public void populateItem(Item<ICellPopulator<ServiceLocator>> cellItem, String componentId, IModel<ServiceLocator> rowModel) { cellItem.add(new SpriteImage(componentId, "grip") { @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.setName("svg"); tag.put("class", "icon drag-indicator"); } }); } @Override public String getCssClass() { return "minimum actions"; } }); columns.add(new AbstractColumn<ServiceLocator, Void>(Model.of("Applicable Names")) { @Override public void populateItem(Item<ICellPopulator<ServiceLocator>> cellItem, String componentId, IModel<ServiceLocator> rowModel) { if (rowModel.getObject().getServiceNames() != null) { cellItem.add(new Label(componentId, rowModel.getObject().getServiceNames())); } else { try { cellItem.add(new EmptyValueLabel(componentId, ServiceLocator.class.getDeclaredMethod("getServiceNames"))); } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } } } }); columns.add(new AbstractColumn<ServiceLocator, Void>(Model.of("Applicable Images")) { @Override public void populateItem(Item<ICellPopulator<ServiceLocator>> cellItem, String componentId, IModel<ServiceLocator> rowModel) { if (rowModel.getObject().getServiceImages() != null) { cellItem.add(new Label(componentId, rowModel.getObject().getServiceImages())); } else { try { cellItem.add(new EmptyValueLabel(componentId, ServiceLocator.class.getDeclaredMethod("getServiceImages"))); } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } } } }); columns.add(new AbstractColumn<ServiceLocator, Void>(Model.of("#Node Selector Entries")) { @Override public void populateItem(Item<ICellPopulator<ServiceLocator>> cellItem, String componentId, IModel<ServiceLocator> rowModel) { cellItem.add(new Label(componentId, rowModel.getObject().getNodeSelector().size())); } }); columns.add(new AbstractColumn<ServiceLocator, Void>(Model.of("")) { @Override public void populateItem(Item<ICellPopulator<ServiceLocator>> cellItem, String componentId, IModel<ServiceLocator> rowModel) { Fragment fragment = new Fragment(componentId, "actionColumnFrag", ServiceLocatorListEditPanel.this); fragment.add(new ModalLink("edit") { @Override protected Component newContent(String id, ModalPanel modal) { return new ServiceLocatorEditPanel(id, locators, cellItem.findParent(Item.class).getIndex()) { @Override protected void onCancel(AjaxRequestTarget target) { modal.close(); } @Override protected void onSave(AjaxRequestTarget target) { markFormDirty(target); modal.close(); onPropertyUpdating(target); target.add(ServiceLocatorListEditPanel.this); } @Override public BuildSpec getBuildSpec() { return ServiceLocatorListEditPanel.this.getBuildSpec(); } @Override public Job getJob() { return ServiceLocatorListEditPanel.this.getJob(); } @Override public List<ParamSpec> getParamSpecs() { return getJob()!=null? getJob().getParamSpecs(): null; } }; } }); fragment.add(new AjaxLink<Void>("delete") { @Override public void onClick(AjaxRequestTarget target) { markFormDirty(target); locators.remove(rowModel.getObject()); onPropertyUpdating(target); target.add(ServiceLocatorListEditPanel.this); } }); cellItem.add(fragment); } @Override public String getCssClass() { return "actions"; } }); IDataProvider<ServiceLocator> dataProvider = new ListDataProvider<ServiceLocator>() { @Override protected List<ServiceLocator> getData() { return locators; } }; DataTable<ServiceLocator, Void> dataTable; add(dataTable = new DataTable<ServiceLocator, Void>("locators", columns, dataProvider, Integer.MAX_VALUE)); dataTable.addTopToolbar(new HeadersToolbar<Void>(dataTable, null)); dataTable.addBottomToolbar(new NoRecordsToolbar(dataTable)); dataTable.add(new NoRecordsBehavior()); dataTable.add(new SortBehavior() { @Override protected void onSort(AjaxRequestTarget target, SortPosition from, SortPosition to) { int fromIndex = from.getItemIndex(); int toIndex = to.getItemIndex(); if (fromIndex < toIndex) { for (int i=0; i<toIndex-fromIndex; i++) Collections.swap(locators, fromIndex+i, fromIndex+i+1); } else { for (int i=0; i<fromIndex-toIndex; i++) Collections.swap(locators, fromIndex-i, fromIndex-i-1); } onPropertyUpdating(target); target.add(ServiceLocatorListEditPanel.this); } }.sortable("tbody")); } @Override public void onEvent(IEvent<?> event) { super.onEvent(event); if (event.getPayload() instanceof PropertyUpdating) { event.stop(); onPropertyUpdating(((PropertyUpdating)event.getPayload()).getHandler()); } } @Override protected List<Serializable> convertInputToValue() throws ConversionException { List<Serializable> value = new ArrayList<>(); for (ServiceLocator each: locators) value.add(each); return value; } @Override public boolean needExplicitSubmit() { return true; } }
/* * Copyright (c) 2018, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.mesh.models; import android.os.Parcel; @SuppressWarnings("WeakerAccess") public class ConfigurationServerModel extends SigModel { public static final Creator<ConfigurationServerModel> CREATOR = new Creator<ConfigurationServerModel>() { @Override public ConfigurationServerModel createFromParcel(final Parcel source) { return new ConfigurationServerModel(source); } @Override public ConfigurationServerModel[] newArray(final int size) { return new ConfigurationServerModel[size]; } }; public ConfigurationServerModel(final int modelId) { super(modelId); } private ConfigurationServerModel(Parcel in){ super(in); } @Override public String getModelName() { return "Configuration Server"; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { super.parcelMeshModel(dest, flags); } }
package com.webstore.models; import java.util.HashSet; import java.util.Set; import javax.persistence.*; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false, updatable = false) private Long id; // Username with unique constraint @Column(name = "username", nullable = false, unique = true) private String username; @Column(name = "password", nullable = false) private String password; @Column(name = "role", nullable = false) private String role; public User() { } public User(String username, String password, String role) { super(); this.username = username; this.password = password; this.role = role; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
package com.dumai.xianjindai.view.xrecyclerview; /** * Created by jianghejie on 15/11/22. */ interface BaseRefreshHeader { int STATE_NORMAL = 0; int STATE_RELEASE_TO_REFRESH = 1; int STATE_REFRESHING = 2; int STATE_DONE = 3; void onMove(float delta); boolean releaseAction(); void refreshComplete(); }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/chromeos/moblab/v1beta1/build_service.proto package com.google.chromeos.moblab.v1beta1; /** * <pre> * Response message for listing models. * </pre> * * Protobuf type {@code google.chromeos.moblab.v1beta1.ListModelsResponse} */ public final class ListModelsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.chromeos.moblab.v1beta1.ListModelsResponse) ListModelsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListModelsResponse.newBuilder() to construct. private ListModelsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListModelsResponse() { models_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new ListModelsResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ListModelsResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { models_ = new java.util.ArrayList<com.google.chromeos.moblab.v1beta1.Model>(); mutable_bitField0_ |= 0x00000001; } models_.add( input.readMessage(com.google.chromeos.moblab.v1beta1.Model.parser(), extensionRegistry)); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); nextPageToken_ = s; break; } case 24: { totalSize_ = input.readInt32(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { models_ = java.util.Collections.unmodifiableList(models_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.chromeos.moblab.v1beta1.BuildServiceProto.internal_static_google_chromeos_moblab_v1beta1_ListModelsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.chromeos.moblab.v1beta1.BuildServiceProto.internal_static_google_chromeos_moblab_v1beta1_ListModelsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.chromeos.moblab.v1beta1.ListModelsResponse.class, com.google.chromeos.moblab.v1beta1.ListModelsResponse.Builder.class); } public static final int MODELS_FIELD_NUMBER = 1; private java.util.List<com.google.chromeos.moblab.v1beta1.Model> models_; /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ @java.lang.Override public java.util.List<com.google.chromeos.moblab.v1beta1.Model> getModelsList() { return models_; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.chromeos.moblab.v1beta1.ModelOrBuilder> getModelsOrBuilderList() { return models_; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ @java.lang.Override public int getModelsCount() { return models_.size(); } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ @java.lang.Override public com.google.chromeos.moblab.v1beta1.Model getModels(int index) { return models_.get(index); } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ @java.lang.Override public com.google.chromeos.moblab.v1beta1.ModelOrBuilder getModelsOrBuilder( int index) { return models_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; private volatile java.lang.Object nextPageToken_; /** * <pre> * Token to retrieve the next page of models. If this field is omitted, there * are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * <pre> * Token to retrieve the next page of models. If this field is omitted, there * are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TOTAL_SIZE_FIELD_NUMBER = 3; private int totalSize_; /** * <pre> * Total number of models. * </pre> * * <code>int32 total_size = 3;</code> * @return The totalSize. */ @java.lang.Override public int getTotalSize() { return totalSize_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < models_.size(); i++) { output.writeMessage(1, models_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } if (totalSize_ != 0) { output.writeInt32(3, totalSize_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < models_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, models_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } if (totalSize_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, totalSize_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.chromeos.moblab.v1beta1.ListModelsResponse)) { return super.equals(obj); } com.google.chromeos.moblab.v1beta1.ListModelsResponse other = (com.google.chromeos.moblab.v1beta1.ListModelsResponse) obj; if (!getModelsList() .equals(other.getModelsList())) return false; if (!getNextPageToken() .equals(other.getNextPageToken())) return false; if (getTotalSize() != other.getTotalSize()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getModelsCount() > 0) { hash = (37 * hash) + MODELS_FIELD_NUMBER; hash = (53 * hash) + getModelsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (37 * hash) + TOTAL_SIZE_FIELD_NUMBER; hash = (53 * hash) + getTotalSize(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.chromeos.moblab.v1beta1.ListModelsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Response message for listing models. * </pre> * * Protobuf type {@code google.chromeos.moblab.v1beta1.ListModelsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.chromeos.moblab.v1beta1.ListModelsResponse) com.google.chromeos.moblab.v1beta1.ListModelsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.chromeos.moblab.v1beta1.BuildServiceProto.internal_static_google_chromeos_moblab_v1beta1_ListModelsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.chromeos.moblab.v1beta1.BuildServiceProto.internal_static_google_chromeos_moblab_v1beta1_ListModelsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.chromeos.moblab.v1beta1.ListModelsResponse.class, com.google.chromeos.moblab.v1beta1.ListModelsResponse.Builder.class); } // Construct using com.google.chromeos.moblab.v1beta1.ListModelsResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getModelsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (modelsBuilder_ == null) { models_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { modelsBuilder_.clear(); } nextPageToken_ = ""; totalSize_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.chromeos.moblab.v1beta1.BuildServiceProto.internal_static_google_chromeos_moblab_v1beta1_ListModelsResponse_descriptor; } @java.lang.Override public com.google.chromeos.moblab.v1beta1.ListModelsResponse getDefaultInstanceForType() { return com.google.chromeos.moblab.v1beta1.ListModelsResponse.getDefaultInstance(); } @java.lang.Override public com.google.chromeos.moblab.v1beta1.ListModelsResponse build() { com.google.chromeos.moblab.v1beta1.ListModelsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.chromeos.moblab.v1beta1.ListModelsResponse buildPartial() { com.google.chromeos.moblab.v1beta1.ListModelsResponse result = new com.google.chromeos.moblab.v1beta1.ListModelsResponse(this); int from_bitField0_ = bitField0_; if (modelsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { models_ = java.util.Collections.unmodifiableList(models_); bitField0_ = (bitField0_ & ~0x00000001); } result.models_ = models_; } else { result.models_ = modelsBuilder_.build(); } result.nextPageToken_ = nextPageToken_; result.totalSize_ = totalSize_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.chromeos.moblab.v1beta1.ListModelsResponse) { return mergeFrom((com.google.chromeos.moblab.v1beta1.ListModelsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.chromeos.moblab.v1beta1.ListModelsResponse other) { if (other == com.google.chromeos.moblab.v1beta1.ListModelsResponse.getDefaultInstance()) return this; if (modelsBuilder_ == null) { if (!other.models_.isEmpty()) { if (models_.isEmpty()) { models_ = other.models_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureModelsIsMutable(); models_.addAll(other.models_); } onChanged(); } } else { if (!other.models_.isEmpty()) { if (modelsBuilder_.isEmpty()) { modelsBuilder_.dispose(); modelsBuilder_ = null; models_ = other.models_; bitField0_ = (bitField0_ & ~0x00000001); modelsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getModelsFieldBuilder() : null; } else { modelsBuilder_.addAllMessages(other.models_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; onChanged(); } if (other.getTotalSize() != 0) { setTotalSize(other.getTotalSize()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.chromeos.moblab.v1beta1.ListModelsResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.chromeos.moblab.v1beta1.ListModelsResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.chromeos.moblab.v1beta1.Model> models_ = java.util.Collections.emptyList(); private void ensureModelsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { models_ = new java.util.ArrayList<com.google.chromeos.moblab.v1beta1.Model>(models_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.chromeos.moblab.v1beta1.Model, com.google.chromeos.moblab.v1beta1.Model.Builder, com.google.chromeos.moblab.v1beta1.ModelOrBuilder> modelsBuilder_; /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public java.util.List<com.google.chromeos.moblab.v1beta1.Model> getModelsList() { if (modelsBuilder_ == null) { return java.util.Collections.unmodifiableList(models_); } else { return modelsBuilder_.getMessageList(); } } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public int getModelsCount() { if (modelsBuilder_ == null) { return models_.size(); } else { return modelsBuilder_.getCount(); } } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public com.google.chromeos.moblab.v1beta1.Model getModels(int index) { if (modelsBuilder_ == null) { return models_.get(index); } else { return modelsBuilder_.getMessage(index); } } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder setModels( int index, com.google.chromeos.moblab.v1beta1.Model value) { if (modelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureModelsIsMutable(); models_.set(index, value); onChanged(); } else { modelsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder setModels( int index, com.google.chromeos.moblab.v1beta1.Model.Builder builderForValue) { if (modelsBuilder_ == null) { ensureModelsIsMutable(); models_.set(index, builderForValue.build()); onChanged(); } else { modelsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder addModels(com.google.chromeos.moblab.v1beta1.Model value) { if (modelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureModelsIsMutable(); models_.add(value); onChanged(); } else { modelsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder addModels( int index, com.google.chromeos.moblab.v1beta1.Model value) { if (modelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureModelsIsMutable(); models_.add(index, value); onChanged(); } else { modelsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder addModels( com.google.chromeos.moblab.v1beta1.Model.Builder builderForValue) { if (modelsBuilder_ == null) { ensureModelsIsMutable(); models_.add(builderForValue.build()); onChanged(); } else { modelsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder addModels( int index, com.google.chromeos.moblab.v1beta1.Model.Builder builderForValue) { if (modelsBuilder_ == null) { ensureModelsIsMutable(); models_.add(index, builderForValue.build()); onChanged(); } else { modelsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder addAllModels( java.lang.Iterable<? extends com.google.chromeos.moblab.v1beta1.Model> values) { if (modelsBuilder_ == null) { ensureModelsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, models_); onChanged(); } else { modelsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder clearModels() { if (modelsBuilder_ == null) { models_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { modelsBuilder_.clear(); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public Builder removeModels(int index) { if (modelsBuilder_ == null) { ensureModelsIsMutable(); models_.remove(index); onChanged(); } else { modelsBuilder_.remove(index); } return this; } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public com.google.chromeos.moblab.v1beta1.Model.Builder getModelsBuilder( int index) { return getModelsFieldBuilder().getBuilder(index); } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public com.google.chromeos.moblab.v1beta1.ModelOrBuilder getModelsOrBuilder( int index) { if (modelsBuilder_ == null) { return models_.get(index); } else { return modelsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public java.util.List<? extends com.google.chromeos.moblab.v1beta1.ModelOrBuilder> getModelsOrBuilderList() { if (modelsBuilder_ != null) { return modelsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(models_); } } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public com.google.chromeos.moblab.v1beta1.Model.Builder addModelsBuilder() { return getModelsFieldBuilder().addBuilder( com.google.chromeos.moblab.v1beta1.Model.getDefaultInstance()); } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public com.google.chromeos.moblab.v1beta1.Model.Builder addModelsBuilder( int index) { return getModelsFieldBuilder().addBuilder( index, com.google.chromeos.moblab.v1beta1.Model.getDefaultInstance()); } /** * <pre> * The list of models. * </pre> * * <code>repeated .google.chromeos.moblab.v1beta1.Model models = 1;</code> */ public java.util.List<com.google.chromeos.moblab.v1beta1.Model.Builder> getModelsBuilderList() { return getModelsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.chromeos.moblab.v1beta1.Model, com.google.chromeos.moblab.v1beta1.Model.Builder, com.google.chromeos.moblab.v1beta1.ModelOrBuilder> getModelsFieldBuilder() { if (modelsBuilder_ == null) { modelsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.chromeos.moblab.v1beta1.Model, com.google.chromeos.moblab.v1beta1.Model.Builder, com.google.chromeos.moblab.v1beta1.ModelOrBuilder>( models_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); models_ = null; } return modelsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * <pre> * Token to retrieve the next page of models. If this field is omitted, there * are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Token to retrieve the next page of models. If this field is omitted, there * are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Token to retrieve the next page of models. If this field is omitted, there * are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken( java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; onChanged(); return this; } /** * <pre> * Token to retrieve the next page of models. If this field is omitted, there * are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); onChanged(); return this; } /** * <pre> * Token to retrieve the next page of models. If this field is omitted, there * are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; onChanged(); return this; } private int totalSize_ ; /** * <pre> * Total number of models. * </pre> * * <code>int32 total_size = 3;</code> * @return The totalSize. */ @java.lang.Override public int getTotalSize() { return totalSize_; } /** * <pre> * Total number of models. * </pre> * * <code>int32 total_size = 3;</code> * @param value The totalSize to set. * @return This builder for chaining. */ public Builder setTotalSize(int value) { totalSize_ = value; onChanged(); return this; } /** * <pre> * Total number of models. * </pre> * * <code>int32 total_size = 3;</code> * @return This builder for chaining. */ public Builder clearTotalSize() { totalSize_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.chromeos.moblab.v1beta1.ListModelsResponse) } // @@protoc_insertion_point(class_scope:google.chromeos.moblab.v1beta1.ListModelsResponse) private static final com.google.chromeos.moblab.v1beta1.ListModelsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.chromeos.moblab.v1beta1.ListModelsResponse(); } public static com.google.chromeos.moblab.v1beta1.ListModelsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListModelsResponse> PARSER = new com.google.protobuf.AbstractParser<ListModelsResponse>() { @java.lang.Override public ListModelsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ListModelsResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ListModelsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListModelsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.chromeos.moblab.v1beta1.ListModelsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* MIT License ----------- Copyright (c) 2019 Ivan Yurkov (MB "Stylo tymas" http://steel-team.net) 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 com.steelteam.openrhynn.scrolls; import com.steelteam.openrhynn.entities.Entity; import com.steelteam.openrhynn.logic.Formulas; import com.steelteam.openrhynn.scrolls.core.BaseScroll; public class BloodScroll extends BaseScroll { public int amount = 0; @Override public void tick() { try { Entity attacker = world.getEntity(attackerId); Entity target = world.getEntity(targetId); if(attackerId == targetId) return; int amountFinal = Formulas.calculateMagicPower(attacker.getMagicMax(), amount); int onep = amount / 100; amount += onep * amountFinal; attacker.restoreHP(amount); world.clearDamage(attacker, target, amount, true); attackerHealth = attacker.healthCurrent; targetHealth = target.healthCurrent; cast(); } catch (Exception ex) { ex.printStackTrace(); } } }
package com.sam_chordas.android.stockhawk.widget; import android.annotation.TargetApi; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.TaskStackBuilder; import android.widget.RemoteViews; import com.sam_chordas.android.stockhawk.R; import com.sam_chordas.android.stockhawk.ui.MyStocksActivity; /** * Created by Yash Tanna on 03/17/2016. */ public class QuoteWidgetProvider extends AppWidgetProvider { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { for (int appWidgetId : appWidgetIds) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_collection); // Create an Intent to launch MainActivity Intent intent = new Intent(context, MyStocksActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.widget, pendingIntent); // Set up the collection if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { setRemoteAdapter(context, views); } else { setRemoteAdapterV11(context, views); } PendingIntent clickPendingIntentTemplate = TaskStackBuilder.create(context) .addNextIntentWithParentStack(intent) .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); views.setPendingIntentTemplate(R.id.widget_list, clickPendingIntentTemplate); // Tell the AppWidgetManager to perform an update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, views); } } /** * Sets the remote adapter used to fill in the list items * * @param views RemoteViews to set the RemoteAdapter */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void setRemoteAdapter(Context context, @NonNull final RemoteViews views) { views.setRemoteAdapter(R.id.widget_list, new Intent(context, QuoteWidgetRemoteViewsService.class)); } /** * Sets the remote adapter used to fill in the list items * * @param views RemoteViews to set the RemoteAdapter */ @SuppressWarnings("deprecation") private void setRemoteAdapterV11(Context context, @NonNull final RemoteViews views) { views.setRemoteAdapter(0, R.id.widget_list, new Intent(context, QuoteWidgetRemoteViewsService.class)); } }
package org.realityforge.gwt.appcache.server.gwtp; import javax.annotation.Nonnull; import javax.servlet.http.HttpServletRequest; import org.realityforge.gwt.appcache.server.propertyprovider.PropertyProvider; public final class FormFactorPropertyProvider implements PropertyProvider { @Nonnull @Override public String getPropertyName() { return "gwtp.formfactor"; } @Override public String getPropertyValue( @Nonnull final HttpServletRequest request ) { final String userAgent = request.getHeader( "User-Agent" ); if ( isSupportedMobileAgent( userAgent ) && !isUnsupportedMobileAgent( userAgent ) ) { return "mobile"; } else if ( isSupportedTabletAgent( userAgent ) ) { return "tablet"; } return "desktop"; } private boolean isSupportedMobileAgent( @Nonnull final String userAgent ) { return ( userAgent.contains( "Mobi" ) || userAgent.contains( "DoCoMo" ) || userAgent.contains( "Mini" ) || userAgent.contains( "Puffin" ) || userAgent.contains( "Fennec" ) || userAgent.contains( "j2me" ) || userAgent.contains( "Palm" ) || userAgent.contains( "portalmmm" ) || userAgent.contains( "Symbian ?OS" ) || userAgent.contains( "BOLT" ) || userAgent.contains( "webOS" ) || userAgent.contains( "UP" ) || userAgent.contains( "\\.(Link|Browser)" ) || userAgent.contains( "MIDP" ) || userAgent.contains( "PSP" ) || userAgent.contains( "WP" ) || userAgent.contains( "SonyEricsson" ) || userAgent.contains( "Windows ?CE" ) || userAgent.contains( "Android 0" ) || userAgent.contains( "Novarra-Vision" ) || userAgent.contains( "Nokia" ) || userAgent.contains( "uZardWeb" ) ); } private boolean isUnsupportedMobileAgent( @Nonnull final String userAgent ) { return ( userAgent.contains( "Silk-Accelerated" ) || userAgent.contains( "Pad" ) || userAgent.contains( "GT-P1000M" ) || userAgent.contains( "Xoom" ) || userAgent.contains( "SCH-I800" ) ); } private boolean isSupportedTabletAgent( @Nonnull final String userAgent ) { return ( userAgent.contains( "Pad" ) || userAgent.contains( "Android" ) || userAgent.contains( "Kindle" ) || userAgent.contains( "Silk-Accelerated" ) || userAgent.contains( "nook" ) || userAgent.contains( "PlayBook" ) ); } }
package seedu.address.model.person; import java.util.List; import java.util.function.Predicate; import seedu.address.logic.commands.FindCommand; import seedu.address.model.FindResults; //@@author tanhengyeow /** * Tests that a {@code Person}'s {@code Comment} matches any of the keywords given. */ public class CommentContainsKeywordsPredicate implements Predicate<Person> { private final List<String> keywords; private final String commandPrefix = "c/"; public CommentContainsKeywordsPredicate(List<String> keywords) { this.keywords = keywords; } @Override public boolean test(Person person) { return keywords.stream() .anyMatch(keyword -> FindResults.getInstance() .containsWordIgnoreCase(person.getComment().value, keyword, commandPrefix) || keywords.stream() .anyMatch(fuzzyKeyword -> FindResults.getInstance().containsFuzzyMatchIgnoreCase( person.getComment().value, fuzzyKeyword, commandPrefix, FindCommand.LEVENSHTEIN_DISTANCE_THRESHOLD))); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof CommentContainsKeywordsPredicate // instanceof handles nulls && this.keywords.equals(((CommentContainsKeywordsPredicate) other).keywords)); // state check } }
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.gwtproject.dom.builder.shared; import org.gwtproject.regexp.shared.RegExp; import org.gwtproject.safehtml.shared.SafeHtml; import org.gwtproject.dom.client.Element; /** * Base implementation of {@link ElementBuilderBase} that handles state, but * nothing else. * * <p> * DO NOT USE THIS CLASS. This class is an implementation class and may change * in the future. * </p> * * This class is used to ensure that the HTML and DOM implementations throw the * same exceptions, even if something is valid in one and not the other. For * example, the DOM implementation supports changing an attribute after setting * inner HTML, but the HTML version does not, so they should both throw an * error. Otherwise, they would not be swappable. */ public abstract class ElementBuilderImpl { /** * A node in the builder stack. */ private static class StackNode { private final ElementBuilderBase<?> builder; private StackNode next; private final String tagName; public StackNode(String tagName, ElementBuilderBase<?> builder) { this.builder = builder; this.tagName = tagName; } } /** * A stack that allows quick access to its top element. * * <p> * FastPeekStack is implemented using a simple linked list of nodes to avoid * the dynamic casts associated with the emulated version of * {@link java.util.ArrayList}. When constructing a large DOM structure, such * as a table, the dynamic casts in ArrayList can significantly degrade * performance. * </p> */ private class FastPeekStack { private static final String EMPTY_STACK_MESSAGE = "There are no elements on the stack."; /** * The top item in the stack. */ private StackNode top; private int size = 0; public boolean isEmpty() { return (top == null); } public StackNode peek() { assertNotEmpty(); return top; } /** * Pop the current {@link StackNode} and return it. * * <p> * The popped node will be recycled and should not be saved. * </p> * * @return the popped node */ public StackNode pop() { assertNotEmpty(); StackNode toRet = top; top = top.next; size--; return toRet; } public void push(ElementBuilderBase<?> builder, String tagName) { StackNode node = new StackNode(tagName, builder); node.next = top; top = node; size++; } public int size() { return size; } /** * Assert that the stack is not empty. * * @throws IllegalStateException if empty */ private void assertNotEmpty() { if (isEmpty()) { throw new IllegalStateException(EMPTY_STACK_MESSAGE); } } } /** * A regex for matching valid HTML tags. */ private static RegExp HTML_TAG_REGEX; private boolean asElementCalled; /** * True if the top most element has not yet been added. */ private boolean isEmpty = true; /** * True if HTML of text has been added. */ private boolean isHtmlOrTextAdded; /** * True if the start tag is still open (open bracket '&lt;' but no close * bracket '&gt;'). */ private boolean isStartTagOpen; /** * True if the style attribute has been opened and closed. */ private boolean isStyleClosed; /** * True if the style attribute is open. */ private boolean isStyleOpen; /** * The stack of element builders. */ private final FastPeekStack stack = new FastPeekStack(); public ElementBuilderImpl() { if (HTML_TAG_REGEX == null) { // Starts with a-z, plus 0 or more alphanumeric values (case insensitive). HTML_TAG_REGEX = RegExp.compile("^[a-z][a-z0-9]*$", "i"); } } public void end() { endImpl(getCurrentTagName()); } public void end(String tagName) { // Verify the tag name matches the expected tag. String topItem = getCurrentTagName(); if (!topItem.equalsIgnoreCase(tagName)) { throw new IllegalStateException("Specified tag \"" + tagName + "\" does not match the current element \"" + topItem + "\""); } // End the element. endImpl(topItem); } public void endStyle() { if (!isStyleOpen) { throw new IllegalStateException( "Attempting to close a style attribute, but the style attribute isn't open"); } maybeCloseStyleAttribute(); } /** * Return the built DOM as an {@link Element}. * * @return the {@link Element} that was built */ public Element finish() { if (asElementCalled) { throw new IllegalStateException("asElement() can only be called once."); } asElementCalled = true; // End all open tags. endAllTags(); return doFinishImpl(); } public int getDepth() { return stack.size(); } public void html(SafeHtml html) { assertStartTagOpen("html cannot be set on an element that already " + "contains other content or elements."); lockCurrentElement(); doHtmlImpl(html); } public void onStart(String tagName, ElementBuilderBase<?> builder) { if (isEmpty) { isEmpty = false; } else if (stack.isEmpty()) { // Check that we aren't creating another top level element. throw new IllegalStateException("You can only build one top level element."); } else { // Check that the element supports children. assertEndTagNotForbidden("child elements"); if (!getCurrentBuilder().isChildElementSupported()) { throw new UnsupportedOperationException(getCurrentTagName() + " does not support child elements."); } } // Check that asElement hasn't already been called. if (isHtmlOrTextAdded) { throw new IllegalStateException("Cannot append an element after setting text of html."); } // Validate the tagName. assertValidTagName(tagName); maybeCloseStartTag(); stack.push(builder, tagName); isStartTagOpen = true; isStyleOpen = false; isStyleClosed = false; isHtmlOrTextAdded = false; } /** * Get the {@link StylesBuilder} used to add style properties to the current * element. * * @return a {@link StylesBuilder} */ public abstract StylesBuilder style(); public void text(String text) { assertStartTagOpen("text cannot be set on an element that already " + "contains other content or elements."); lockCurrentElement(); doTextImpl(text); } /** * Assert that the builder is in a state where an attribute can be added. * * @throw {@link IllegalStateException} if the start tag is closed */ protected void assertCanAddAttributeImpl() { assertStartTagOpen("Attributes cannot be added after appending HTML or adding a child " + "element."); maybeCloseStyleAttribute(); } /** * Assert that a style property can be added, and setup the state as if one is * about to be added. */ protected void assertCanAddStylePropertyImpl() { assertStartTagOpen("Style properties cannot be added after appending HTML or adding a child " + "element."); // Check if a style attribute already exists. if (isStyleClosed) { throw new IllegalStateException( "Style properties must be added at the same time. If you already added style properties," + " you cannot add more after adding non-style attributes."); } // Open the style attribute. if (!isStyleOpen) { isStyleOpen = true; doOpenStyleImpl(); } } /** * Assert that the specified tag name is valid. * * @throws IllegalArgumentException if not valid */ protected void assertValidTagName(String tagName) { if (!HTML_TAG_REGEX.test(tagName)) { throw new IllegalArgumentException("The specified tag name is invalid: " + tagName); } } /** * Close the start tag. */ protected abstract void doCloseStartTagImpl(); /** * Close the style attribute. */ protected abstract void doCloseStyleAttributeImpl(); /** * Self-close the start tag. This method is called for elements that forbid * the end tag. */ protected abstract void doEndStartTagImpl(); /** * End the specified tag. * * @param tagName the name of the tag to end */ protected abstract void doEndTagImpl(String tagName); /** * Return the build element. * * @return the element */ protected abstract Element doFinishImpl(); /** * Set the specified html as the inner HTML of the current element. * * @param html the HTML to set */ protected abstract void doHtmlImpl(SafeHtml html); /** * Open the style attribute. */ protected abstract void doOpenStyleImpl(); /** * Set the specified text as the inner text of the current element. * * @param text the text to set */ protected abstract void doTextImpl(String text); /** * End all open tags, including the root element. * * <p> * Doing so also ensures that all builder methods will throw an exception * because the stack is empty, and a new element cannot be started. * </p> */ protected void endAllTags() { while (!stack.isEmpty()) { end(); } } /** * Lock the current element, preventing any additional changes to it. The only * valid option is to call {@link #end()}. */ protected void lockCurrentElement() { maybeCloseStartTag(); assertEndTagNotForbidden("html"); isHtmlOrTextAdded = true; } /** * Assert that the current builder does not forbid end tags. * * @param operation the operation that the user is attempting * @throw {@link UnsupportedOperationException} if not supported */ private void assertEndTagNotForbidden(String operation) { if (getCurrentBuilder().isEndTagForbidden()) { throw new UnsupportedOperationException(getCurrentTagName() + " does not support " + operation); } } /** * Assert that the start tag is still open. * * @param message the error message if the start tag is not open * @throw {@link IllegalStateException} if the start tag is closed */ private void assertStartTagOpen(String message) { if (!isStartTagOpen) { throw new IllegalStateException(message); } } /** * End the current element without checking the tag name. * * @param tagName the tag name to end */ private void endImpl(String tagName) { // Close the start tag. maybeCloseStartTag(); /* * End the tag. The tag name is safe because it comes from the stack, and * tag names are checked before they are added to the stack. */ if (getCurrentBuilder().isEndTagForbidden()) { doEndStartTagImpl(); } else { doEndTagImpl(tagName); } // Popup the item off the top of the stack. isStartTagOpen = false; // Closed because this element was added. isStyleClosed = true; // Too late to add styles. stack.pop(); /* * If this element was added, then we did not add html or text to the * parent. */ isHtmlOrTextAdded = false; } /** * Get the builder at the top of the stack. * * @return an {@link ElementBuilderBase} * @throws IllegalStateException if there are no elements on the stack */ private ElementBuilderBase<?> getCurrentBuilder() { return stack.peek().builder; } /** * Get the tag name of the element at the top of the stack. * * @return a tag name * @throws IllegalStateException if there are no elements on the stack */ private String getCurrentTagName() { return stack.peek().tagName; } /** * Close the start tag if it is still open. */ private void maybeCloseStartTag() { maybeCloseStyleAttribute(); if (isStartTagOpen) { isStartTagOpen = false; /* * Close the start tag, unless the end tag is forbidden. If the end tag is * forbidden, the only valid call is to #end(), which will self end the * start tag. */ if (!getCurrentBuilder().isEndTagForbidden()) { doCloseStartTagImpl(); } } } /** * Close the style attribute if it is still open. */ private void maybeCloseStyleAttribute() { if (isStyleOpen) { isStyleOpen = false; isStyleClosed = true; doCloseStyleAttributeImpl(); } } }
package org.obapanel.jedis.collections; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; import redis.clients.jedis.Transaction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import static org.obapanel.jedis.common.test.TransactionOrder.quickReponseExecuted; /** * Mock of jedis methods used by the lock */ public class MockOfJedisForSet { private static final Logger LOG = LoggerFactory.getLogger(MockOfJedisForList.class); public static final String CLIENT_RESPONSE_OK = "OK"; public static final String CLIENT_RESPONSE_KO = "KO"; // Zero to prevent some unit test // One to one pass // More to more passes static final int UNIT_TEST_CYCLES_LIST = 1; static boolean unitTestEnabledForList() { return UNIT_TEST_CYCLES_LIST > 0; } private final Jedis jedis; private final JedisPool jedisPool; private final Transaction transaction; private final Map<String, Object> data = Collections.synchronizedMap(new HashMap<>()); public MockOfJedisForSet() { jedis = Mockito.mock(Jedis.class); jedisPool = Mockito.mock(JedisPool.class); when(jedisPool.getResource()).thenReturn(jedis); transaction = Mockito.mock(Transaction.class); when(jedis.multi()).thenReturn(transaction); when(jedis.exists(anyString())).thenAnswer(ioc -> { String key = ioc.getArgument(0); return mockExists(key); }); when(jedis.del(anyString())).thenAnswer(ioc -> { String key = ioc.getArgument(0); return mockDel(key); }); when(transaction.del(anyString())).thenAnswer(ioc -> { String key = ioc.getArgument(0); return quickReponseExecuted(mockDel(key)); }); when(jedis.sadd(anyString(), any())).thenAnswer(this::iocSadd); when(transaction.sadd(anyString(), any())).thenAnswer( ioc -> quickReponseExecuted(iocSadd(ioc)) ); when(jedis.sismember(anyString(), anyString())).thenAnswer(ioc -> { String key = ioc.getArgument(0); String value = ioc.getArgument(1); return mockSismember(key, value); }); when(jedis.scard(anyString())).thenAnswer(ioc -> { String key = ioc.getArgument(0); return mockScard(key); }); when(jedis.srem(anyString(), any())).thenAnswer(ioc -> { String key = ioc.getArgument(0); Object value; if (ioc.getArguments().length > 2) { // String[] has beem passed as many arguments List<String> temp = new ArrayList<>(); for(int i=1; i < ioc.getArguments().length; i++) { temp.add(ioc.getArgument(i)); } value = temp.toArray(new String[0]); } else { // passed String[] value = ioc.getArgument(1); } return mockSrem(key, value); }); when(jedis.sscan(anyString(), anyString())).thenAnswer(ioc -> { String key = ioc.getArgument(0); String cursor = ioc.getArgument(1); ScanParams scanParams = new ScanParams(); return mockSscan(key, cursor, scanParams); }); when(jedis.sscan(anyString(), anyString(), any(ScanParams.class))).thenAnswer(ioc -> { String key = ioc.getArgument(0); String cursor = ioc.getArgument(1); ScanParams scanParams = ioc.getArgument(2); return mockSscan(key, cursor, scanParams); }); } private Long iocSadd(InvocationOnMock ioc){ // dont like it, but it works String key = ioc.getArgument(0); Object value; if (ioc.getArguments().length > 2) { // String[] has beem passed as many arguments List<String> temp = new ArrayList<>(); for(int i=1; i < ioc.getArguments().length; i++) { temp.add(ioc.getArgument(i)); } value = temp.toArray(new String[0]); } else { // passed String[] value = ioc.getArgument(1); } return mockSadd(key, value); } Jedis getJedis(){ return jedis; } JedisPool getJedisPool() { return jedisPool; } synchronized void clearData(){ data.clear(); } private synchronized Set<String> getStringSet(String key) { return (Set<String>) data.computeIfAbsent(key, k -> new HashSet<String>()); } synchronized boolean mockExists(String key) { return data.containsKey(key); } synchronized Long mockDel(String key) { if (data.containsKey(key)) { data.remove(key); return 1L; } else { return 0L; } } synchronized Long mockSadd(String key, Object value) { if (value instanceof String) { return doAdd(key, new String[] {(String) value}); } else if (value instanceof String[]) { return doAdd(key, (String[]) value); } else { return 0L; } } private Long doAdd(String key, String[] values) { Set<String> set = getStringSet(key); long num = 0; for(String value: values) { boolean added = set.add(value); if (added) { num++; } } return num; } synchronized Boolean mockSismember(String key, String value) { return getStringSet(key).contains(value); } synchronized Long mockScard(String key) { return Long.valueOf(getStringSet(key).size()); } synchronized ScanResult<String> mockSscan(String key, String cursor, ScanParams scanParams) { Set<String> set = getStringSet(key); if (set.isEmpty()) { return new ScanResult<>(ScanParams.SCAN_POINTER_START, new ArrayList<>()); } else if (ScanParams.SCAN_POINTER_START.equals(cursor)) { return new ScanResult<>("999", new ArrayList<>(set)); } else { return new ScanResult<>(ScanParams.SCAN_POINTER_START, new ArrayList<>()); } } synchronized Long mockSrem(String key, Object value) { if (value instanceof String) { return doRem(key, new String[] {(String) value}); } else if (value instanceof String[]) { return doRem(key, (String[]) value); } else { return 0L; } } synchronized Long doRem(String key, String[] values) { Set<String> set = getStringSet(key); long num = 0; for(String value: values) { boolean removed = set.remove(value); if (removed) { num++; } } return num; } }
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * Licensed under The MIT License (Massachusetts Institute of Technology License) * * See http://opensource.org/licenses/MIT * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.timingdiagram.command; import net.sourceforge.plantuml.LineLocation; import net.sourceforge.plantuml.command.CommandExecutionResult; import net.sourceforge.plantuml.command.SingleLineCommand2; import net.sourceforge.plantuml.command.regex.IRegex; import net.sourceforge.plantuml.command.regex.RegexConcat; import net.sourceforge.plantuml.command.regex.RegexLeaf; import net.sourceforge.plantuml.command.regex.RegexOptional; import net.sourceforge.plantuml.command.regex.RegexResult; import net.sourceforge.plantuml.timingdiagram.TimingDiagram; public class CommandClock extends SingleLineCommand2<TimingDiagram> { public CommandClock() { super(getRegexConcat()); } private static IRegex getRegexConcat() { return RegexConcat.build(CommandClock.class.getName(), RegexLeaf.start(), // new RegexOptional( // new RegexConcat( // new RegexLeaf("COMPACT", "(compact)"), // RegexLeaf.spaceOneOrMore())), // new RegexLeaf("TYPE", "clock"), // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("CODE", "([\\p{L}0-9_.@]+)"), // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("with"), // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("period"), // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("PERIOD", "([0-9]+)"), // new RegexOptional(new RegexConcat( // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("pulse"), // RegexLeaf.spaceOneOrMore(), // new RegexLeaf("PULSE", "([0-9]+)") // )), RegexLeaf.end()); } @Override final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) { final String compact = arg.get("COMPACT", 0); final String code = arg.get("CODE", 0); final int period = Integer.parseInt(arg.get("PERIOD", 0)); final String pulseString = arg.get("PULSE", 0); int pulse = 0; if (pulseString != null) { pulse = Integer.parseInt(pulseString); } return diagram.createClock(code, code, period, pulse, compact != null); } }
package io.ebeaninternal.server.querydefn; import io.ebean.*; import io.ebean.OrderBy.Property; import io.ebean.bean.CallOrigin; import io.ebean.bean.ObjectGraphNode; import io.ebean.bean.ObjectGraphOrigin; import io.ebean.bean.PersistenceContext; import io.ebean.event.BeanQueryRequest; import io.ebean.event.readaudit.ReadEvent; import io.ebean.plugin.BeanType; import io.ebeaninternal.api.*; import io.ebeaninternal.server.autotune.ProfilingListener; import io.ebeaninternal.server.core.SpiOrmQueryRequest; import io.ebeaninternal.server.deploy.*; import io.ebeaninternal.server.el.ElPropertyDeploy; import io.ebeaninternal.server.expression.*; import io.ebeaninternal.server.query.NativeSqlQueryPlanKey; import io.ebeaninternal.server.rawsql.SpiRawSql; import io.ebeaninternal.server.transaction.ExternalJdbcTransaction; import javax.persistence.PersistenceException; import java.sql.Connection; import java.sql.Timestamp; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; /** * Default implementation of an Object Relational query. */ public final class DefaultOrmQuery<T> extends AbstractQuery implements SpiQuery<T> { private static final String DEFAULT_QUERY_NAME = "default"; private static final FetchConfig FETCH_CACHE = FetchConfig.ofCache(); private static final FetchConfig FETCH_QUERY = FetchConfig.ofQuery(); private static final FetchConfig FETCH_LAZY = FetchConfig.ofLazy(); private final Class<T> beanType; private final ExpressionFactory expressionFactory; private final BeanDescriptor<T> rootBeanDescriptor; private BeanDescriptor<T> beanDescriptor; private SpiEbeanServer server; private SpiTransaction transaction; /** * For lazy loading of ManyToMany we need to add a join to the intersection table. This is that * join to the intersection table. */ private TableJoin m2mIncludeJoin; private ProfilingListener profilingListener; private Type type; private String label; private Mode mode = Mode.NORMAL; private Object tenantId; /** * Holds query in structured form. */ private OrmQueryDetail detail; private int maxRows; private int firstRow; private boolean disableLazyLoading; /** * Lazy loading batch size (can override server wide default). */ private int lazyLoadBatchSize; private OrderBy<T> orderBy; private String loadMode; private String loadDescription; private String generatedSql; private String lazyLoadProperty; private String lazyLoadManyPath; private boolean allowLoadErrors; /** * Flag set for report/DTO beans when we may choose to explicitly include the Id property. */ private boolean manualId; /** * Set to true by a user wanting a DISTINCT query (id property must be excluded). */ private boolean distinct; /** * Set to true if this is a future fetch using background threads. */ private boolean futureFetch; /** * Only used for read auditing with findFutureList() query. */ private ReadEvent futureFetchAudit; private int timeout; /** * The property used to get the key value for a Map. */ private String mapKey; /** * Used for find by id type query. */ private Object id; private Map<String, ONamedParam> namedParams; /** * Bind parameters when using the query language. */ private BindParams bindParams; private DefaultExpressionList<T> textExpressions; private DefaultExpressionList<T> whereExpressions; private DefaultExpressionList<T> havingExpressions; private boolean asOfBaseTable; private int asOfTableCount; /** * Set for flashback style 'as of' query. */ private Timestamp asOf; private TemporalMode temporalMode = TemporalMode.CURRENT; private Timestamp versionsStart; private Timestamp versionsEnd; private List<String> softDeletePredicates; private boolean disableReadAudit; private int bufferFetchSizeHint; private boolean usageProfiling = true; private CacheMode useBeanCache = CacheMode.AUTO; private CacheMode useQueryCache = CacheMode.OFF; private Boolean readOnly; private PersistenceContextScope persistenceContextScope; /** * Allow for explicit on off or null for default. */ private Boolean autoTune; private LockWait forUpdate; private LockType lockType; private boolean singleAttribute; private CountDistinctOrder countDistinctOrder; private boolean autoTuned; private String rootTableAlias; private String baseTable; /** * The node of the bean or collection that fired lazy loading. Not null if profiling is on and * this query is for lazy loading. Used to hook back a lazy loading query to the "original" query * point. */ private ObjectGraphNode parentNode; private BeanPropertyAssocMany<?> lazyLoadForParentsProperty; private CQueryPlanKey queryPlanKey; private PersistenceContext persistenceContext; private ManyWhereJoins manyWhereJoins; private SpiRawSql rawSql; private boolean useDocStore; private String docIndexName; private OrmUpdateProperties updateProperties; private String nativeSql; private boolean orderById; private ProfileLocation profileLocation; public DefaultOrmQuery(BeanDescriptor<T> desc, SpiEbeanServer server, ExpressionFactory expressionFactory) { this.beanDescriptor = desc; this.rootBeanDescriptor = desc; this.beanType = desc.type(); this.server = server; this.orderById = server.config().isDefaultOrderById(); this.disableLazyLoading = server.config().isDisableLazyLoading(); this.expressionFactory = expressionFactory; this.detail = new OrmQueryDetail(); } public void setNativeSql(String nativeSql) { this.nativeSql = nativeSql; } @Override public <D> DtoQuery<D> asDto(Class<D> dtoClass) { return server.findDto(dtoClass, this); } @Override public UpdateQuery<T> asUpdate() { return new DefaultUpdateQuery<>(this); } @Override public BeanDescriptor<T> getBeanDescriptor() { return beanDescriptor; } @Override public boolean isFindAll() { return whereExpressions == null && nativeSql == null && rawSql == null; } @Override public boolean isFindById() { if (id == null && whereExpressions != null) { id = whereExpressions.idEqualTo(beanDescriptor.idName()); if (id != null) { whereExpressions = null; } } return id != null; } @Override public String profileEventId() { switch (mode) { case LAZYLOAD_BEAN: return FIND_ONE_LAZY; case LAZYLOAD_MANY: return FIND_MANY_LAZY; default: return type.profileEventId(); } } @Override public String getProfileId() { return getPlanLabel(); } @Override public Query<T> setProfileLocation(ProfileLocation profileLocation) { this.profileLocation = profileLocation; return this; } @Override public String getLabel() { return label; } @Override public String getPlanLabel() { if (label != null) { return label; } if (profileLocation != null) { return profileLocation.label(); } return null; } @Override public void setProfilePath(String label, String relativePath, ProfileLocation profileLocation) { this.profileLocation = profileLocation; this.label = ((profileLocation == null) ? label : profileLocation.label()) + "_" + relativePath; } @Override public Query<T> setLabel(String label) { this.label = label; return this; } @Override public boolean isAutoTunable() { return nativeSql == null && beanDescriptor.isAutoTunable(); } @Override public Query<T> setUseDocStore(boolean useDocStore) { this.useDocStore = useDocStore; return this; } @Override public boolean isUseDocStore() { return useDocStore; } @Override public Query<T> apply(FetchPath fetchPath) { fetchPath.apply(this); return this; } @Override public void addSoftDeletePredicate(String softDeletePredicate) { if (softDeletePredicates == null) { softDeletePredicates = new ArrayList<>(); } softDeletePredicates.add(softDeletePredicate); } @Override public List<String> getSoftDeletePredicates() { return softDeletePredicates; } @Override public boolean isAsOfBaseTable() { return asOfBaseTable; } @Override public void setAsOfBaseTable() { this.asOfBaseTable = true; } @Override public Query<T> setAllowLoadErrors() { this.allowLoadErrors = true; return this; } @Override public void incrementAsOfTableCount() { asOfTableCount++; } @Override public int getAsOfTableCount() { return asOfTableCount; } @Override public Timestamp getAsOf() { return asOf; } @Override public Query<T> asOf(Timestamp asOfDateTime) { this.temporalMode = (asOfDateTime != null) ? TemporalMode.AS_OF : TemporalMode.CURRENT; this.asOf = asOfDateTime; return this; } @Override public Query<T> asDraft() { this.temporalMode = TemporalMode.DRAFT; this.useBeanCache = CacheMode.OFF; return this; } @Override public Query<T> setIncludeSoftDeletes() { this.temporalMode = TemporalMode.SOFT_DELETED; return this; } @Override public Query<T> setDocIndexName(String indexName) { this.docIndexName = indexName; this.useDocStore = true; return this; } @Override public String getDocIndexName() { return docIndexName; } @Override public SpiRawSql getRawSql() { return rawSql; } @Override public Query<T> setRawSql(RawSql rawSql) { this.rawSql = (SpiRawSql) rawSql; return this; } @Override public String getOriginKey() { if (parentNode == null || parentNode.getOriginQueryPoint() == null) { return null; } else { return parentNode.getOriginQueryPoint().getKey(); } } @Override public int getLazyLoadBatchSize() { return lazyLoadBatchSize; } @Override public Query<T> setLazyLoadBatchSize(int lazyLoadBatchSize) { this.lazyLoadBatchSize = lazyLoadBatchSize; return this; } @Override public String getLazyLoadProperty() { return lazyLoadProperty; } @Override public void setLazyLoadProperty(String lazyLoadProperty) { this.lazyLoadProperty = lazyLoadProperty; } @Override public ExpressionFactory getExpressionFactory() { return expressionFactory; } private void createExtraJoinsToSupportManyWhereClause() { manyWhereJoins = new ManyWhereJoins(); if (whereExpressions != null) { whereExpressions.containsMany(beanDescriptor, manyWhereJoins); } if (havingExpressions != null) { havingExpressions.containsMany(beanDescriptor, manyWhereJoins); } if (orderBy != null) { for (Property orderProperty : orderBy.getProperties()) { ElPropertyDeploy elProp = beanDescriptor.elPropertyDeploy(orderProperty.getProperty()); if (elProp != null && elProp.containsFormulaWithJoin()) { manyWhereJoins.addFormulaWithJoin(elProp.elPrefix(), elProp.name()); } } } } /** * Return the extra joins required to support the where clause for 'Many' properties. */ @Override public ManyWhereJoins getManyWhereJoins() { return manyWhereJoins; } /** * Return true if select all properties was used to ensure the property invoking a lazy load was * included in the query. */ @Override public boolean selectAllForLazyLoadProperty() { if (lazyLoadProperty != null) { if (!detail.containsProperty(lazyLoadProperty)) { detail.select("*"); return true; } } return false; } private List<OrmQueryProperties> removeQueryJoins() { List<OrmQueryProperties> queryJoins = detail.removeSecondaryQueries(); if (queryJoins != null) { if (orderBy != null) { // remove any orderBy properties that relate to // paths of the secondary queries for (OrmQueryProperties joinPath : queryJoins) { // loop through the orderBy properties and // move any ones related to the query join List<Property> properties = orderBy.getProperties(); Iterator<Property> it = properties.iterator(); while (it.hasNext()) { Property property = it.next(); if (property.getProperty().startsWith(joinPath.getPath())) { // remove this orderBy segment and // add it to the secondary join it.remove(); joinPath.addSecJoinOrderProperty(property); } } } } } return queryJoins; } private List<OrmQueryProperties> removeLazyJoins() { return detail.removeSecondaryLazyQueries(); } @Override public void setLazyLoadManyPath(String lazyLoadManyPath) { this.lazyLoadManyPath = lazyLoadManyPath; } @Override public SpiQuerySecondary convertJoins() { if (!useDocStore) { createExtraJoinsToSupportManyWhereClause(); } markQueryJoins(); return new OrmQuerySecondary(removeQueryJoins(), removeLazyJoins()); } /** * Limit the number of fetch joins to Many properties, mark as query joins as needed. */ private void markQueryJoins() { detail.markQueryJoins(beanDescriptor, lazyLoadManyPath, isAllowOneManyFetch(), type.defaultSelect()); } private boolean isAllowOneManyFetch() { if (Mode.LAZYLOAD_MANY == mode) { return false; } else { return !hasMaxRowsOrFirstRow() || isRawSql(); } } @Override public void setDefaultSelectClause() { if (type.defaultSelect()) { detail.setDefaultSelectClause(beanDescriptor); } else if (!detail.hasSelectClause()) { // explicit empty select when single attribute query on non-root fetch path detail.setEmptyBase(); } } @Override public void setTenantId(Object tenantId) { this.tenantId = tenantId; } @Override public Object getTenantId() { return tenantId; } @Override public void setDetail(OrmQueryDetail detail) { this.detail = detail; } @Override public boolean tuneFetchProperties(OrmQueryDetail tunedDetail) { return detail.tuneFetchProperties(tunedDetail); } @Override public OrmQueryDetail getDetail() { return detail; } @Override public ExpressionList<T> filterMany(String prop) { OrmQueryProperties chunk = detail.getChunk(prop, true); return chunk.filterMany(this); } @Override public void setFilterMany(String prop, ExpressionList<?> filterMany) { if (filterMany != null) { OrmQueryProperties chunk = detail.getChunk(prop, true); chunk.setFilterMany((SpiExpressionList<?>) filterMany); } } @Override public void prepareDocNested() { if (textExpressions != null) { textExpressions.prepareDocNested(beanDescriptor); } if (whereExpressions != null) { whereExpressions.prepareDocNested(beanDescriptor); } } /** * Setup to be a delete or update query. */ @Override public void setupForDeleteOrUpdate() { forUpdate = null; rootTableAlias = "${RTA}"; // alias we remove later setSelectId(); } @Override public CQueryPlanKey setDeleteByIdsPlan() { // re-build plan for cascading via delete by ids queryPlanKey = queryPlanKey.withDeleteByIds(); return queryPlanKey; } /** * Set the select clause to select the Id property. */ @Override public void setSelectId() { // clear select and fetch joins.. detail.clear(); select(beanDescriptor.idBinder().getIdProperty()); } @Override public void setSingleAttribute() { this.singleAttribute = true; } /** * Return true if this is a single attribute query. */ @Override public boolean isSingleAttribute() { return singleAttribute; } @Override public CountDistinctOrder getCountDistinctOrder() { return countDistinctOrder; } /** * Return true if the Id should be included in the query. */ @Override public boolean isWithId() { return !manualId && !distinct && !singleAttribute; } @Override public CacheIdLookup<T> cacheIdLookup() { if (whereExpressions == null) { return null; } List<SpiExpression> underlyingList = whereExpressions.getUnderlyingList(); if (underlyingList.isEmpty()) { if (id != null) { return new CacheIdLookupSingle<>(id); } } else if (underlyingList.size() == 1) { SpiExpression singleExpression = underlyingList.get(0); if (singleExpression instanceof IdInExpression) { return new CacheIdLookupMany<>((IdInExpression) singleExpression); } else if (singleExpression instanceof InExpression) { InExpression in = (InExpression)singleExpression; if (in.property().equals(beanDescriptor.idName())) { return new CacheIdLookupMany<>(in); } } } return null; } @Override public NaturalKeyQueryData<T> naturalKey() { if (whereExpressions == null) { return null; } BeanNaturalKey naturalKey = beanDescriptor.naturalKey(); if (naturalKey == null) { return null; } NaturalKeyQueryData<T> data = new NaturalKeyQueryData<>(naturalKey); for (SpiExpression expression : whereExpressions.getUnderlyingList()) { // must be eq or in if (!expression.naturalKey(data)) { return null; } } return data; } @Override public NaturalKeyBindParam getNaturalKeyBindParam() { NaturalKeyBindParam namedBind = null; if (bindParams != null) { namedBind = bindParams.getNaturalKeyBindParam(); if (namedBind == null) { return null; } } if (whereExpressions != null) { List<SpiExpression> exprList = whereExpressions.internalList(); if (exprList.size() > 1) { return null; } else if (exprList.isEmpty()) { return namedBind; } else { if (namedBind != null) { return null; } SpiExpression se = exprList.get(0); if (se instanceof SimpleExpression) { SimpleExpression e = (SimpleExpression) se; if (e.isOpEquals()) { return new NaturalKeyBindParam(e.getPropName(), e.getValue()); } } } } return null; } @Override public SpiQuery<T> copy() { return copy(server); } @Override public SpiQuery<T> copy(SpiEbeanServer server) { DefaultOrmQuery<T> copy = new DefaultOrmQuery<>(beanDescriptor, server, expressionFactory); copy.transaction = transaction; copy.m2mIncludeJoin = m2mIncludeJoin; copy.profilingListener = profilingListener; copy.profileLocation = profileLocation; copy.baseTable = baseTable; copy.rootTableAlias = rootTableAlias; copy.distinct = distinct; copy.allowLoadErrors = allowLoadErrors; copy.timeout = timeout; copy.mapKey = mapKey; copy.id = id; copy.label = label; copy.nativeSql = nativeSql; copy.useBeanCache = useBeanCache; copy.useQueryCache = useQueryCache; copy.readOnly = readOnly; if (detail != null) { copy.detail = detail.copy(); } copy.temporalMode = temporalMode; copy.firstRow = firstRow; copy.maxRows = maxRows; if (orderBy != null) { copy.orderBy = orderBy.copy(); } copy.orderById = orderById; if (bindParams != null) { copy.bindParams = bindParams.copy(); } if (whereExpressions != null) { copy.whereExpressions = whereExpressions.copy(copy); } if (havingExpressions != null) { copy.havingExpressions = havingExpressions.copy(copy); } copy.persistenceContextScope = persistenceContextScope; copy.usageProfiling = usageProfiling; copy.autoTune = autoTune; copy.parentNode = parentNode; copy.forUpdate = forUpdate; copy.rawSql = rawSql; setCancelableQuery(copy); // required to cancel findId query return copy; } @Override public Query<T> setPersistenceContextScope(PersistenceContextScope scope) { this.persistenceContextScope = scope; return this; } @Override public PersistenceContextScope getPersistenceContextScope() { return persistenceContextScope; } @Override public Type getType() { return type; } @Override public void setType(Type type) { this.type = type; } @Override public String getLoadDescription() { return loadDescription; } @Override public String getLoadMode() { return loadMode; } @Override public void setLoadDescription(String loadMode, String loadDescription) { this.loadMode = loadMode; this.loadDescription = loadDescription; } /** * Return the TransactionContext. * <p> * If no TransactionContext is present on the query then the TransactionContext from the * Transaction is used (transaction scoped persistence context). * </p> */ @Override public PersistenceContext getPersistenceContext() { return persistenceContext; } /** * Set an explicit TransactionContext (typically for a refresh query). * <p> * If no TransactionContext is present on the query then the TransactionContext from the * Transaction is used (transaction scoped persistence context). * </p> */ @Override public void setPersistenceContext(PersistenceContext persistenceContext) { this.persistenceContext = persistenceContext; } @Override public void setLazyLoadForParents(BeanPropertyAssocMany<?> many) { this.lazyLoadForParentsProperty = many; } @Override public BeanPropertyAssocMany<?> getLazyLoadMany() { return lazyLoadForParentsProperty; } /** * Return true if the query detail has neither select or joins specified. */ @Override public boolean isDetailEmpty() { return detail.isEmpty(); } @Override public boolean isAutoTuned() { return autoTuned; } @Override public void setAutoTuned(boolean autoTuned) { this.autoTuned = autoTuned; } @Override public Boolean isAutoTune() { return autoTune; } @Override public void setDefaultRawSqlIfRequired() { if (beanDescriptor.isRawSqlBased() && rawSql == null) { rawSql = beanDescriptor.namedRawSql(DEFAULT_QUERY_NAME); } } @Override public Query<T> setAutoTune(boolean autoTune) { this.autoTune = autoTune; return this; } @Override public Query<T> withLock(LockType lockType) { return setForUpdateWithMode(LockWait.WAIT, lockType); } @Override public Query<T> withLock(LockType lockType, LockWait lockWait) { return setForUpdateWithMode(lockWait, lockType); } @Override public Query<T> forUpdate() { return setForUpdateWithMode(LockWait.WAIT, LockType.DEFAULT); } @Override public Query<T> forUpdateNoWait() { return setForUpdateWithMode(LockWait.NOWAIT, LockType.DEFAULT); } @Override public Query<T> forUpdateSkipLocked() { return setForUpdateWithMode(LockWait.SKIPLOCKED, LockType.DEFAULT); } private Query<T> setForUpdateWithMode(LockWait mode, LockType lockType) { this.forUpdate = mode; this.lockType = lockType; this.useBeanCache = CacheMode.OFF; return this; } @Override public boolean isForUpdate() { return forUpdate != null; } @Override public LockWait getForUpdateLockWait() { return forUpdate; } @Override public LockType getForUpdateLockType() { return lockType; } @Override public ProfilingListener getProfilingListener() { return profilingListener; } @Override public void setProfilingListener(ProfilingListener profilingListener) { this.profilingListener = profilingListener; } @Override public QueryType getQueryType() { if (type != null) { switch (type) { case DELETE: return QueryType.DELETE; case UPDATE: return QueryType.UPDATE; } } return QueryType.FIND; } @Override public Mode getMode() { return mode; } @Override public TemporalMode getTemporalMode() { return temporalMode; } @Override public boolean isAsOfQuery() { return asOf != null; } @Override public boolean isAsDraft() { return TemporalMode.DRAFT == temporalMode; } @Override public boolean isIncludeSoftDeletes() { return TemporalMode.SOFT_DELETED == temporalMode; } @Override public void setMode(Mode mode) { this.mode = mode; } @Override public boolean isUsageProfiling() { return usageProfiling; } @Override public void setUsageProfiling(boolean usageProfiling) { this.usageProfiling = usageProfiling; } @Override public void setParentNode(ObjectGraphNode parentNode) { this.parentNode = parentNode; } @Override public ObjectGraphNode getParentNode() { return parentNode; } @Override public ObjectGraphNode setOrigin(CallOrigin callOrigin) { // create a 'origin' which links this query to the profiling information ObjectGraphOrigin o = new ObjectGraphOrigin(calculateOriginQueryHash(), callOrigin, beanType.getName()); parentNode = new ObjectGraphNode(o, null); return parentNode; } /** * Calculate a hash for use in determining the ObjectGraphOrigin. * <p> * This should be quite a stable hash as most uniqueness is determined by the CallStack, so we * only use the bean type and overall query type. * </p> * <p> * This stable hash allows the query to be changed (joins added etc) without losing the already * collected usage profiling. * </p> */ private int calculateOriginQueryHash() { int hc = beanType.getName().hashCode(); hc = hc * 92821 + (type == null ? 0 : type.ordinal()); return hc; } /** * Calculate the query hash for either AutoTune query tuning or Query Plan caching. */ CQueryPlanKey createQueryPlanKey() { if (isNativeSql()) { String bindHash = (bindParams == null) ? "" : bindParams.calcQueryPlanHash(); queryPlanKey = new NativeSqlQueryPlanKey(type.ordinal() + nativeSql + "-" + firstRow + "-" + maxRows + "-" + bindHash); } else { queryPlanKey = new OrmQueryPlanKey(planDescription(), maxRows, firstRow, rawSql); } return queryPlanKey; } private String planDescription() { StringBuilder sb = new StringBuilder(300); if (type != null) { sb.append(type.ordinal()); } if (useDocStore) { sb.append("/ds"); } if (beanDescriptor.discValue() != null) { sb.append("/dv").append(beanDescriptor.discValue()); } if (temporalMode != SpiQuery.TemporalMode.CURRENT) { sb.append("/tm").append(temporalMode.ordinal()); if (versionsStart != null) { sb.append("v"); } } if (forUpdate != null) { sb.append("/fu").append(forUpdate.ordinal()); if (lockType != null) { sb.append("t").append(lockType.ordinal()); } } if (id != null) { sb.append("/id"); } if (manualId) { sb.append("/md"); } if (distinct) { sb.append("/dt"); } if (allowLoadErrors) { sb.append("/ae"); } if (disableLazyLoading) { sb.append("/dl"); } if (baseTable != null) { sb.append("/bt").append(baseTable); } if (rootTableAlias != null) { sb.append("/ra").append(rootTableAlias); } if (orderBy != null) { sb.append("/ob").append(orderBy.toStringFormat()); } if (m2mIncludeJoin != null) { sb.append("/m2").append(m2mIncludeJoin.getTable()); } if (mapKey != null) { sb.append("/mk").append(mapKey); } if (countDistinctOrder != null) { sb.append("/cd").append(countDistinctOrder.name()); } if (detail != null) { sb.append("/d["); detail.queryPlanHash(sb); sb.append("]"); } if (bindParams != null) { sb.append("/b["); bindParams.buildQueryPlanHash(sb); sb.append("]"); } if (whereExpressions != null) { sb.append("/w["); whereExpressions.queryPlanHash(sb); sb.append("]"); } if (havingExpressions != null) { sb.append("/h["); havingExpressions.queryPlanHash(sb); sb.append("]"); } if (updateProperties != null) { sb.append("/u["); updateProperties.buildQueryPlanHash(sb); sb.append("]"); } return sb.toString(); } @Override public boolean isNativeSql() { return nativeSql != null; } @Override public String getNativeSql() { return nativeSql; } @Override public Object getQueryPlanKey() { return queryPlanKey; } /** * Prepare the query which prepares any expressions (sub-query expressions etc) and calculates the query plan key. */ @Override public CQueryPlanKey prepare(SpiOrmQueryRequest<T> request) { prepareExpressions(request); prepareForPaging(); queryPlanKey = createQueryPlanKey(); return queryPlanKey; } /** * Prepare the expressions (compile sub-queries etc). */ private void prepareExpressions(BeanQueryRequest<?> request) { detail.prepareExpressions(request); if (whereExpressions != null) { whereExpressions.prepareExpression(request); } if (havingExpressions != null) { havingExpressions.prepareExpression(request); } } /** * deemed to be a be a paging query - check that the order by contains the id * property to ensure unique row ordering for predicable paging but only in * case, this is not a distinct query */ private void prepareForPaging() { // add the rawSql statement - if any if (orderByIsEmpty()) { if (rawSql != null && rawSql.getSql() != null) { order(rawSql.getSql().getOrderBy()); } } if (checkPagingOrderBy()) { beanDescriptor.appendOrderById(this); } } @Override public void queryBindKey(BindValuesKey key) { key.add(id); if (whereExpressions != null) whereExpressions.queryBindKey(key); if (havingExpressions != null) havingExpressions.queryBindKey(key); if (bindParams != null) bindParams.queryBindHash(key); key.add(asOf).add(versionsStart).add(versionsEnd); } /** * Return a hash that includes the query plan and bind values. * <p> * This hash can be used to identify if we have executed the exact same query (including bind * values) before. * </p> */ @Override public HashQuery queryHash() { // calculateQueryPlanHash is called just after potential AutoTune tuning // so queryPlanHash is calculated well before this method is called BindValuesKey bindKey = new BindValuesKey(); queryBindKey(bindKey); return new HashQuery(queryPlanKey, bindKey); } @Override public boolean isRawSql() { return rawSql != null; } /** * Return the timeout. */ @Override public int getTimeout() { return timeout; } @Override public boolean hasMaxRowsOrFirstRow() { return maxRows > 0 || firstRow > 0; } @Override public boolean isVersionsBetween() { return versionsStart != null; } @Override public Timestamp getVersionStart() { return versionsStart; } @Override public Timestamp getVersionEnd() { return versionsEnd; } @Override public Boolean isReadOnly() { return readOnly; } @Override public Query<T> setReadOnly(boolean readOnly) { this.readOnly = readOnly; return this; } @Override public boolean isBeanCachePut() { return useBeanCache.isPut() && beanDescriptor.isBeanCaching(); } @Override public boolean isBeanCacheGet() { return useBeanCache.isGet() && beanDescriptor.isBeanCaching(); } @Override public boolean isForceHitDatabase() { return forUpdate != null || CacheMode.PUT == useBeanCache; } @Override public void resetBeanCacheAutoMode(boolean findOne) { if (useBeanCache == CacheMode.AUTO && useQueryCache != CacheMode.OFF) { useBeanCache = CacheMode.OFF; } } @Override public CacheMode getUseBeanCache() { return useBeanCache; } @Override public CacheMode getUseQueryCache() { return useQueryCache; } @Override public Query<T> setBeanCacheMode(CacheMode beanCacheMode) { this.useBeanCache = beanCacheMode; return this; } @Override public Query<T> setUseQueryCache(CacheMode useQueryCache) { this.useQueryCache = useQueryCache; return this; } @Override public Query<T> setLoadBeanCache(boolean loadBeanCache) { this.useBeanCache = CacheMode.PUT; return this; } @Override public Query<T> setTimeout(int secs) { this.timeout = secs; return this; } @Override public void selectProperties(Set<String> props) { detail.selectProperties(props); } @Override public void fetchProperties(String property, Set<String> columns, FetchConfig config) { detail.fetchProperties(property, columns, config); } @Override public void selectProperties(OrmQueryProperties properties) { detail.selectProperties(properties); } @Override public void fetchProperties(String path, OrmQueryProperties other) { detail.fetchProperties(path, other); } @Override public void addNested(String name, OrmQueryDetail nestedDetail, FetchConfig config) { detail.addNested(name, nestedDetail, config); } @Override public Query<T> select(String columns) { detail.select(columns); return this; } @Override public Query<T> select(FetchGroup<T> fetchGroup) { this.detail = ((SpiFetchGroup<T>) fetchGroup).detail(); return this; } @Override public Query<T> fetch(String path) { return fetch(path, null, null); } @Override public Query<T> fetch(String path, FetchConfig joinConfig) { return fetch(path, null, joinConfig); } @Override public Query<T> fetch(String path, String properties) { return fetch(path, properties, null); } @Override public Query<T> fetch(String path, String properties, FetchConfig config) { if (nativeSql != null && (config == null || config.isJoin())) { // can't use fetch join with nativeSql (as the root query) config = FETCH_QUERY; } return fetchInternal(path, properties, config); } @Override public Query<T> fetchQuery(String path) { return fetchInternal(path, null, FETCH_QUERY); } @Override public Query<T> fetchCache(String path) { return fetchInternal(path, null, FETCH_CACHE); } @Override public Query<T> fetchLazy(String path) { return fetchInternal(path, null, FETCH_LAZY); } @Override public Query<T> fetchQuery(String path, String properties) { return fetchInternal(path, properties, FETCH_QUERY); } @Override public Query<T> fetchCache(String path, String properties) { return fetchInternal(path, properties, FETCH_CACHE); } @Override public Query<T> fetchLazy(String path, String properties) { return fetchInternal(path, properties, FETCH_LAZY); } private Query<T> fetchInternal(String path, String properties, FetchConfig config) { detail.fetch(path, properties, config); return this; } @Override public Query<T> usingTransaction(Transaction transaction) { this.transaction = (SpiTransaction) transaction; return this; } @Override public Query<T> usingConnection(Connection connection) { this.transaction = new ExternalJdbcTransaction(connection); return this; } @Override public Query<T> usingDatabase(Database database) { this.server = (SpiEbeanServer) database; return this; } @Override public int delete() { return server.delete(this, transaction); } @Override public int delete(Transaction transaction) { return server.delete(this, transaction); } @Override public int update() { return server.update(this, transaction); } @Override public int update(Transaction transaction) { return server.update(this, transaction); } @Override public <A> List<A> findIds() { // a copy of this query is made in the server // as the query needs to modified (so we modify // the copy rather than this query instance) return server.findIds(this, transaction); } @Override public boolean exists() { return server.exists(this, transaction); } @Override public int findCount() { // a copy of this query is made in the server // as the query needs to modified (so we modify // the copy rather than this query instance) return server.findCount(this, transaction); } @Override public void findEachWhile(Predicate<T> consumer) { server.findEachWhile(this, consumer, transaction); } @Override public void findEach(Consumer<T> consumer) { server.findEach(this, consumer, transaction); } @Override public void findEach(int batch, Consumer<List<T>> consumer) { server.findEach(this, batch, consumer, transaction); } @Override public QueryIterator<T> findIterate() { return server.findIterate(this, transaction); } @Override public Stream<T> findStream() { return server.findStream(this, transaction); } @Override public Stream<T> findLargeStream() { return server.findLargeStream(this, transaction); } @Override public List<Version<T>> findVersions() { this.temporalMode = TemporalMode.VERSIONS; return server.findVersions(this, transaction); } @Override public List<Version<T>> findVersionsBetween(Timestamp start, Timestamp end) { if (start == null || end == null) { throw new IllegalArgumentException("start and end must not be null"); } this.temporalMode = TemporalMode.VERSIONS; this.versionsStart = start; this.versionsEnd = end; return server.findVersions(this, transaction); } @Override public List<T> findList() { return server.findList(this, transaction); } @Override public Set<T> findSet() { return server.findSet(this, transaction); } @Override public <K> Map<K, T> findMap() { return server.findMap(this, transaction); } @Override @SuppressWarnings("unchecked") public <A> List<A> findSingleAttributeList() { return (List<A>) server.findSingleAttributeList(this, transaction); } @Override public <A> A findSingleAttribute() { List<A> list = findSingleAttributeList(); return !list.isEmpty() ? list.get(0) : null; } @Override public T findOne() { return server.findOne(this, transaction); } @Override public Optional<T> findOneOrEmpty() { return server.findOneOrEmpty(this, transaction); } @Override public FutureIds<T> findFutureIds() { return server.findFutureIds(this, transaction); } @Override public FutureList<T> findFutureList() { return server.findFutureList(this, transaction); } @Override public FutureRowCount<T> findFutureCount() { return server.findFutureCount(this, transaction); } @Override public PagedList<T> findPagedList() { return server.findPagedList(this, transaction); } @Override public Query<T> setParameter(Object value) { if (bindParams == null) { bindParams = new BindParams(); } bindParams.setNextParameter(value); return this; } @Override public Query<T> setParameters(Object... values) { if (bindParams == null) { bindParams = new BindParams(); } bindParams.setNextParameters(values); return this; } /** * Set an ordered bind parameter according to its position. Note that the position starts at 1 to * be consistent with JDBC PreparedStatement. You need to set a parameter value for each ? you * have in the query. */ @Override public Query<T> setParameter(int position, Object value) { if (bindParams == null) { bindParams = new BindParams(); } bindParams.setParameter(position, value); return this; } /** * Set a named bind parameter. Named parameters have a colon to prefix the name. */ @Override public Query<T> setParameter(String name, Object value) { if (namedParams != null) { ONamedParam param = namedParams.get(name); if (param != null) { param.setValue(value); return this; } } if (bindParams == null) { bindParams = new BindParams(); } bindParams.setParameter(name, value); return this; } @Override public boolean checkPagingOrderBy() { return orderById && !useDocStore; } @Override public boolean orderByIsEmpty() { return orderBy == null || orderBy.isEmpty(); } @Override public OrderBy<T> getOrderBy() { return orderBy; } @Override @Deprecated public OrderBy<T> orderBy() { return order(); } @Override public OrderBy<T> order() { if (orderBy == null) { orderBy = new OrderBy<>(this, null); } return orderBy; } @Override @Deprecated public Query<T> orderBy(String orderByClause) { return order(orderByClause); } @Override public Query<T> order(String orderByClause) { if (orderByClause == null || orderByClause.trim().isEmpty()) { this.orderBy = null; } else { this.orderBy = new OrderBy<>(this, orderByClause); } return this; } @Override @Deprecated public Query<T> setOrderBy(OrderBy<T> orderBy) { return setOrder(orderBy); } @Override public Query<T> setOrder(OrderBy<T> orderBy) { this.orderBy = orderBy; if (orderBy != null) { orderBy.setQuery(this); } return this; } @Override public boolean isManualId() { return manualId; } @Override public void setManualId() { if (detail != null && detail.hasSelectClause()) { this.manualId = true; } } /** * return true if user specified to use SQL DISTINCT (effectively excludes id property). */ @Override public boolean isDistinct() { return distinct; } /** * Internally set to use SQL DISTINCT on the query but still have id property included. */ @Override public Query<T> setDistinct(boolean distinct) { this.distinct = distinct; return this; } @Override public Query<T> setCountDistinct(CountDistinctOrder countDistinctOrder) { this.countDistinctOrder = countDistinctOrder; return this; } @Override public boolean isCountDistinct() { return countDistinctOrder != null; } @Override public Class<T> getBeanType() { return beanType; } @Override public Class<? extends T> getInheritType() { return beanDescriptor.type(); } @SuppressWarnings("unchecked") @Override public Query<T> setInheritType(Class<? extends T> type) { if (type == beanType) { return this; } InheritInfo inheritInfo = rootBeanDescriptor.inheritInfo(); inheritInfo = inheritInfo == null ? null : inheritInfo.readType(type); if (inheritInfo == null) { throw new IllegalArgumentException("Given type " + type + " is not a subtype of " + beanType); } beanDescriptor = (BeanDescriptor<T>) rootBeanDescriptor.descriptor(type); return this; } @Override public String toString() { return "Query [" + whereExpressions + "]"; } @Override public TableJoin getM2mIncludeJoin() { return m2mIncludeJoin; } @Override public void setM2MIncludeJoin(TableJoin m2mIncludeJoin) { this.m2mIncludeJoin = m2mIncludeJoin; } @Override public Query<T> setDisableLazyLoading(boolean disableLazyLoading) { this.disableLazyLoading = disableLazyLoading; return this; } @Override public boolean isDisableLazyLoading() { return disableLazyLoading; } @Override public int getFirstRow() { return firstRow; } @Override public Query<T> setFirstRow(int firstRow) { this.firstRow = firstRow; return this; } @Override public int getMaxRows() { return maxRows; } @Override public Query<T> setMaxRows(int maxRows) { this.maxRows = maxRows; return this; } @Override public String getMapKey() { return mapKey; } @Override public Query<T> setMapKey(String mapKey) { this.mapKey = mapKey; return this; } @Override public Object getId() { return id; } @Override public Query<T> setId(Object id) { if (id == null) { throw new NullPointerException("The id is null"); } this.id = id; return this; } @Override public BindParams getBindParams() { return bindParams; } @Override public Query<T> where(Expression expression) { where().add(expression); return this; } @Override public ExpressionList<T> text() { if (textExpressions == null) { useDocStore = true; textExpressions = new DefaultExpressionList<>(this); } return textExpressions; } @Override public ExpressionList<T> where() { if (whereExpressions == null) { whereExpressions = new DefaultExpressionList<>(this, null); } return whereExpressions; } @Override public void simplifyExpressions() { if (whereExpressions != null) { whereExpressions.simplify(); } } @Override public Query<T> having(Expression expression) { having().add(expression); return this; } @Override public ExpressionList<T> having() { if (havingExpressions == null) { havingExpressions = new DefaultExpressionList<>(this, null); } return havingExpressions; } @Override public SpiExpressionList<T> getHavingExpressions() { return havingExpressions; } @Override public SpiExpressionList<T> getWhereExpressions() { return whereExpressions; } @Override public SpiExpressionList<T> getTextExpression() { return textExpressions; } @Override public String getGeneratedSql() { return generatedSql; } @Override public void setGeneratedSql(String generatedSql) { this.generatedSql = generatedSql; } @Override public void checkNamedParameters() { if (namedParams != null) { for (ONamedParam value : namedParams.values()) { value.checkValueSet(); } } } @Override public SpiNamedParam createNamedParameter(String name) { if (namedParams == null) { namedParams = new HashMap<>(); } return namedParams.computeIfAbsent(name, ONamedParam::new); } @Override public void setDefaultFetchBuffer(int fetchSize) { if (bufferFetchSizeHint == 0) { bufferFetchSizeHint = fetchSize; } } @Override public Query<T> setBufferFetchSizeHint(int bufferFetchSizeHint) { this.bufferFetchSizeHint = bufferFetchSizeHint; return this; } @Override public int getBufferFetchSizeHint() { return bufferFetchSizeHint; } @Override public Query<T> setDisableReadAuditing() { this.disableReadAudit = true; return this; } @Override public boolean isDisableReadAudit() { return disableReadAudit; } @Override public boolean isFutureFetch() { return futureFetch; } @Override public void setFutureFetch(boolean backgroundFetch) { this.futureFetch = backgroundFetch; } @Override public void setFutureFetchAudit(ReadEvent event) { this.futureFetchAudit = event; } @Override public ReadEvent getFutureFetchAudit() { return futureFetchAudit; } @Override public Query<T> setBaseTable(String baseTable) { this.baseTable = baseTable; return this; } @Override public String getBaseTable() { return baseTable; } @Override public Query<T> alias(String alias) { this.rootTableAlias = alias; return this; } @Override public String getAlias() { return rootTableAlias; } @Override public String getAlias(String defaultAlias) { return rootTableAlias != null ? rootTableAlias : defaultAlias; } @Override public Set<String> validate() { return server.validateQuery(this); } /** * Validate all the expression properties/paths given the bean descriptor. */ @Override public Set<String> validate(BeanType<T> desc) { SpiExpressionValidation validation = new SpiExpressionValidation(desc); if (whereExpressions != null) { whereExpressions.validate(validation); } if (havingExpressions != null) { havingExpressions.validate(validation); } if (orderBy != null) { for (Property property : orderBy.getProperties()) { validation.validate(property.getProperty()); } } return validation.getUnknownProperties(); } void setUpdateProperties(OrmUpdateProperties updateProperties) { this.updateProperties = updateProperties; } @Override public OrmUpdateProperties getUpdateProperties() { return updateProperties; } @Override public ProfileLocation getProfileLocation() { return profileLocation; } @Override public void handleLoadError(String fullName, Exception e) { if (!allowLoadErrors) { throw new PersistenceException("Error loading on " + fullName, e); } } @Override public Query<T> orderById(boolean orderById) { this.orderById = orderById; return this; } }
// // This file is auto-generated. Please don't modify it! // package org.opencv.ml; // C++: class CvBoostParams public class CvBoostParams extends CvDTreeParams { protected CvBoostParams(long addr) { super(addr); } // // C++: CvBoostParams::CvBoostParams() // public CvBoostParams() { super( CvBoostParams_0() ); return; } // // C++: int CvBoostParams::boost_type // public int get_boost_type() { int retVal = get_boost_type_0(nativeObj); return retVal; } // // C++: void CvBoostParams::boost_type // public void set_boost_type(int boost_type) { set_boost_type_0(nativeObj, boost_type); return; } // // C++: int CvBoostParams::weak_count // public int get_weak_count() { int retVal = get_weak_count_0(nativeObj); return retVal; } // // C++: void CvBoostParams::weak_count // public void set_weak_count(int weak_count) { set_weak_count_0(nativeObj, weak_count); return; } // // C++: int CvBoostParams::split_criteria // public int get_split_criteria() { int retVal = get_split_criteria_0(nativeObj); return retVal; } // // C++: void CvBoostParams::split_criteria // public void set_split_criteria(int split_criteria) { set_split_criteria_0(nativeObj, split_criteria); return; } // // C++: double CvBoostParams::weight_trim_rate // public double get_weight_trim_rate() { double retVal = get_weight_trim_rate_0(nativeObj); return retVal; } // // C++: void CvBoostParams::weight_trim_rate // public void set_weight_trim_rate(double weight_trim_rate) { set_weight_trim_rate_0(nativeObj, weight_trim_rate); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: CvBoostParams::CvBoostParams() private static native long CvBoostParams_0(); // C++: int CvBoostParams::boost_type private static native int get_boost_type_0(long nativeObj); // C++: void CvBoostParams::boost_type private static native void set_boost_type_0(long nativeObj, int boost_type); // C++: int CvBoostParams::weak_count private static native int get_weak_count_0(long nativeObj); // C++: void CvBoostParams::weak_count private static native void set_weak_count_0(long nativeObj, int weak_count); // C++: int CvBoostParams::split_criteria private static native int get_split_criteria_0(long nativeObj); // C++: void CvBoostParams::split_criteria private static native void set_split_criteria_0(long nativeObj, int split_criteria); // C++: double CvBoostParams::weight_trim_rate private static native double get_weight_trim_rate_0(long nativeObj); // C++: void CvBoostParams::weight_trim_rate private static native void set_weight_trim_rate_0(long nativeObj, double weight_trim_rate); // native support for java finalize() private static native void delete(long nativeObj); }
package org.sagebionetworks.bridge.upload; /** Enum defining the valid values for upload format. */ public enum UploadFormat { V1_LEGACY, V2_GENERIC, }
/* * Copyright (C) 2021 Scott Shaffer - 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.tipplerow.jam.vector; import lombok.NonNull; import java.util.Arrays; import java.util.stream.DoubleStream; /** * Provides an implementation of the JamVector interface using an existing * bare array as the underlying storage. * * @author Scott Shaffer */ final class ArrayWrapper implements VectorView { @NonNull private final double[] array; private ArrayWrapper(double[] array) { this.array = array; } /** * Creates a new wrapper for an existing bare array. * * @param array the array to serve as the vector storage. * * @return a new wrapper for the specified array. */ public static ArrayWrapper wrap(double[] array) { return new ArrayWrapper(array); } @Override public double get(int index) { return array[index]; } @Override public int length() { return array.length; } @Override public DoubleStream streamValues() { return Arrays.stream(array); } @Override public double[] toArray() { return Arrays.copyOf(array, length()); } }
package demo.model; /** * @author noear 2022/1/18 created */ public class UserModel { public Integer id; public String name; }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alipay.sofa.lookout.gateway.core.prototype.queue; import com.alipay.lookout.api.Gauge; import com.alipay.lookout.api.Id; import com.alipay.lookout.api.Registry; import com.alipay.sofa.lookout.gateway.core.common.Executors; import com.alipay.sofa.lookout.gateway.core.prototype.pipeline.AbstractProcessor; import com.alipay.sofa.lookout.gateway.core.queue.MappedFilePersistentQueue; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; /** * 配合序列化器, 可以将这个类做成通用的, 从而提升到prototype里 * * @author xiangfeng.xzc * @date 2018/11/15 */ public class BasePersistQueueProcessor<T> extends AbstractProcessor<T, T> { protected static final Logger LOGGER = LoggerFactory .getLogger(BasePersistQueueProcessor.class); private static final String QUEUE_SIZE_METRIC_NAME = "queue.size"; private static final long BYTES_OF_MB = 1024 * 1024; private final int threads; private final String dir; private final String queueName; private final Registry registry; private final Serializer<T> serializer; private MappedFilePersistentQueue queue; private ExecutorService executor; public BasePersistQueueProcessor(int threads, String dir, String queueName, Registry registry, Serializer<T> serializer) { Preconditions.checkArgument(threads > 0 && threads <= 100); this.threads = threads; this.dir = Preconditions.checkNotNull(dir); this.queueName = Preconditions.checkNotNull(queueName); this.registry = Preconditions.checkNotNull(registry); this.serializer = Preconditions.checkNotNull(serializer); } @Override protected void doStart() { try { queue = new MappedFilePersistentQueue(dir, queueName); Map<String, String> tags = new HashMap<>(); tags.put("name", queueName); Id id = registry.createId(QUEUE_SIZE_METRIC_NAME, tags); registry.gauge(id, (Gauge<Number>) () -> queue.getBackFileSize() / BYTES_OF_MB); } catch (IOException e) { throw new RuntimeException(e); } ThreadFactory tf = new ThreadFactoryBuilder() .setNameFormat("queue_processor_poller-%d") .setThreadFactory(DequeueThread::new) .build(); executor = Executors.newFixedThreadPoolExecutor( threads, 100, "queue_processor_poller", tf, new ThreadPoolExecutor.AbortPolicy(), registry); // 启动线程 for (int i = 0; i < threads; i++) { this.executor.execute(this::poll); } } private void poll() { Thread currentThread = Thread.currentThread(); while (!currentThread.isInterrupted()) { try { byte[] data = queue.consume(); if (data != null) { T t = serializer.deserialize(data); onOutput(t); } else { Thread.sleep(100); } } catch (InterruptedException e) { currentThread.interrupt(); break; } catch (Exception e) { LOGGER.error("queue post process error", e); } } } @Override public void onInput(T t) { byte[] bytes = serializer.serialize(t); if (bytes != null) { queue.produce(bytes); } } }
/* * Copyright 2021 TTT. * * 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 ttt.utils.engines.enums; /** * I tipi di metodi che possono essere utilizzati da un Engine per completare e * richiedere valori. * * @author TTT */ public enum MethodType { /** * Segnala un metodo di tipo GET, con valore di ritorno. */ GET, /** * Segnala un metodo di tipo SET, senza necessariamente un metodo di ritorno * ma che deve rispettare il numero di parametri e i tipi definiti * dall'engine che deve utilizzare il metodo. */ SET, /** * Segnala un metodo che viene chiamato solamente dopo aver chiamato tutti i * metodi set e aver inizializzato i valori base.<br> * Non necessita un ritorno ma deve rispettare il numero di parametri e i * tipi definiti dall'engine che deve utilizzare il metodo. */ CALC, EVENT }
package dao; import models.Department; import models.News; import models.User; import org.sql2o.Connection; import org.sql2o.Sql2o; import org.sql2o.Sql2oException; import java.util.List; public class Sql2oUsersDao implements IUsersDao{ private final Sql2o sql2o; public Sql2oUsersDao(Sql2o sql2o) { this.sql2o = sql2o; } @Override public void add(User user) { String sql = "INSERT INTO users(name, title, roles, associated_department) VALUES (:name, :title, :roles, :associated_department);"; try (Connection con = sql2o.open()) { int id = (int) con.createQuery(sql, true) .bind(user) .executeUpdate() .getKey(); user.setId(id); } catch (Sql2oException ex) { System.out.println(ex); } } @Override public void addUserNewsDepartment(User user, News news, Department department) { } @Override public List<User> getAll() { try (Connection con = sql2o.open()) { return con.createQuery("SELECT * FROM users") .executeAndFetch(User.class); } } @Override public User findById(int id) { try (Connection con = sql2o.open()) { return con.createQuery("SELECT * FROM users WHERE id = :id") .addParameter("id", id) .executeAndFetchFirst(User.class); } } @Override public List<Department> getUserDepartment(int blackout_id) { return null; } @Override public List<User> getUserNews(int blackout_id) { return null; } @Override public void deleteById(int id) { String sql = "DELETE from users WHERE id=:id"; try (Connection con = sql2o.open()) { con.createQuery(sql) .addParameter("id", id) .executeUpdate(); } catch (Sql2oException ex) { System.out.println(ex); } } @Override public void clearAll() { String sql = "DELETE from users"; try (Connection con = sql2o.open()) { con.createQuery(sql).executeUpdate(); } catch (Sql2oException ex) { System.out.println(ex); } } }
// Copyright (c) 2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.daml.ledger.api.v1.ValueOuterClass; import com.daml.ledger.javaapi.data.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import tests.numerictest.*; import tests.numerictest.nestednumericbox.*; @RunWith(JUnitPlatform.class) public class NumericTest { void checkRecord(NumericBox myRecord) { assertEquals(myRecord.decimal, decimalValue()); assertEquals(myRecord.numeric0, numeric0Value()); assertEquals(myRecord.numeric37, numeric37Value()); NumericBox myNestedRecord = ((Nested) myRecord.nestedBox).numericBoxValue; assertEquals(myNestedRecord.decimal, decimalValue().negate()); assertEquals(myNestedRecord.numeric0, numeric0Value().negate()); assertEquals(myNestedRecord.numeric37, numeric37Value().negate()); assertTrue(myNestedRecord.nestedBox instanceof NoMore); } @Test void deserializableFromRecord() { ArrayList<Record.Field> fieldsList_ = new ArrayList<>(10); fieldsList_.add(new Record.Field("decimal", new Numeric(decimalValue().negate()))); fieldsList_.add(new Record.Field("numeric0", new Numeric(numeric0Value().negate()))); fieldsList_.add(new Record.Field("numeric37", new Numeric(numeric37Value().negate()))); fieldsList_.add(new Record.Field("nested", new Variant("NoMore", Unit.getInstance()))); Record nestedRecord = new Record(fieldsList_); ArrayList<Record.Field> fieldsList = new ArrayList<>(10); fieldsList.add(new Record.Field("decimal", new Numeric(decimalValue()))); fieldsList.add(new Record.Field("numeric0", new Numeric(numeric0Value()))); fieldsList.add(new Record.Field("numeric37", new Numeric(numeric37Value()))); fieldsList.add(new Record.Field("nestedBox", new Variant("Nested", nestedRecord))); Value value = new Record(fieldsList); NumericBox record = NumericBox.fromValue(value); checkRecord(record); assertTrue( "to value uses original daml lf names for fields", record.toValue().getFieldsMap().get("numeric37").asNumeric().isPresent()); } @Test void objectMethodsWork() { NumericBox record1 = numericBox(); NumericBox record2 = numericBox(); assertEquals(record1, record2); assertEquals(record1.hashCode(), record2.hashCode()); } ValueOuterClass.Record.Builder recordBuilder() { return ValueOuterClass.Record.newBuilder(); } ValueOuterClass.RecordField.Builder recordFieldBuilder() { return ValueOuterClass.RecordField.newBuilder(); } ValueOuterClass.Value.Builder valueBuilder() { return ValueOuterClass.Value.newBuilder(); } ValueOuterClass.Variant.Builder variantBuilder() { return ValueOuterClass.Variant.newBuilder(); } com.google.protobuf.Empty.Builder emptyBuilder() { return com.google.protobuf.Empty.newBuilder(); } @Test void outerRecordRoundtrip() { ValueOuterClass.Value protoValue = valueBuilder() .setRecord( recordBuilder() .addFields( recordFieldBuilder() .setLabel("decimal") .setValue(valueBuilder().setNumeric("10.0000000000"))) .addFields( recordFieldBuilder() .setLabel("numeric0") .setValue( valueBuilder() .setNumeric("99999999999999999999999999999999999999"))) .addFields( recordFieldBuilder() .setLabel("numeric37") .setValue( valueBuilder() .setNumeric("9.9999999999999999999999999999999999999"))) .addFields( recordFieldBuilder() .setLabel("nestedBox") .setValue( valueBuilder() .setVariant( variantBuilder() .setConstructor("Nested") .setValue( valueBuilder() .setRecord( recordBuilder() .addFields( recordFieldBuilder() .setLabel("decimal") .setValue( valueBuilder() .setNumeric( "-10.0000000000"))) .addFields( recordFieldBuilder() .setLabel("numeric0") .setValue( valueBuilder() .setNumeric( "-99999999999999999999999999999999999999"))) .addFields( recordFieldBuilder() .setLabel("numeric37") .setValue( valueBuilder() .setNumeric( "-9.9999999999999999999999999999999999999"))) .addFields( recordFieldBuilder() .setLabel("nestedBox") .setValue( valueBuilder() .setVariant( variantBuilder() .setConstructor( "NoMore") .setValue( valueBuilder() .setUnit( emptyBuilder()))))))))))) .build(); Value value = Value.fromProto(protoValue); NumericBox fromValue = NumericBox.fromValue(value); NumericBox fromConstructor = numericBox(); NumericBox fromRoundTrip = NumericBox.fromValue(Value.fromProto(fromConstructor.toValue().toProto())); assertEquals(fromValue, fromConstructor); assertEquals(fromConstructor.toValue(), value); assertEquals(fromConstructor.toValue().toProto(), protoValue); assertEquals(fromRoundTrip, fromConstructor); } BigDecimal maxValue(int s) { return new BigDecimal(BigInteger.TEN.pow(38).subtract(BigInteger.ONE), s); } java.math.BigDecimal decimalValue() { return BigDecimal.TEN.setScale(10); } java.math.BigDecimal numeric0Value() { return maxValue(0); } java.math.BigDecimal numeric37Value() { return maxValue(37); } NumericBox numericBox() { return new NumericBox( decimalValue(), numeric0Value(), numeric37Value(), new Nested( new NumericBox( decimalValue().negate(), numeric0Value().negate(), numeric37Value().negate(), new NoMore(Unit.getInstance())))); } }
/** * Copyright 2021 Shulie Technology, Co.Ltd * Email: shulie@shulie.io * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * See the License for the specific language governing permissions and * limitations under the License. */ package com.pamirs.attach.plugin.apache.kafka.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.shulie.instrument.simulator.api.reflect.Reflect; import com.shulie.instrument.simulator.api.reflect.ReflectException; /** * @Author <a href="tangyuhan@shulie.io">yuhan.tang</a> * @package: com.pamirs.attach.plugin.apache.kafka.util * @Date 2020-04-10 18:43 */ public class ReflectUtil { private static final Map<String, Field> FIELDMAP = new ConcurrentHashMap<String, Field>(); private static final Map<String, Method> METHODMAP = new ConcurrentHashMap<String, Method>(); public static Field getField(Object o, String fieldName) throws Exception { String key = o.toString() + "-" + fieldName; Field field = FIELDMAP.get(key); if (null == field) { if (o instanceof Class) { Class clazz = (Class) o; field = clazz.getDeclaredField(fieldName); } else { Class clazz = o.getClass(); field = clazz.getDeclaredField(fieldName); } if (!field.isAccessible()) { field.setAccessible(true); } FIELDMAP.put(key, field); } return field; } public static Method getMethod(Object o, String fieldName, Class... pamras) throws Exception { String key = o.toString() + "-" + fieldName; Method method = METHODMAP.get(key); if (null == method) { if (o instanceof Class) { Class clazz = (Class) o; method = clazz.getDeclaredMethod(fieldName, pamras); } else { Class clazz = o.getClass(); method = clazz.getDeclaredMethod(fieldName, pamras); } if (!method.isAccessible()) { method.setAccessible(true); } METHODMAP.put(key, method); } return method; } public static <T> T reflectSlience(Object obj, String name) { try { return Reflect.on(obj).get(name); } catch (ReflectException ignore) { return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.query; import com.azure.spring.data.cosmos.core.CosmosOperations; import com.azure.spring.data.cosmos.core.query.CosmosQuery; import org.springframework.data.repository.query.RepositoryQuery; import org.springframework.data.repository.query.ResultProcessor; import org.springframework.data.repository.query.ReturnedType; /** * Abstract class for cosmos query. */ public abstract class AbstractCosmosQuery implements RepositoryQuery { private final CosmosQueryMethod method; protected final CosmosOperations operations; /** * Initialization * * @param method CosmosQueryMethod * @param operations CosmosOperations */ public AbstractCosmosQuery(CosmosQueryMethod method, CosmosOperations operations) { this.method = method; this.operations = operations; } /** * Executes the {@link AbstractCosmosQuery} with the given parameters. * * @param parameters must not be {@literal null}. * @return execution result. Can be {@literal null}. */ @Override public Object execute(Object[] parameters) { final CosmosParameterAccessor accessor = new CosmosParameterParameterAccessor(method, parameters); final CosmosQuery query = createQuery(accessor); final ResultProcessor processor = method.getResultProcessor().withDynamicProjection(accessor); final String container = ((CosmosEntityMetadata) method.getEntityInformation()).getContainerName(); final CosmosQueryExecution execution = getExecution(accessor, processor.getReturnedType()); return execution.execute(query, processor.getReturnedType().getDomainType(), container); } /** * Determines the appropriate execution path for a query * * @param returnedType The return type of the method * @param accessor Object for accessing method parameters * @return the execution type needed to handle the query */ protected CosmosQueryExecution getExecution(CosmosParameterAccessor accessor, ReturnedType returnedType) { if (isDeleteQuery()) { return new CosmosQueryExecution.DeleteExecution(operations); } else if (isPageQuery()) { return new CosmosQueryExecution.PagedExecution(operations, accessor.getPageable()); } else if (isExistsQuery()) { return new CosmosQueryExecution.ExistsExecution(operations); } else if (isCollectionQuery()) { return new CosmosQueryExecution.MultiEntityExecution(operations); } else { return new CosmosQueryExecution.SingleEntityExecution(operations, returnedType); } } /** * Get method of query * * @return CosmosQueryMethod */ public CosmosQueryMethod getQueryMethod() { return method; } protected abstract CosmosQuery createQuery(CosmosParameterAccessor accessor); protected abstract boolean isDeleteQuery(); protected abstract boolean isExistsQuery(); protected boolean isPageQuery() { return method.isPageQuery(); } protected boolean isCollectionQuery() { return method.isCollectionQuery(); } }
/** * 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.avro.io; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; import org.apache.avro.Schema; import org.apache.avro.util.Utf8; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Parameterized.class) public class TestValidatingIO { enum Encoding { BINARY, BLOCKING_BINARY, JSON, } private static final Logger LOG = LoggerFactory.getLogger(TestValidatingIO.class); private Encoding eEnc; private int iSkipL; private String sJsSch; private String sCl; public TestValidatingIO (Encoding enc, int skip, String js, String cls) { this.eEnc = enc; this.iSkipL = skip; this.sJsSch = js; this.sCl = cls; } private static final int COUNT = 1; @Test public void testMain() throws IOException { for (int i = 0; i < COUNT; i++) { testOnce(new Schema.Parser().parse(sJsSch), sCl, iSkipL, eEnc); } } private void testOnce(Schema schema, String calls, int skipLevel, Encoding encoding) throws IOException { Object[] values = randomValues(calls); print(eEnc, iSkipL, schema, schema, values, values); byte[] bytes = make(schema, calls, values, encoding); check(schema, bytes, calls, values, skipLevel, encoding); } public static byte[] make(Schema sc, String calls, Object[] values, Encoding encoding) throws IOException { EncoderFactory factory = EncoderFactory.get(); ByteArrayOutputStream ba = new ByteArrayOutputStream(); Encoder bvo = null; switch (encoding) { case BINARY: bvo = factory.binaryEncoder(ba, null); break; case BLOCKING_BINARY: bvo = factory.blockingBinaryEncoder(ba, null); break; case JSON: bvo = factory.jsonEncoder(sc, ba); break; } Encoder vo = factory.validatingEncoder(sc, bvo); generate(vo, calls, values); vo.flush(); return ba.toByteArray(); } public static class InputScanner { private final char[] chars; private int cpos = 0; public InputScanner(char[] chars) { this.chars = chars; } public boolean next() { if (cpos < chars.length) { cpos++; } return cpos != chars.length; } public char cur() { return chars[cpos]; } public boolean isDone() { return cpos == chars.length; } } public static void generate(Encoder vw, String calls, Object[] values) throws IOException { InputScanner cs = new InputScanner(calls.toCharArray()); int p = 0; while (! cs.isDone()) { char c = cs.cur(); cs.next(); switch (c) { case 'N': vw.writeNull(); break; case 'B': boolean b = (Boolean) values[p++]; vw.writeBoolean(b); break; case 'I': int ii = (Integer) values[p++]; vw.writeInt(ii); break; case 'L': long l = (Long) values[p++]; vw.writeLong(l); break; case 'F': float f = (Float) values[p++]; vw.writeFloat(f); break; case 'D': double d = (Double) values[p++]; vw.writeDouble(d); break; case 'S': { extractInt(cs); String s = (String) values[p++]; vw.writeString(new Utf8(s)); break; } case 'K': { extractInt(cs); String s = (String) values[p++]; vw.writeString(s); break; } case 'b': { extractInt(cs); byte[] bb = (byte[]) values[p++]; vw.writeBytes(bb); break; } case 'f': { extractInt(cs); byte[] bb = (byte[]) values[p++]; vw.writeFixed(bb); break; } case 'e': { int e = extractInt(cs); vw.writeEnum(e); break; } case '[': vw.writeArrayStart(); break; case ']': vw.writeArrayEnd(); break; case '{': vw.writeMapStart(); break; case '}': vw.writeMapEnd(); break; case 'c': vw.setItemCount(extractInt(cs)); break; case 's': vw.startItem(); break; case 'U': { vw.writeIndex(extractInt(cs)); break; } default: fail(); break; } } } public static Object[] randomValues(String calls) { Random r = new Random(0L); InputScanner cs = new InputScanner(calls.toCharArray()); List<Object> result = new ArrayList<Object>(); while (! cs.isDone()) { char c = cs.cur(); cs.next(); switch (c) { case 'N': break; case 'B': result.add(r.nextBoolean()); break; case 'I': result.add(r.nextInt()); break; case 'L': result.add(new Long(r.nextInt())); break; case 'F': result.add(new Float(r.nextInt())); break; case 'D': result.add(new Double(r.nextInt())); break; case 'S': case 'K': result.add(nextString(r, extractInt(cs))); break; case 'b': case 'f': result.add(nextBytes(r, extractInt(cs))); break; case 'e': case 'c': case 'U': extractInt(cs); case '[': case ']': case '{': case '}': case 's': break; default: fail(); break; } } return result.toArray(); } private static int extractInt(InputScanner sc) { int r = 0; while (! sc.isDone()) { if (Character.isDigit(sc.cur())) { r = r * 10 + sc.cur() - '0'; sc.next(); } else { break; } } return r; } private static byte[] nextBytes(Random r, int length) { byte[] bb = new byte[length]; r.nextBytes(bb); return bb; } private static String nextString(Random r, int length) { char[] cc = new char[length]; for (int i = 0; i < length; i++) { cc[i] = (char) ('A' + r.nextInt(26)); } return new String(cc); } private static void check(Schema sc, byte[] bytes, String calls, Object[] values, final int skipLevel, Encoding encoding) throws IOException { // dump(bytes); // System.out.println(new String(bytes, "UTF-8")); Decoder bvi = null; switch (encoding) { case BINARY: case BLOCKING_BINARY: bvi = DecoderFactory.get().binaryDecoder(bytes, null); break; case JSON: InputStream in = new ByteArrayInputStream(bytes); bvi = new JsonDecoder(sc, in); } Decoder vi = new ValidatingDecoder(sc, bvi); check(vi, calls, values, skipLevel); } public static void check(Decoder vi, String calls, Object[] values, final int skipLevel) throws IOException { InputScanner cs = new InputScanner(calls.toCharArray()); int p = 0; int level = 0; long[] counts = new long[100]; boolean[] isArray = new boolean[100]; boolean[] isEmpty = new boolean[100]; while (! cs.isDone()) { final char c = cs.cur(); cs.next(); switch (c) { case 'N': vi.readNull(); break; case 'B': assertEquals(values[p++], vi.readBoolean()); break; case 'I': assertEquals(values[p++], vi.readInt()); break; case 'L': assertEquals(values[p++], vi.readLong()); break; case 'F': if (!(values[p] instanceof Float)) fail(); float f = (Float) values[p++]; assertEquals(f, vi.readFloat(), Math.abs(f / 1000)); break; case 'D': if (!(values[p] instanceof Double)) fail(); double d = (Double) values[p++]; assertEquals(d, vi.readDouble(), Math.abs(d / 1000)); break; case 'S': extractInt(cs); if (level == skipLevel) { vi.skipString(); p++; } else { String s = (String) values[p++]; assertEquals(new Utf8(s), vi.readString(null)); } break; case 'K': extractInt(cs); if (level == skipLevel) { vi.skipString(); p++; } else { String s = (String) values[p++]; assertEquals(new Utf8(s), vi.readString(null)); } break; case 'b': extractInt(cs); if (level == skipLevel) { vi.skipBytes(); p++; } else { byte[] bb = (byte[]) values[p++]; ByteBuffer bb2 = vi.readBytes(null); byte[] actBytes = new byte[bb2.remaining()]; System.arraycopy(bb2.array(), bb2.position(), actBytes, 0, bb2.remaining()); assertArrayEquals(bb, actBytes); } break; case 'f': { int len = extractInt(cs); if (level == skipLevel) { vi.skipFixed(len); p++; } else { byte[] bb = (byte[]) values[p++]; byte[] actBytes = new byte[len]; vi.readFixed(actBytes); assertArrayEquals(bb, actBytes); } } break; case 'e': { int e = extractInt(cs); if (level == skipLevel) { vi.readEnum(); } else { assertEquals(e, vi.readEnum()); } } break; case '[': if (level == skipLevel) { p += skip(cs, vi, true); break; } else { level++; counts[level] = vi.readArrayStart(); isArray[level] = true; isEmpty[level] = counts[level] == 0; continue; } case '{': if (level == skipLevel) { p += skip(cs, vi, false); break; } else { level++; counts[level] = vi.readMapStart(); isArray[level] = false; isEmpty[level] = counts[level] == 0; continue; } case ']': assertEquals(0, counts[level]); if (! isEmpty[level]) { assertEquals(0, vi.arrayNext()); } level--; break; case '}': assertEquals(0, counts[level]); if (! isEmpty[level]) { assertEquals(0, vi.mapNext()); } level--; break; case 's': if (counts[level] == 0) { if (isArray[level]) { counts[level] = vi.arrayNext(); } else { counts[level] = vi.mapNext(); } } counts[level]--; continue; case 'c': extractInt(cs); continue; case 'U': { int idx = extractInt(cs); assertEquals(idx, vi.readIndex()); continue; } case 'R': ((ResolvingDecoder) vi).readFieldOrder(); continue; default: fail(); } } assertEquals(values.length, p); } private static int skip(InputScanner cs, Decoder vi, boolean isArray) throws IOException { final char end = isArray ? ']' : '}'; if (isArray) { assertEquals(0, vi.skipArray()); } else if (end == '}'){ assertEquals(0, vi.skipMap()); } int level = 0; int p = 0; while (! cs.isDone()) { char c = cs.cur(); cs.next(); switch (c) { case '[': case '{': ++level; break; case ']': case '}': if (c == end && level == 0) { return p; } level--; break; case 'B': case 'I': case 'L': case 'F': case 'D': case 'S': case 'K': case 'b': case 'f': case 'e': p++; break; } } throw new RuntimeException("Don't know how to skip"); } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(convertTo2dArray(encodings, skipLevels, testSchemas())); } private static Object[][] encodings = new Object[][] { { Encoding.BINARY }, { Encoding.BLOCKING_BINARY }, { Encoding.JSON } }; private static Object[][] skipLevels = new Object[][] { { -1 }, { 0 }, { 1 }, { 2 }, }; public static Object[][] convertTo2dArray(final Object[][]... values) { ArrayList<Object[]> ret = new ArrayList<Object[]>(); Iterator<Object[]> iter = cartesian(values); while (iter.hasNext()) { Object[] objects = iter.next(); ret.add(objects); } Object[][] retArrays = new Object[ret.size()][]; for (int i = 0; i < ret.size(); i++) { retArrays[i] = ret.get(i); } return retArrays; } /** * Returns the Cartesian product of input sequences. */ public static Iterator<Object[]> cartesian(final Object[][]... values) { return new Iterator<Object[]>() { private int[] pos = new int[values.length]; @Override public boolean hasNext() { return pos[0] < values[0].length; } @Override public Object[] next() { Object[][] v = new Object[values.length][]; for (int i = 0; i < v.length; i++) { v[i] = values[i][pos[i]]; } for (int i = v.length - 1; i >= 0; i--) { if (++pos[i] == values[i].length) { if (i != 0) { pos[i] = 0; } } else { break; } } return concat(v); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * Concatenates the input sequences in order and forms a longer sequence. */ public static Object[] concat(Object[]... oo) { int l = 0; for (Object[] o : oo) { l += o.length; } Object[] result = new Object[l]; l = 0; for (Object[] o : oo) { System.arraycopy(o, 0, result, l, o.length); l += o.length; } return result; } /** * Pastes incoming tables to form a wider table. All incoming tables * should be of same height. */ static Object[][] paste(Object[][]... in) { Object[][] result = new Object[in[0].length][]; Object[][] cc = new Object[in.length][]; for (int i = 0; i < result.length; i++) { for (int j = 0; j < cc.length; j++) { cc[j] = in[j][i]; } result[i] = concat(cc); } return result; } public static Object[][] testSchemas() { /** * The first argument is a schema. * The second one is a sequence of (single character) mnemonics: * N null * B boolean * I int * L long * F float * D double * K followed by integer - key-name (and its length) in a map * S followed by integer - string and its length * b followed by integer - bytes and length * f followed by integer - fixed and length * c Number of items to follow in an array/map. * U followed by integer - Union and its branch * e followed by integer - Enum and its value * [ Start array * ] End array * { Start map * } End map * s start item */ return new Object[][] { { "\"null\"", "N" }, { "\"boolean\"", "B" }, { "\"int\"", "I" }, { "\"long\"", "L" }, { "\"float\"", "F" }, { "\"double\"", "D" }, { "\"string\"", "S0" }, { "\"string\"", "S10" }, { "\"bytes\"", "b0" }, { "\"bytes\"", "b10" }, { "{\"type\":\"fixed\", \"name\":\"fi\", \"size\": 1}", "f1" }, { "{\"type\":\"fixed\", \"name\":\"fi\", \"size\": 10}", "f10" }, { "{\"type\":\"enum\", \"name\":\"en\", \"symbols\":[\"v1\", \"v2\"]}", "e1" }, { "{\"type\":\"array\", \"items\": \"boolean\"}", "[]", }, { "{\"type\":\"array\", \"items\": \"int\"}", "[]", }, { "{\"type\":\"array\", \"items\": \"long\"}", "[]", }, { "{\"type\":\"array\", \"items\": \"float\"}", "[]", }, { "{\"type\":\"array\", \"items\": \"double\"}", "[]", }, { "{\"type\":\"array\", \"items\": \"string\"}", "[]", }, { "{\"type\":\"array\", \"items\": \"bytes\"}", "[]", }, { "{\"type\":\"array\", \"items\":{\"type\":\"fixed\", " + "\"name\":\"fi\", \"size\": 10}}", "[]" }, { "{\"type\":\"array\", \"items\": \"boolean\"}", "[c1sB]" }, { "{\"type\":\"array\", \"items\": \"int\"}", "[c1sI]" }, { "{\"type\":\"array\", \"items\": \"long\"}", "[c1sL]" }, { "{\"type\":\"array\", \"items\": \"float\"}", "[c1sF]" }, { "{\"type\":\"array\", \"items\": \"double\"}", "[c1sD]" }, { "{\"type\":\"array\", \"items\": \"string\"}", "[c1sS10]" }, { "{\"type\":\"array\", \"items\": \"bytes\"}", "[c1sb10]" }, { "{\"type\":\"array\", \"items\": \"int\"}", "[c1sIc1sI]" }, { "{\"type\":\"array\", \"items\": \"int\"}", "[c2sIsI]" }, { "{\"type\":\"array\", \"items\":{\"type\":\"fixed\", " + "\"name\":\"fi\", \"size\": 10}}", "[c2sf10sf10]" }, { "{\"type\":\"map\", \"values\": \"boolean\"}", "{}" }, { "{\"type\":\"map\", \"values\": \"int\"}", "{}" }, { "{\"type\":\"map\", \"values\": \"long\"}", "{}" }, { "{\"type\":\"map\", \"values\": \"float\"}", "{}" }, { "{\"type\":\"map\", \"values\": \"double\"}", "{}" }, { "{\"type\":\"map\", \"values\": \"string\"}", "{}" }, { "{\"type\":\"map\", \"values\": \"bytes\"}", "{}" }, { "{\"type\":\"map\", \"values\": " + "{\"type\":\"array\", \"items\":\"int\"}}", "{}" }, { "{\"type\":\"map\", \"values\": \"boolean\"}", "{c1sK5B}" }, { "{\"type\":\"map\", \"values\": \"int\"}", "{c1sK5I}" }, { "{\"type\":\"map\", \"values\": \"long\"}", "{c1sK5L}" }, { "{\"type\":\"map\", \"values\": \"float\"}", "{c1sK5F}" }, { "{\"type\":\"map\", \"values\": \"double\"}", "{c1sK5D}" }, { "{\"type\":\"map\", \"values\": \"string\"}", "{c1sK5S10}" }, { "{\"type\":\"map\", \"values\": \"bytes\"}", "{c1sK5b10}" }, { "{\"type\":\"map\", \"values\": " + "{\"type\":\"array\", \"items\":\"int\"}}", "{c1sK5[c3sIsIsI]}" }, { "{\"type\":\"map\", \"values\": \"boolean\"}", "{c1sK5Bc2sK5BsK5B}" }, { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f\", \"type\":\"boolean\"}]}", "B" }, { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f\", \"type\":\"int\"}]}", "I" }, { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f\", \"type\":\"long\"}]}", "L" }, { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f\", \"type\":\"float\"}]}", "F" }, { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f\", \"type\":\"double\"}]}", "D" }, { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f\", \"type\":\"string\"}]}", "S10" }, { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f\", \"type\":\"bytes\"}]}", "b10" }, // multi-field records { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f1\", \"type\":\"int\"}," + "{\"name\":\"f2\", \"type\":\"double\"}," + "{\"name\":\"f3\", \"type\":\"string\"}]}", "IDS10" }, { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f0\", \"type\":\"null\"}," + "{\"name\":\"f1\", \"type\":\"boolean\"}," + "{\"name\":\"f2\", \"type\":\"int\"}," + "{\"name\":\"f3\", \"type\":\"long\"}," + "{\"name\":\"f4\", \"type\":\"float\"}," + "{\"name\":\"f5\", \"type\":\"double\"}," + "{\"name\":\"f6\", \"type\":\"string\"}," + "{\"name\":\"f7\", \"type\":\"bytes\"}]}", "NBILFDS10b25" }, // record of records { "{\"type\":\"record\",\"name\":\"outer\",\"fields\":[" + "{\"name\":\"f1\", \"type\":{\"type\":\"record\", " + "\"name\":\"inner\", \"fields\":[" + "{\"name\":\"g1\", \"type\":\"int\"}, {\"name\":\"g2\", " + "\"type\":\"double\"}]}}," + "{\"name\":\"f2\", \"type\":\"string\"}," + "{\"name\":\"f3\", \"type\":\"inner\"}]}", "IDS10ID" }, // record with array { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f1\", \"type\":\"long\"}," + "{\"name\":\"f2\", " + "\"type\":{\"type\":\"array\", \"items\":\"int\"}}]}", "L[c1sI]" }, // record with map { "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f1\", \"type\":\"long\"}," + "{\"name\":\"f2\", " + "\"type\":{\"type\":\"map\", \"values\":\"int\"}}]}", "L{c1sK5I}" }, // array of records { "{\"type\":\"array\", \"items\":" + "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f1\", \"type\":\"long\"}," + "{\"name\":\"f2\", \"type\":\"null\"}]}}", "[c2sLNsLN]" }, { "{\"type\":\"array\", \"items\":" + "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f1\", \"type\":\"long\"}," + "{\"name\":\"f2\", " + "\"type\":{\"type\":\"array\", \"items\":\"int\"}}]}}", "[c2sL[c1sI]sL[c2sIsI]]" }, { "{\"type\":\"array\", \"items\":" + "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f1\", \"type\":\"long\"}," + "{\"name\":\"f2\", " + "\"type\":{\"type\":\"map\", \"values\":\"int\"}}]}}", "[c2sL{c1sK5I}sL{c2sK5IsK5I}]" }, { "{\"type\":\"array\", \"items\":" + "{\"type\":\"record\",\"name\":\"r\",\"fields\":[" + "{\"name\":\"f1\", \"type\":\"long\"}," + "{\"name\":\"f2\", " + "\"type\":[\"null\", \"int\"]}]}}", "[c2sLU0NsLU1I]" }, { "[\"boolean\"]", "U0B" }, { "[\"int\"]", "U0I" }, { "[\"long\"]", "U0L" }, { "[\"float\"]", "U0F" }, { "[\"double\"]", "U0D" }, { "[\"string\"]", "U0S10" }, { "[\"bytes\"]", "U0b10" }, { "[\"null\", \"int\"]", "U0N" }, { "[\"boolean\", \"int\"]", "U0B" }, { "[\"boolean\", \"int\"]", "U1I" }, { "[\"boolean\", {\"type\":\"array\", \"items\":\"int\"} ]", "U0B" }, { "[\"boolean\", {\"type\":\"array\", \"items\":\"int\"} ]", "U1[c1sI]" }, // Recursion { "{\"type\": \"record\", \"name\": \"Node\", \"fields\": [" + "{\"name\":\"label\", \"type\":\"string\"}," + "{\"name\":\"children\", \"type\":" + "{\"type\": \"array\", \"items\": \"Node\" }}]}", "S10[c1sS10[]]" }, { "{\"type\": \"record\", \"name\": \"Lisp\", \"fields\": [" + "{\"name\":\"value\", \"type\":[\"null\", \"string\"," + "{\"type\": \"record\", \"name\": \"Cons\", \"fields\": [" + "{\"name\":\"car\", \"type\":\"Lisp\"}," + "{\"name\":\"cdr\", \"type\":\"Lisp\"}]}]}]}", "U0N"}, { "{\"type\": \"record\", \"name\": \"Lisp\", \"fields\": [" + "{\"name\":\"value\", \"type\":[\"null\", \"string\"," + "{\"type\": \"record\", \"name\": \"Cons\", \"fields\": [" + "{\"name\":\"car\", \"type\":\"Lisp\"}," + "{\"name\":\"cdr\", \"type\":\"Lisp\"}]}]}]}", "U1S10"}, { "{\"type\": \"record\", \"name\": \"Lisp\", \"fields\": [" + "{\"name\":\"value\", \"type\":[\"null\", \"string\"," + "{\"type\": \"record\", \"name\": \"Cons\", \"fields\": [" + "{\"name\":\"car\", \"type\":\"Lisp\"}," + "{\"name\":\"cdr\", \"type\":\"Lisp\"}]}]}]}", "U2U1S10U0N"}, // Deep recursion { "{\"type\": \"record\", \"name\": \"Node\", \"fields\": [" + "{\"name\":\"children\", \"type\":" + "{\"type\": \"array\", \"items\": \"Node\" }}]}", "[c1s[c1s[c1s[c1s[c1s[c1s[c1s[c1s[c1s[c1s[c1s[]]]]]]]]]]]]" }, }; } static void dump(byte[] bb) { int col = 0; for (byte b : bb) { if (col % 16 == 0) { System.out.println(); } col++; System.out.print(Integer.toHexString(b & 0xff) + " "); } System.out.println(); } static void print(Encoding encoding, int skipLevel, Schema writerSchema, Schema readerSchema, Object[] writtenValues, Object[] expectedValues) { LOG.debug("{} Skip Level {}", encoding, skipLevel); printSchemaAndValues("Writer", writerSchema, writtenValues); printSchemaAndValues("Reader", readerSchema, expectedValues); } private static void printSchemaAndValues(String schemaType, Schema schema, Object[] values) { LOG.debug("{} Schema {}", schemaType, schema); for (Object value : values) { LOG.debug("{} -> {}", value, value.getClass().getSimpleName()); } } }
package com.moon.core.lang.support; import com.moon.core.lang.ThrowUtil; import com.moon.core.util.ListUtil; import java.util.Set; /** * @author moonsky */ public final class ClassSupport { private ClassSupport() { ThrowUtil.noInstanceError(); } public static Set<Class> addAllInterfaces(Set<Class> list, Class[] types) { for (int i = 0; i < types.length; i++) { addAllInterfaces(list, types[i]); } return list; } public static Set<Class> addAllInterfaces(Set<Class> list, Class type) { if (type.isInterface()) { ListUtil.add(list, type); } addAllInterfaces(list, type.getInterfaces()); if ((type = type.getSuperclass()) != null) { addAllInterfaces(list, type); } return list; } }
/* * Copyright 2019 ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package tech.pegasys.pantheon.services; import tech.pegasys.pantheon.ethereum.core.Block; import tech.pegasys.pantheon.ethereum.eth.sync.BlockBroadcaster; import tech.pegasys.pantheon.plugin.services.PantheonEvents; import com.google.common.collect.ImmutableMap; import io.vertx.core.json.Json; public class PantheonEventsImpl implements PantheonEvents { private final BlockBroadcaster blockBroadcaster; public PantheonEventsImpl(final BlockBroadcaster blockBroadcaster) { this.blockBroadcaster = blockBroadcaster; } @Override public Object addNewBlockPropagatedListener(final NewBlockPropagatedListener listener) { return blockBroadcaster.subscribePropagateNewBlocks( block -> dispatchNewBlockPropagatedMessage(block, listener)); } @Override public void removeNewBlockPropagatedListener(final Object listenerIdentifier) { if (listenerIdentifier instanceof Long) { blockBroadcaster.unsubscribePropagateNewBlocks((Long) listenerIdentifier); } } private void dispatchNewBlockPropagatedMessage( final Block block, final NewBlockPropagatedListener listener) { final ImmutableMap<Object, Object> result = new ImmutableMap.Builder<>() .put("type", "NewBlock") .put("blockHash", block.getHash().toString()) .put("blockNumber", block.getHeader().getNumber()) .put("timestamp", block.getHeader().getTimestamp()) .build(); listener.newBlockPropagated(Json.encode(result)); } }
package com.cowthan.pattern1.factory.method; /** * 场景类,女娲 * @author qiaoliang * */ public class Director_NvWa { public static void main(String[] args) { AbstractHumanFactory factory = new HumanFactory(); //===造白人 IHuman wh = factory.createHuman(WhiteHuman.class); wh.getColor(); wh.say(); //===造黑人 IHuman bh = factory.createHuman(BlackHuman.class); bh.getColor(); bh.say(); //===造黄人 IHuman yh = factory.createHuman(YellowHuman.class); yh.getColor(); yh.say(); } }
/** * Copyright (c) 2010 Abbcc Corp. * No 225,Wen Yi RD, Hang Zhou, Zhe Jiang, China. * All rights reserved. * * "df.java is the copyrighted, * proprietary property of Abbcc Company and its * subsidiaries and affiliates which retain all right, title and interest * therein." * * Revision History * * Date Programmer Notes * --------- --------------------- -------------------------------------------- * 2009-12-7 wangjin initial */ package com.abbcc.dao; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import com.abbcc.common.PaginationSupport; import com.abbcc.models.AbcAttachment; public interface AttachmentDAO { public void save(AbcAttachment transientInstance); public void delete(AbcAttachment persistentInstance); public AbcAttachment findById(String id); public List<AbcAttachment> findByExample(AbcAttachment instance); public List<AbcAttachment> findAll(); public void saveOrUpdate(AbcAttachment instance); public PaginationSupport findPageByCriteria( final DetachedCriteria detachedCriteria); public PaginationSupport findPageByCriteria( final DetachedCriteria detachedCriteria, final int startIndex); public PaginationSupport findPageByCriteria( final DetachedCriteria detachedCriteria, final int pageSize, final int startIndex); public List findAllByCriteria(final DetachedCriteria detachedCriteria); public int getCountByCriteria(final DetachedCriteria detachedCriteria); public void callProcedure(String procString, List<Object> params) throws Exception; public List getCallProcedureResult(String procString, List<Object> params) throws Exception; }
package ug.robot; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import ug.util.Param; public class Shooter extends Mechanism { public DcMotor shooter; public Servo pusher; //boolean encMode = false; int upPosEnc; private ElapsedTime runtime = new ElapsedTime(); public boolean isPowered; int lastMotorPos; int zeroMotorPos; int topMotorPos; double pushIn; double pushOut; public int currentTarget; double lastTimeNotStalled; public Shooter(String n, HardwareMap hardwareMap) { super(n, hardwareMap); shooter = getHwMotor("shooter"); //shooter.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); //shooter.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); pusher = getHwServo("pusher"); hmp.put(mName("Speed"), new Param(1.0)); hmp.get(mName("Speed")).setStandardServo(); isPowered = false; //Value is 600 for 3.7 Motor, 2200 for Neverest 20 } public void init() { stop(); runtime.reset(); shooter.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); //zeroMotorPos = shooter.getCurrentPosition(); //lastMotorPos = zeroMotorPos; shooter.setPower(0); //shooter.setTargetPosition(0); shooter.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); lastTimeNotStalled = runtime.seconds(); //currentTarget = zeroMotorPos; //topMotorPos = -3600; pushIn = .6; pushOut = .95; retract(); } public void shoot(){ pusher.setPosition(pushIn); } public void retract(){ pusher.setPosition(pushOut); } public void powerOn() { isPowered = true; //shooter.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); shooter.setPower(1); } public void powerOff() { isPowered = false; //shooter.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); stop(); } public void start(){ } public void stop() { //if(!encMode) { shooter.setPower(0); //} isPowered = false; } public void hold(){ isPowered = true; shooter.setPower(getPVal("Speed")/2); } /* public boolean aboveRobot(int encVal){ if(-encVal > liftUpVal){ return true; } return false; } public void raiseFast() { isPowered = true; lift.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); lift.setPower(-getPVal("Speed")*0.8); //encMode = false; } public void fullIn(){ isPowered = true; lift.setPower(getPVal("Speed")); lift.setTargetPosition(upPosEnc); //encMode = true; lift.setMode(DcMotor.RunMode.RUN_TO_POSITION); } public void goToDump(){ isPowered = true; lift.setPower(getPVal("Speed")); lift.setTargetPosition(upPosEnc + (int)(getPVal("DumpVal"))); //encMode = true; lift.setMode(DcMotor.RunMode.RUN_TO_POSITION); } public void fullDown(){ isPowered = true; lift.setPower(getPVal("Speed")); lift.setTargetPosition(upPosEnc + (int)(getPVal("FullDownVal"))); //encMode = true; lift.setMode(DcMotor.RunMode.RUN_TO_POSITION); } public void startingUp(){ upPosEnc = lift.getCurrentPosition(); } public void startingDown(){ upPosEnc = lift.getCurrentPosition()- (int)getPVal("FullDownVal")-150; } public void stopIfStalled(){ if(!isStalledNow()) lastTimeNotStalled = runtime.seconds(); if(isStalledNow()&&runtime.seconds()-lastTimeNotStalled > 0.3){ stop(); } } public boolean isStalledNow(){ if(!isPowered) { lastMotorPos = lift.getCurrentPosition(); return false; } if(Math.abs(lastMotorPos - lift.getCurrentPosition())<5 ){ lastMotorPos = lift.getCurrentPosition(); return true; } lastMotorPos = lift.getCurrentPosition(); return false; } public void autonFullDown(LinearOpMode om){ int startPos = lift.getCurrentPosition(); lower(); double startTime = om.getRuntime(); while(lift.getCurrentPosition()-startPos < getPVal("FullDownVal") && om.opModeIsActive() && om.getRuntime()-startTime < 5){ om.telemetry.addData("lift: ", "lifting " + (lift.getCurrentPosition()-startPos)); om.telemetry.update(); //stopIfStalled(); } om.telemetry.addData("lift: ", "stopped"); om.telemetry.update(); stop(); if(lift.getCurrentPosition()-startPos < getPVal("FullDownVal")){ om.stop(); } } public void autonFullUp(LinearOpMode om){ int startPos = lift.getCurrentPosition(); raiseFast(); double startTime = om.getRuntime(); while((lift.getCurrentPosition()-startPos) > -getPVal("FullDownVal") && om.opModeIsActive() && om.getRuntime()-startTime < 5){ om.telemetry.addData("lift: ", "lifting " + ((lift.getCurrentPosition()-startPos))); om.telemetry.update(); //stopIfStalled(); } om.telemetry.addData("lift: ", "stopped"); om.telemetry.update(); stop(); if((lift.getCurrentPosition()-startPos) > -getPVal("FullDownVal")){ om.stop(); } } */ public void stopAndReset(){ shooter.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.serde2.lazy.objectinspector; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.serde2.lazy.LazyUnion; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.UnionObjectInspector; import org.apache.hadoop.io.Text; /** * LazyUnionObjectInspector works on union data that is stored in LazyUnion. * * Always use the {@link LazyObjectInspectorFactory} to create new * ObjectInspector objects, instead of directly creating an instance of this * class. */ public class LazyUnionObjectInspector implements UnionObjectInspector { public static final Log LOG = LogFactory .getLog(LazyUnionObjectInspector.class.getName()); private List<ObjectInspector> ois; private byte separator; private Text nullSequence; private boolean escaped; private byte escapeChar; protected LazyUnionObjectInspector() { super(); } protected LazyUnionObjectInspector( List<ObjectInspector> ois, byte separator, Text nullSequence, boolean escaped, byte escapeChar) { init(ois, separator, nullSequence, escaped, escapeChar); } @Override public String getTypeName() { return ObjectInspectorUtils.getStandardUnionTypeName(this); } protected void init( List<ObjectInspector> ois, byte separator, Text nullSequence, boolean escaped, byte escapeChar) { this.separator = separator; this.nullSequence = nullSequence; this.escaped = escaped; this.escapeChar = escapeChar; this.ois = new ArrayList<ObjectInspector>(); this.ois.addAll(ois); } protected LazyUnionObjectInspector(List<ObjectInspector> ois, byte separator, Text nullSequence) { init(ois, separator, nullSequence); } protected void init(List<ObjectInspector> ois, byte separator, Text nullSequence) { this.separator = separator; this.nullSequence = nullSequence; this.ois = new ArrayList<ObjectInspector>(); this.ois.addAll(ois); } @Override public final Category getCategory() { return Category.UNION; } public byte getSeparator() { return separator; } public Text getNullSequence() { return nullSequence; } public boolean isEscaped() { return escaped; } public byte getEscapeChar() { return escapeChar; } @Override public Object getField(Object data) { if (data == null) { return null; } return ((LazyUnion) data).getField(); } @Override public List<ObjectInspector> getObjectInspectors() { return ois; } @Override public byte getTag(Object data) { if (data == null) { return -1; } return ((LazyUnion) data).getTag(); } }
package it.sorint.welearnbe.controllers.entity; public class FullSessionFE extends SessionFE { private CourseWithUnitsFE course; public CourseWithUnitsFE getCourse() { return course; } public void setCourse(CourseWithUnitsFE course) { this.course = course; } }
package org.revolut.handler; import com.google.gson.Gson; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.HttpString; /** * Created by Leo on 5/27/2018. */ public abstract class AbstractHttpHandler implements HttpHandler { protected void writeResponse(HttpServerExchange exchange, Object result, int code) { exchange.setStatusCode(code); exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json"); exchange.getResponseSender().send(new Gson().toJson(result)); } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.encodings; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Arrays; public class EncodingViewer extends DialogWrapper { private static final Logger LOG = Logger.getInstance("#com.intellij.internal.encodings.EncodingViewer"); private JPanel myPanel; private JTextArea myText; private JComboBox myEncoding; private JButton myLoadFile; private byte[] myBytes; public EncodingViewer() { super(false); initEncodings(); myLoadFile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { VirtualFile file = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), myPanel, null, null); if (file != null) { loadFrom(file); } } }); init(); } @Override protected String getDimensionServiceKey() { return "EncodingViewer"; } private void loadFrom(VirtualFile virtualFile) { try { myBytes = virtualFile.contentsToByteArray(); } catch (IOException e) { LOG.error(e); return; } refreshText(); } private void refreshText() { String selectedCharset = getSelectedCharset(); if (myBytes == null || selectedCharset == null) return; try { myText.setText(new String(myBytes, selectedCharset)); } catch (UnsupportedEncodingException e) { LOG.error(e); } } private String getSelectedCharset() { return ((Charset) myEncoding.getSelectedItem()).name(); } private void initEncodings() { Charset[] availableCharsets = CharsetToolkit.getAvailableCharsets(); myEncoding.setModel(new DefaultComboBoxModel(availableCharsets)); int defaultIndex = Arrays.asList(availableCharsets).indexOf(CharsetToolkit.getDefaultSystemCharset()); myEncoding.setSelectedIndex(defaultIndex); myEncoding.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { refreshText(); } } }); } @Override protected JComponent createCenterPanel() { return myPanel; } }
/* * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdds; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import com.google.common.base.Preconditions; import org.apache.commons.lang3.SystemUtils; import org.apache.hadoop.hdds.utils.SignalLogger; import org.apache.hadoop.hdds.utils.VersionInfo; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.util.ShutdownHookManager; import org.slf4j.Logger; /** * Simple utility class to collection string conversion methods. */ public final class StringUtils { private StringUtils() { } // Using the charset canonical name for String/byte[] conversions is much // more efficient due to use of cached encoders/decoders. private static final String UTF8_CSN = StandardCharsets.UTF_8.name(); /** * Priority of the StringUtils shutdown hook. */ private static final int SHUTDOWN_HOOK_PRIORITY = 0; /** * Decode a specific range of bytes of the given byte array to a string * using UTF8. * * @param bytes The bytes to be decoded into characters * @param offset The index of the first byte to decode * @param length The number of bytes to decode * @return The decoded string */ public static String bytes2String(byte[] bytes, int offset, int length) { try { return new String(bytes, offset, length, UTF8_CSN); } catch (UnsupportedEncodingException e) { // should never happen! throw new IllegalArgumentException("UTF8 encoding is not supported", e); } } /** * Decode a specific range of bytes of the given byte array to a string * using UTF8. * * @param bytes The bytes to be decoded into characters * @return The decoded string */ public static String bytes2String(byte[] bytes) { return bytes2String(bytes, 0, bytes.length); } /** * Converts a string to a byte array using UTF8 encoding. */ public static byte[] string2Bytes(String str) { try { return str.getBytes(UTF8_CSN); } catch (UnsupportedEncodingException e) { // should never happen! throw new IllegalArgumentException("UTF8 decoding is not supported", e); } } /** * Return a message for logging. * @param prefix prefix keyword for the message * @param msg content of the message * @return a message for logging */ public static String toStartupShutdownString(String prefix, String... msg) { StringBuilder b = new StringBuilder(prefix); b.append("\n/************************************************************"); for (String s : msg) { b.append("\n").append(prefix).append(s); } b.append("\n************************************************************/"); return b.toString(); } public static void startupShutdownMessage(VersionInfo versionInfo, Class<?> clazz, String[] args, Logger log) { final String hostname = NetUtils.getHostname(); final String className = clazz.getSimpleName(); if (log.isInfoEnabled()) { log.info(createStartupShutdownMessage(versionInfo, className, hostname, args)); } if (SystemUtils.IS_OS_UNIX) { try { SignalLogger.INSTANCE.register(log); } catch (Throwable t) { log.warn("failed to register any UNIX signal loggers: ", t); } } ShutdownHookManager.get().addShutdownHook( () -> log.info(toStartupShutdownString("SHUTDOWN_MSG: ", "Shutting down " + className + " at " + hostname)), SHUTDOWN_HOOK_PRIORITY); } /** * Generate the text for the startup/shutdown message of processes. * @param className short name of the class * @param hostname hostname * @param args Command arguments * @return a string to log. */ public static String createStartupShutdownMessage(VersionInfo versionInfo, String className, String hostname, String[] args) { return toStartupShutdownString("STARTUP_MSG: ", "Starting " + className, " host = " + hostname, " args = " + (args != null ? Arrays.asList(args) : new ArrayList<>()), " version = " + versionInfo.getVersion(), " classpath = " + System.getProperty("java.class.path"), " build = " + versionInfo.getUrl() + "/" + versionInfo.getRevision() + " ; compiled by '" + versionInfo.getUser() + "' on " + versionInfo.getDate(), " java = " + System.getProperty("java.version")); } public static String appendIfNotPresent(String str, char c) { Preconditions.checkNotNull(str, "Input string is null"); return str.isEmpty() || str.charAt(str.length() - 1) != c ? str + c : str; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataproc/v1/jobs.proto package com.google.cloud.dataproc.v1; public interface JobOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.dataproc.v1.Job) com.google.protobuf.MessageOrBuilder { /** * <pre> * Optional. The fully qualified reference to the job, which can be used to * obtain the equivalent REST path of the job resource. If this property * is not specified when a job is created, the server generates a * &lt;code&gt;job_id&lt;/code&gt;. * </pre> * * <code>.google.cloud.dataproc.v1.JobReference reference = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the reference field is set. */ boolean hasReference(); /** * <pre> * Optional. The fully qualified reference to the job, which can be used to * obtain the equivalent REST path of the job resource. If this property * is not specified when a job is created, the server generates a * &lt;code&gt;job_id&lt;/code&gt;. * </pre> * * <code>.google.cloud.dataproc.v1.JobReference reference = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The reference. */ com.google.cloud.dataproc.v1.JobReference getReference(); /** * <pre> * Optional. The fully qualified reference to the job, which can be used to * obtain the equivalent REST path of the job resource. If this property * is not specified when a job is created, the server generates a * &lt;code&gt;job_id&lt;/code&gt;. * </pre> * * <code>.google.cloud.dataproc.v1.JobReference reference = 1 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.JobReferenceOrBuilder getReferenceOrBuilder(); /** * <pre> * Required. Job information, including how, when, and where to * run the job. * </pre> * * <code>.google.cloud.dataproc.v1.JobPlacement placement = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return Whether the placement field is set. */ boolean hasPlacement(); /** * <pre> * Required. Job information, including how, when, and where to * run the job. * </pre> * * <code>.google.cloud.dataproc.v1.JobPlacement placement = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The placement. */ com.google.cloud.dataproc.v1.JobPlacement getPlacement(); /** * <pre> * Required. Job information, including how, when, and where to * run the job. * </pre> * * <code>.google.cloud.dataproc.v1.JobPlacement placement = 2 [(.google.api.field_behavior) = REQUIRED];</code> */ com.google.cloud.dataproc.v1.JobPlacementOrBuilder getPlacementOrBuilder(); /** * <pre> * Optional. Job is a Hadoop job. * </pre> * * <code>.google.cloud.dataproc.v1.HadoopJob hadoop_job = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the hadoopJob field is set. */ boolean hasHadoopJob(); /** * <pre> * Optional. Job is a Hadoop job. * </pre> * * <code>.google.cloud.dataproc.v1.HadoopJob hadoop_job = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The hadoopJob. */ com.google.cloud.dataproc.v1.HadoopJob getHadoopJob(); /** * <pre> * Optional. Job is a Hadoop job. * </pre> * * <code>.google.cloud.dataproc.v1.HadoopJob hadoop_job = 3 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.HadoopJobOrBuilder getHadoopJobOrBuilder(); /** * <pre> * Optional. Job is a Spark job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkJob spark_job = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the sparkJob field is set. */ boolean hasSparkJob(); /** * <pre> * Optional. Job is a Spark job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkJob spark_job = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The sparkJob. */ com.google.cloud.dataproc.v1.SparkJob getSparkJob(); /** * <pre> * Optional. Job is a Spark job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkJob spark_job = 4 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.SparkJobOrBuilder getSparkJobOrBuilder(); /** * <pre> * Optional. Job is a PySpark job. * </pre> * * <code>.google.cloud.dataproc.v1.PySparkJob pyspark_job = 5 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the pysparkJob field is set. */ boolean hasPysparkJob(); /** * <pre> * Optional. Job is a PySpark job. * </pre> * * <code>.google.cloud.dataproc.v1.PySparkJob pyspark_job = 5 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The pysparkJob. */ com.google.cloud.dataproc.v1.PySparkJob getPysparkJob(); /** * <pre> * Optional. Job is a PySpark job. * </pre> * * <code>.google.cloud.dataproc.v1.PySparkJob pyspark_job = 5 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.PySparkJobOrBuilder getPysparkJobOrBuilder(); /** * <pre> * Optional. Job is a Hive job. * </pre> * * <code>.google.cloud.dataproc.v1.HiveJob hive_job = 6 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the hiveJob field is set. */ boolean hasHiveJob(); /** * <pre> * Optional. Job is a Hive job. * </pre> * * <code>.google.cloud.dataproc.v1.HiveJob hive_job = 6 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The hiveJob. */ com.google.cloud.dataproc.v1.HiveJob getHiveJob(); /** * <pre> * Optional. Job is a Hive job. * </pre> * * <code>.google.cloud.dataproc.v1.HiveJob hive_job = 6 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.HiveJobOrBuilder getHiveJobOrBuilder(); /** * <pre> * Optional. Job is a Pig job. * </pre> * * <code>.google.cloud.dataproc.v1.PigJob pig_job = 7 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the pigJob field is set. */ boolean hasPigJob(); /** * <pre> * Optional. Job is a Pig job. * </pre> * * <code>.google.cloud.dataproc.v1.PigJob pig_job = 7 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The pigJob. */ com.google.cloud.dataproc.v1.PigJob getPigJob(); /** * <pre> * Optional. Job is a Pig job. * </pre> * * <code>.google.cloud.dataproc.v1.PigJob pig_job = 7 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.PigJobOrBuilder getPigJobOrBuilder(); /** * <pre> * Optional. Job is a SparkR job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkRJob spark_r_job = 21 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the sparkRJob field is set. */ boolean hasSparkRJob(); /** * <pre> * Optional. Job is a SparkR job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkRJob spark_r_job = 21 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The sparkRJob. */ com.google.cloud.dataproc.v1.SparkRJob getSparkRJob(); /** * <pre> * Optional. Job is a SparkR job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkRJob spark_r_job = 21 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.SparkRJobOrBuilder getSparkRJobOrBuilder(); /** * <pre> * Optional. Job is a SparkSql job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkSqlJob spark_sql_job = 12 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the sparkSqlJob field is set. */ boolean hasSparkSqlJob(); /** * <pre> * Optional. Job is a SparkSql job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkSqlJob spark_sql_job = 12 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The sparkSqlJob. */ com.google.cloud.dataproc.v1.SparkSqlJob getSparkSqlJob(); /** * <pre> * Optional. Job is a SparkSql job. * </pre> * * <code>.google.cloud.dataproc.v1.SparkSqlJob spark_sql_job = 12 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.SparkSqlJobOrBuilder getSparkSqlJobOrBuilder(); /** * <pre> * Optional. Job is a Presto job. * </pre> * * <code>.google.cloud.dataproc.v1.PrestoJob presto_job = 23 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the prestoJob field is set. */ boolean hasPrestoJob(); /** * <pre> * Optional. Job is a Presto job. * </pre> * * <code>.google.cloud.dataproc.v1.PrestoJob presto_job = 23 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The prestoJob. */ com.google.cloud.dataproc.v1.PrestoJob getPrestoJob(); /** * <pre> * Optional. Job is a Presto job. * </pre> * * <code>.google.cloud.dataproc.v1.PrestoJob presto_job = 23 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.PrestoJobOrBuilder getPrestoJobOrBuilder(); /** * <pre> * Output only. The job status. Additional application-specific * status information may be contained in the &lt;code&gt;type_job&lt;/code&gt; * and &lt;code&gt;yarn_applications&lt;/code&gt; fields. * </pre> * * <code>.google.cloud.dataproc.v1.JobStatus status = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the status field is set. */ boolean hasStatus(); /** * <pre> * Output only. The job status. Additional application-specific * status information may be contained in the &lt;code&gt;type_job&lt;/code&gt; * and &lt;code&gt;yarn_applications&lt;/code&gt; fields. * </pre> * * <code>.google.cloud.dataproc.v1.JobStatus status = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ com.google.cloud.dataproc.v1.JobStatus getStatus(); /** * <pre> * Output only. The job status. Additional application-specific * status information may be contained in the &lt;code&gt;type_job&lt;/code&gt; * and &lt;code&gt;yarn_applications&lt;/code&gt; fields. * </pre> * * <code>.google.cloud.dataproc.v1.JobStatus status = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.cloud.dataproc.v1.JobStatusOrBuilder getStatusOrBuilder(); /** * <pre> * Output only. The previous job status. * </pre> * * <code>repeated .google.cloud.dataproc.v1.JobStatus status_history = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<com.google.cloud.dataproc.v1.JobStatus> getStatusHistoryList(); /** * <pre> * Output only. The previous job status. * </pre> * * <code>repeated .google.cloud.dataproc.v1.JobStatus status_history = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.cloud.dataproc.v1.JobStatus getStatusHistory(int index); /** * <pre> * Output only. The previous job status. * </pre> * * <code>repeated .google.cloud.dataproc.v1.JobStatus status_history = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ int getStatusHistoryCount(); /** * <pre> * Output only. The previous job status. * </pre> * * <code>repeated .google.cloud.dataproc.v1.JobStatus status_history = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<? extends com.google.cloud.dataproc.v1.JobStatusOrBuilder> getStatusHistoryOrBuilderList(); /** * <pre> * Output only. The previous job status. * </pre> * * <code>repeated .google.cloud.dataproc.v1.JobStatus status_history = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.cloud.dataproc.v1.JobStatusOrBuilder getStatusHistoryOrBuilder( int index); /** * <pre> * Output only. The collection of YARN applications spun up by this job. * **Beta** Feature: This report is available for testing purposes only. It * may be changed before final release. * </pre> * * <code>repeated .google.cloud.dataproc.v1.YarnApplication yarn_applications = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<com.google.cloud.dataproc.v1.YarnApplication> getYarnApplicationsList(); /** * <pre> * Output only. The collection of YARN applications spun up by this job. * **Beta** Feature: This report is available for testing purposes only. It * may be changed before final release. * </pre> * * <code>repeated .google.cloud.dataproc.v1.YarnApplication yarn_applications = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.cloud.dataproc.v1.YarnApplication getYarnApplications(int index); /** * <pre> * Output only. The collection of YARN applications spun up by this job. * **Beta** Feature: This report is available for testing purposes only. It * may be changed before final release. * </pre> * * <code>repeated .google.cloud.dataproc.v1.YarnApplication yarn_applications = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ int getYarnApplicationsCount(); /** * <pre> * Output only. The collection of YARN applications spun up by this job. * **Beta** Feature: This report is available for testing purposes only. It * may be changed before final release. * </pre> * * <code>repeated .google.cloud.dataproc.v1.YarnApplication yarn_applications = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ java.util.List<? extends com.google.cloud.dataproc.v1.YarnApplicationOrBuilder> getYarnApplicationsOrBuilderList(); /** * <pre> * Output only. The collection of YARN applications spun up by this job. * **Beta** Feature: This report is available for testing purposes only. It * may be changed before final release. * </pre> * * <code>repeated .google.cloud.dataproc.v1.YarnApplication yarn_applications = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> */ com.google.cloud.dataproc.v1.YarnApplicationOrBuilder getYarnApplicationsOrBuilder( int index); /** * <pre> * Output only. A URI pointing to the location of the stdout of the job's * driver program. * </pre> * * <code>string driver_output_resource_uri = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The driverOutputResourceUri. */ java.lang.String getDriverOutputResourceUri(); /** * <pre> * Output only. A URI pointing to the location of the stdout of the job's * driver program. * </pre> * * <code>string driver_output_resource_uri = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for driverOutputResourceUri. */ com.google.protobuf.ByteString getDriverOutputResourceUriBytes(); /** * <pre> * Output only. If present, the location of miscellaneous control files * which may be used as part of job setup and handling. If not present, * control files may be placed in the same location as `driver_output_uri`. * </pre> * * <code>string driver_control_files_uri = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The driverControlFilesUri. */ java.lang.String getDriverControlFilesUri(); /** * <pre> * Output only. If present, the location of miscellaneous control files * which may be used as part of job setup and handling. If not present, * control files may be placed in the same location as `driver_output_uri`. * </pre> * * <code>string driver_control_files_uri = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for driverControlFilesUri. */ com.google.protobuf.ByteString getDriverControlFilesUriBytes(); /** * <pre> * Optional. The labels to associate with this job. * Label **keys** must contain 1 to 63 characters, and must conform to * [RFC 1035](https://www.ietf.org/rfc/rfc1035.txt). * Label **values** may be empty, but, if present, must contain 1 to 63 * characters, and must conform to [RFC * 1035](https://www.ietf.org/rfc/rfc1035.txt). No more than 32 labels can be * associated with a job. * </pre> * * <code>map&lt;string, string&gt; labels = 18 [(.google.api.field_behavior) = OPTIONAL];</code> */ int getLabelsCount(); /** * <pre> * Optional. The labels to associate with this job. * Label **keys** must contain 1 to 63 characters, and must conform to * [RFC 1035](https://www.ietf.org/rfc/rfc1035.txt). * Label **values** may be empty, but, if present, must contain 1 to 63 * characters, and must conform to [RFC * 1035](https://www.ietf.org/rfc/rfc1035.txt). No more than 32 labels can be * associated with a job. * </pre> * * <code>map&lt;string, string&gt; labels = 18 [(.google.api.field_behavior) = OPTIONAL];</code> */ boolean containsLabels( java.lang.String key); /** * Use {@link #getLabelsMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, java.lang.String> getLabels(); /** * <pre> * Optional. The labels to associate with this job. * Label **keys** must contain 1 to 63 characters, and must conform to * [RFC 1035](https://www.ietf.org/rfc/rfc1035.txt). * Label **values** may be empty, but, if present, must contain 1 to 63 * characters, and must conform to [RFC * 1035](https://www.ietf.org/rfc/rfc1035.txt). No more than 32 labels can be * associated with a job. * </pre> * * <code>map&lt;string, string&gt; labels = 18 [(.google.api.field_behavior) = OPTIONAL];</code> */ java.util.Map<java.lang.String, java.lang.String> getLabelsMap(); /** * <pre> * Optional. The labels to associate with this job. * Label **keys** must contain 1 to 63 characters, and must conform to * [RFC 1035](https://www.ietf.org/rfc/rfc1035.txt). * Label **values** may be empty, but, if present, must contain 1 to 63 * characters, and must conform to [RFC * 1035](https://www.ietf.org/rfc/rfc1035.txt). No more than 32 labels can be * associated with a job. * </pre> * * <code>map&lt;string, string&gt; labels = 18 [(.google.api.field_behavior) = OPTIONAL];</code> */ java.lang.String getLabelsOrDefault( java.lang.String key, java.lang.String defaultValue); /** * <pre> * Optional. The labels to associate with this job. * Label **keys** must contain 1 to 63 characters, and must conform to * [RFC 1035](https://www.ietf.org/rfc/rfc1035.txt). * Label **values** may be empty, but, if present, must contain 1 to 63 * characters, and must conform to [RFC * 1035](https://www.ietf.org/rfc/rfc1035.txt). No more than 32 labels can be * associated with a job. * </pre> * * <code>map&lt;string, string&gt; labels = 18 [(.google.api.field_behavior) = OPTIONAL];</code> */ java.lang.String getLabelsOrThrow( java.lang.String key); /** * <pre> * Optional. Job scheduling configuration. * </pre> * * <code>.google.cloud.dataproc.v1.JobScheduling scheduling = 20 [(.google.api.field_behavior) = OPTIONAL];</code> * @return Whether the scheduling field is set. */ boolean hasScheduling(); /** * <pre> * Optional. Job scheduling configuration. * </pre> * * <code>.google.cloud.dataproc.v1.JobScheduling scheduling = 20 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The scheduling. */ com.google.cloud.dataproc.v1.JobScheduling getScheduling(); /** * <pre> * Optional. Job scheduling configuration. * </pre> * * <code>.google.cloud.dataproc.v1.JobScheduling scheduling = 20 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.cloud.dataproc.v1.JobSchedulingOrBuilder getSchedulingOrBuilder(); /** * <pre> * Output only. A UUID that uniquely identifies a job within the project * over time. This is in contrast to a user-settable reference.job_id that * may be reused over time. * </pre> * * <code>string job_uuid = 22 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The jobUuid. */ java.lang.String getJobUuid(); /** * <pre> * Output only. A UUID that uniquely identifies a job within the project * over time. This is in contrast to a user-settable reference.job_id that * may be reused over time. * </pre> * * <code>string job_uuid = 22 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for jobUuid. */ com.google.protobuf.ByteString getJobUuidBytes(); /** * <pre> * Output only. Indicates whether the job is completed. If the value is `false`, * the job is still in progress. If `true`, the job is completed, and * `status.state` field will indicate if it was successful, failed, * or cancelled. * </pre> * * <code>bool done = 24 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The done. */ boolean getDone(); public com.google.cloud.dataproc.v1.Job.TypeJobCase getTypeJobCase(); }
package com.hs.LeetCode02; /** * TODO * * @author 微信公众号《和尚的破功之路》 * @date 2022/1/23 17:49 * version: 1.0 */ public class LT23 { public ListNode mergeKLists(ListNode[] lists) { ListNode newList = new ListNode(Integer.MIN_VALUE); ListNode newHead = newList; for (int i = 0; i < lists.length; i++) { ListNode list1 = lists[i]; ListNode mergeList = mergeList(newList, list1); while (mergeList != null) { mergeList = mergeList.next; } } return newList.next; } public ListNode mergeList(ListNode list1, ListNode list2) { ListNode newList = new ListNode(0); ListNode newHead = newList; while (list1 != null && list2 != null) { if (list1.val <= list2.val) { newHead.next = list1; list1 = list1.next; } else { newHead.next = list2; list2 = list2.next; } newHead = newHead.next; } while (list1 != null) { newHead.next = list1; list1 = list1.next; newHead = newHead.next; } while (list2 != null) { newHead.next = list2; list2 = list2.next; newHead = newHead.next; } return newList.next; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.ozone.client.checksum; import org.apache.hadoop.fs.CompositeCrcFileChecksum; import org.apache.hadoop.fs.FileChecksum; import org.apache.hadoop.fs.MD5MD5CRC32GzipFileChecksum; import org.apache.hadoop.hdds.protocol.proto.HddsProtos; import org.apache.hadoop.hdds.scm.OzoneClientConfig; import org.apache.hadoop.hdds.scm.XceiverClientFactory; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.MD5Hash; import org.apache.hadoop.ozone.client.OzoneBucket; import org.apache.hadoop.ozone.client.OzoneVolume; import org.apache.hadoop.ozone.client.protocol.ClientProtocol; import org.apache.hadoop.ozone.client.rpc.RpcClient; import org.apache.hadoop.ozone.om.helpers.OmKeyArgs; import org.apache.hadoop.ozone.om.helpers.OmKeyInfo; import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo; import org.apache.hadoop.ozone.om.protocol.OzoneManagerProtocol; import org.apache.hadoop.util.CrcComposer; import org.apache.hadoop.util.CrcUtil; import org.apache.hadoop.util.DataChecksum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; /** * The base class to support file checksum. */ public abstract class BaseFileChecksumHelper { static final Logger LOG = LoggerFactory.getLogger(BaseFileChecksumHelper.class); private OmKeyInfo keyInfo; private OzoneVolume volume; private OzoneBucket bucket; private String keyName; private final long length; private ClientProtocol rpcClient; private OzoneClientConfig.ChecksumCombineMode combineMode; private final DataOutputBuffer blockChecksumBuf = new DataOutputBuffer(); private XceiverClientFactory xceiverClientFactory; private FileChecksum fileChecksum; private List<OmKeyLocationInfo> keyLocationInfos; private long remaining = 0L; private int bytesPerCRC = -1; private long crcPerBlock = 0; // initialization BaseFileChecksumHelper( OzoneVolume volume, OzoneBucket bucket, String keyName, long length, OzoneClientConfig.ChecksumCombineMode checksumCombineMode, ClientProtocol rpcClient) throws IOException { this.volume = volume; this.bucket = bucket; this.keyName = keyName; this.length = length; this.combineMode = checksumCombineMode; this.rpcClient = rpcClient; this.xceiverClientFactory = ((RpcClient)rpcClient).getXceiverClientManager(); if (this.length > 0) { fetchBlocks(); } } public BaseFileChecksumHelper(OzoneVolume volume, OzoneBucket bucket, String keyName, long length, OzoneClientConfig.ChecksumCombineMode checksumCombineMode, ClientProtocol rpcClient, OmKeyInfo keyInfo) throws IOException { this(volume, bucket, keyName, length, checksumCombineMode, rpcClient); this.keyInfo = keyInfo; } protected String getSrc() { return "Volume: " + volume.getName() + " Bucket: " + bucket.getName() + " " + keyName; } protected long getLength() { return length; } protected ClientProtocol getRpcClient() { return rpcClient; } protected OzoneClientConfig.ChecksumCombineMode getCombineMode() { return combineMode; } protected XceiverClientFactory getXceiverClientFactory() { return xceiverClientFactory; } protected DataOutputBuffer getBlockChecksumBuf() { return blockChecksumBuf; } protected List<OmKeyLocationInfo> getKeyLocationInfoList() { return keyLocationInfos; } protected long getRemaining() { return remaining; } protected void setRemaining(long remaining) { this.remaining = remaining; } int getBytesPerCRC() { return bytesPerCRC; } protected void setBytesPerCRC(int bytesPerCRC) { this.bytesPerCRC = bytesPerCRC; } /** * Request the blocks created in the most recent version from Ozone Manager. * * @throws IOException */ private void fetchBlocks() throws IOException { if (keyInfo == null) { OzoneManagerProtocol ozoneManagerClient = getRpcClient().getOzoneManagerClient(); OmKeyArgs keyArgs = new OmKeyArgs.Builder().setVolumeName(volume.getName()) .setBucketName(bucket.getName()).setKeyName(keyName) .setRefreshPipeline(true).setSortDatanodesInPipeline(true) .setLatestVersionLocation(true).build(); keyInfo = ozoneManagerClient.lookupKey(keyArgs); } if (keyInfo.getReplicationConfig() .getReplicationType() == HddsProtos.ReplicationType.EC) { return; } if (keyInfo.getFileChecksum() != null && isFullLength(keyInfo.getDataSize())) { // if the checksum is cached in OM, and we request the checksum of // the full length. fileChecksum = keyInfo.getFileChecksum(); } // use OmKeyArgs to call Om.lookup() and get OmKeyInfo keyLocationInfos = keyInfo .getLatestVersionLocations().getBlocksLatestVersionOnly(); } /** * Return true if the requested length is longer than the file length * (dataSize). * * @param dataSize file length * @return */ private boolean isFullLength(long dataSize) { return this.length >= dataSize; } /** * Compute file checksum given the list of chunk checksums requested earlier. * * Skip computation if the already computed, or if the OmKeyInfo of the key * in OM has pre-computed checksum. * @throws IOException */ public void compute() throws IOException { if (fileChecksum != null) { LOG.debug("Checksum is available. Skip computing it."); return; } /** * request length is 0 or the file is empty, return one with the * magic entry that matches the md5 of a 32 byte zero-padded byte array. */ if (keyLocationInfos == null || keyLocationInfos.isEmpty()) { // Explicitly specified here in case the default DataOutputBuffer // buffer length value is changed in future. final int lenOfZeroBytes = 32; byte[] emptyBlockMd5 = new byte[lenOfZeroBytes]; MD5Hash fileMD5 = MD5Hash.digest(emptyBlockMd5); fileChecksum = new MD5MD5CRC32GzipFileChecksum(0, 0, fileMD5); } else { checksumBlocks(); fileChecksum = makeFinalResult(); } } /** * Compute block checksums block by block and append the raw bytes of the * block checksums into getBlockChecksumBuf(). * * @throws IOException */ protected abstract void checksumBlocks() throws IOException; /** * Make final file checksum result given the per-block or per-block-group * checksums collected into getBlockChecksumBuf(). */ private FileChecksum makeFinalResult() throws IOException { switch (getCombineMode()) { case MD5MD5CRC: return makeMd5CrcResult(); case COMPOSITE_CRC: return makeCompositeCrcResult(); default: throw new IOException("Unknown ChecksumCombineMode: " + getCombineMode()); } } private FileChecksum makeMd5CrcResult() { // TODO: support CRC32C //compute file MD5 final MD5Hash fileMD5 = MD5Hash.digest(getBlockChecksumBuf().getData()); // assume CRC32 for now return new MD5MD5CRC32GzipFileChecksum(getBytesPerCRC(), crcPerBlock, fileMD5); } FileChecksum makeCompositeCrcResult() throws IOException { long blockSizeHint = 0; if (keyLocationInfos.size() > 0) { blockSizeHint = keyLocationInfos.get(0).getLength(); } CrcComposer crcComposer = CrcComposer.newCrcComposer(DataChecksum.Type.CRC32, blockSizeHint); byte[] blockChecksumBytes = blockChecksumBuf.getData(); for (int i = 0; i < keyLocationInfos.size(); ++i) { OmKeyLocationInfo block = keyLocationInfos.get(i); // For every LocatedBlock, we expect getBlockSize() // to accurately reflect the number of file bytes digested in the block // checksum. int blockCrc = CrcUtil.readInt(blockChecksumBytes, i * 4); crcComposer.update(blockCrc, block.getLength()); LOG.debug( "Added blockCrc 0x{} for block index {} of size {}", Integer.toString(blockCrc, 16), i, block.getLength()); } int compositeCrc = CrcUtil.readInt(crcComposer.digest(), 0); return new CompositeCrcFileChecksum( compositeCrc, DataChecksum.Type.CRC32, bytesPerCRC); } public FileChecksum getFileChecksum() { return fileChecksum; } }
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.geoip.commands; import com.maxmind.geoip2.record.Country; import io.github.nucleuspowered.nucleus.Nucleus; import io.github.nucleuspowered.nucleus.internal.annotations.RunAsync; import io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers; import io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions; import io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand; import io.github.nucleuspowered.nucleus.internal.command.AbstractCommand; import io.github.nucleuspowered.nucleus.internal.command.NucleusParameters; import io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation; import io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel; import io.github.nucleuspowered.nucleus.modules.geoip.handlers.GeoIpDatabaseHandler; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.args.CommandElement; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.util.annotation.NonnullByDefault; import java.util.HashMap; import java.util.Map; import java.util.Optional; @RunAsync @NoModifiers @Permissions @RegisterCommand("geoip") @NonnullByDefault public class GeoIpCommand extends AbstractCommand<CommandSource> { private final GeoIpDatabaseHandler databaseHandler = Nucleus.getNucleus().getInternalServiceManager().getServiceUnchecked(GeoIpDatabaseHandler.class); @Override protected Map<String, PermissionInformation> permissionSuffixesToRegister() { return new HashMap<String, PermissionInformation>() {{ put("login", PermissionInformation.getWithTranslation("permission.geoip.login", SuggestedLevel.ADMIN)); }}; } @Override public CommandElement[] getArguments() { return new CommandElement[] { NucleusParameters.ONE_PLAYER_NO_SELECTOR }; } @Override public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception { Player player = args.<Player>getOne(NucleusParameters.Keys.PLAYER).get(); Optional<Country> country = this.databaseHandler.getDetails(player.getConnection().getAddress().getAddress()).get(); if (country.isPresent()) { src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("geoip.playerfrom", player.getName(), country.get().getName())); } else { src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("geoip.noinfo", player.getName())); } return CommandResult.success(); } }
/* * #%L * FHIR Implementation * %% * Copyright (C) 2018 DataScience 9 LLC * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /** * This code is 100% AUTO generated. Please do not modify it DIRECTLY * If you need new features or function or changes please update the templates * then submit the template through our web interface. */ package org.fhir.pojo; import com.google.gson.GsonBuilder; /** * Auto generated from the FHIR specification * generated on 07/14/2018 */ public class TestScriptRuleHelper { public static TestScriptRule fromJson(String json) { if (null == json) return null; return new GsonBuilder().create().fromJson(json, TestScriptRule.class); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alipay.sofa.jraft.rhea.client; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alipay.remoting.InvokeCallback; import com.alipay.remoting.InvokeContext; import com.alipay.remoting.rpc.RpcClient; import com.alipay.sofa.jraft.Status; import com.alipay.sofa.jraft.rhea.client.failover.FailoverClosure; import com.alipay.sofa.jraft.rhea.client.pd.AbstractPlacementDriverClient; import com.alipay.sofa.jraft.rhea.client.pd.PlacementDriverClient; import com.alipay.sofa.jraft.rhea.cmd.store.BaseRequest; import com.alipay.sofa.jraft.rhea.cmd.store.BaseResponse; import com.alipay.sofa.jraft.rhea.errors.Errors; import com.alipay.sofa.jraft.rhea.errors.ErrorsHelper; import com.alipay.sofa.jraft.rhea.options.RpcOptions; import com.alipay.sofa.jraft.rhea.rpc.ExtSerializerSupports; import com.alipay.sofa.jraft.rhea.util.concurrent.CallerRunsPolicyWithReport; import com.alipay.sofa.jraft.rhea.util.concurrent.NamedThreadFactory; import com.alipay.sofa.jraft.util.Endpoint; import com.alipay.sofa.jraft.util.ExecutorServiceHelper; import com.alipay.sofa.jraft.util.Requires; import com.alipay.sofa.jraft.util.ThreadPoolUtil; /** * * @author jiachun.fjc */ public class DefaultRheaKVRpcService implements RheaKVRpcService { private static final Logger LOG = LoggerFactory.getLogger(DefaultRheaKVRpcService.class); private final PlacementDriverClient pdClient; private final RpcClient rpcClient; private final Endpoint selfEndpoint; private ThreadPoolExecutor rpcCallbackExecutor; private int rpcTimeoutMillis; private boolean started; public DefaultRheaKVRpcService(PlacementDriverClient pdClient, Endpoint selfEndpoint) { this.pdClient = pdClient; this.rpcClient = ((AbstractPlacementDriverClient) pdClient).getRpcClient(); this.selfEndpoint = selfEndpoint; } // public DefaultRheaKVRpcService(DTGPlacementDriverClient pdClient, Endpoint selfEndpoint) { // this.pdClient = pdClient; // this.rpcClient = ((DefaultPlacementDriverClient) pdClient).getRpcClient(); // this.selfEndpoint = selfEndpoint; // } @Override public synchronized boolean init(final RpcOptions opts) { if (this.started) { LOG.info("[DefaultRheaKVRpcService] already started."); return true; } this.rpcCallbackExecutor = createRpcCallbackExecutor(opts); this.rpcTimeoutMillis = opts.getRpcTimeoutMillis(); Requires.requireTrue(this.rpcTimeoutMillis > 0, "opts.rpcTimeoutMillis must > 0"); LOG.info("[DefaultRheaKVRpcService] start successfully, options: {}.", opts); return this.started = true; } @Override public synchronized void shutdown() { ExecutorServiceHelper.shutdownAndAwaitTermination(this.rpcCallbackExecutor); this.started = false; LOG.info("[DefaultRheaKVRpcService] shutdown successfully."); } @Override public <V> CompletableFuture<V> callAsyncWithRpc(final BaseRequest request, final FailoverClosure<V> closure, final Errors lastCause) { return callAsyncWithRpc(request, closure, lastCause, true); } @Override public <V> CompletableFuture<V> callAsyncWithRpc(final BaseRequest request, final FailoverClosure<V> closure, final Errors lastCause, final boolean requireLeader) { final boolean forceRefresh = ErrorsHelper.isInvalidPeer(lastCause); final Endpoint endpoint = getRpcEndpoint(request.getRegionId(), forceRefresh, this.rpcTimeoutMillis, requireLeader); internalCallAsyncWithRpc(endpoint, request, closure); return closure.future(); } public Endpoint getLeader(final long regionId, final boolean forceRefresh, final long timeoutMillis) { return this.pdClient.getLeader(regionId, forceRefresh, timeoutMillis); } public Endpoint getLuckyPeer(final long regionId, final boolean forceRefresh, final long timeoutMillis) { return this.pdClient.getLuckyPeer(regionId, forceRefresh, timeoutMillis, this.selfEndpoint); } public Endpoint getRpcEndpoint(final long regionId, final boolean forceRefresh, final long timeoutMillis, final boolean requireLeader) { if (requireLeader) { return getLeader(regionId, forceRefresh, timeoutMillis); } else { return getLuckyPeer(regionId, forceRefresh, timeoutMillis); } } private <V> void internalCallAsyncWithRpc(final Endpoint endpoint, final BaseRequest request, final FailoverClosure<V> closure) { final String address = endpoint.toString(); System.out.println(address); final InvokeContext invokeCtx = ExtSerializerSupports.getInvokeContext(); final InvokeCallback invokeCallback = new InvokeCallback() { @Override public void onResponse(final Object result) { final BaseResponse<?> response = (BaseResponse<?>) result; if (response.isSuccess()) { closure.setData(response.getValue()); closure.run(Status.OK()); } else { closure.setError(response.getError()); closure.run(new Status(-1, "RPC failed with address: %s, response: %s", address, response)); } } @Override public void onException(final Throwable t) { closure.failure(t); } @Override public Executor getExecutor() { return rpcCallbackExecutor; } }; try { this.rpcClient.invokeWithCallback(address, request, invokeCtx, invokeCallback, this.rpcTimeoutMillis); } catch (final Throwable t) { closure.failure(t); } } private ThreadPoolExecutor createRpcCallbackExecutor(final RpcOptions opts) { final int callbackExecutorCorePoolSize = opts.getCallbackExecutorCorePoolSize(); final int callbackExecutorMaximumPoolSize = opts.getCallbackExecutorMaximumPoolSize(); if (callbackExecutorCorePoolSize <= 0 || callbackExecutorMaximumPoolSize <= 0) { return null; } final String name = "rheakv-rpc-callback"; return ThreadPoolUtil.newBuilder() // .poolName(name) // .enableMetric(true) // .coreThreads(callbackExecutorCorePoolSize) // .maximumThreads(callbackExecutorMaximumPoolSize) // .keepAliveSeconds(120L) // .workQueue(new ArrayBlockingQueue<>(opts.getCallbackExecutorQueueCapacity())) // .threadFactory(new NamedThreadFactory(name, true)) // .rejectedHandler(new CallerRunsPolicyWithReport(name)) // .build(); } }
package textFormat; import java.awt.*; import javax.swing.*; /** * A program to test formatted text fields * @version 1.04 2016-05-10 * @author Cay Horstmann */ public class FormatTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new FormatTestFrame(); frame.setTitle("FormatTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
package cn.wowspeeder.ss; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramPacket; import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; public class SSServerUdpProxyHandler extends SimpleChannelInboundHandler<ByteBuf> { private static InternalLogger logger = InternalLoggerFactory.getInstance(SSServerUdpProxyHandler.class); private static EventLoopGroup proxyBossGroup = new NioEventLoopGroup(); public SSServerUdpProxyHandler() { } @Override protected void channelRead0(ChannelHandlerContext clientCtx, ByteBuf msg) throws Exception { // logger.debug("readableBytes:" + msg.readableBytes()); InetSocketAddress clientSender = clientCtx.channel().attr(SSCommon.RemoteAddr).get(); InetSocketAddress clientRecipient = clientCtx.channel().attr(SSCommon.REMOTE_DES).get(); proxy(clientSender, clientRecipient, clientCtx, msg.retain()); } private void proxy(InetSocketAddress clientSender, InetSocketAddress clientRecipient, ChannelHandlerContext clientCtx, ByteBuf msg) { Channel pc = NatMapper.getUdpChannel(clientSender); if (pc == null) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(proxyBossGroup).channel(NioDatagramChannel.class) .option(ChannelOption.SO_RCVBUF, 64 * 1024)// 设置UDP读缓冲区为64k .option(ChannelOption.SO_SNDBUF, 64 * 1024)// 设置UDP写缓冲区为64k .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { int proxyIdleTimeout = clientRecipient.getPort() != 53 ? SSCommon.UDP_PROXY_IDEL_TIME : SSCommon.UDP_DNS_PROXY_IDEL_TIME; ch.pipeline() .addLast("timeout", new IdleStateHandler(0, 0, proxyIdleTimeout, TimeUnit.SECONDS) { @Override protected IdleStateEvent newIdleStateEvent(IdleState state, boolean first) { // logger.debug("{} state:{}", clientSender.toString(), state.toString()); NatMapper.closeChannelGracefully(clientSender); return super.newIdleStateEvent(state, first); } }) // .addLast(new LoggingHandler(LogLevel.INFO)) .addLast("udpProxy", new SimpleChannelInboundHandler<DatagramPacket>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { // logger.debug("rc received message "); clientCtx.channel().attr(SSCommon.REMOTE_SRC).set(msg.sender()); clientCtx.channel().writeAndFlush(msg.retain().content()); } }); } }); try { pc = bootstrap .bind(0) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { logger.debug("channel id {}, {}<->{}<->{} connect {}", clientCtx.channel().id().toString(), clientSender.toString(), future.channel().localAddress().toString(), clientRecipient.toString(), future.isSuccess()); NatMapper.putUdpChannel(clientSender, future.channel()); } } }) .sync() .channel(); } catch (Exception e) { logger.error("connect intenet error", e); return; } } else { // logger.debug("pc {} already exist", clientSender.toString()); } if (pc != null) { pc.writeAndFlush(new DatagramPacket(msg, clientRecipient)); } } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package DECL|package|org.apache.hadoop.crypto.key package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|crypto operator|. name|key package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Queue import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|LinkedBlockingQueue import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|TimeoutException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|crypto operator|. name|key operator|. name|kms operator|. name|ValueQueue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|crypto operator|. name|key operator|. name|kms operator|. name|ValueQueue operator|. name|QueueRefiller import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|crypto operator|. name|key operator|. name|kms operator|. name|ValueQueue operator|. name|SyncGenerationPolicy import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|test operator|. name|GenericTestUtils import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Assert import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|Sets import|; end_import begin_class DECL|class|TestValueQueue specifier|public class|class name|TestValueQueue block|{ DECL|field|LOG name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|TestValueQueue operator|. name|class argument_list|) decl_stmt|; DECL|class|FillInfo specifier|private specifier|static class|class name|FillInfo block|{ DECL|field|num specifier|final name|int name|num decl_stmt|; DECL|field|key specifier|final name|String name|key decl_stmt|; DECL|method|FillInfo (int num, String key) name|FillInfo parameter_list|( name|int name|num parameter_list|, name|String name|key parameter_list|) block|{ name|this operator|. name|num operator|= name|num expr_stmt|; name|this operator|. name|key operator|= name|key expr_stmt|; block|} block|} DECL|class|MockFiller specifier|private specifier|static class|class name|MockFiller implements|implements name|QueueRefiller argument_list|< name|String argument_list|> block|{ DECL|field|fillCalls specifier|final name|LinkedBlockingQueue argument_list|< name|FillInfo argument_list|> name|fillCalls init|= operator|new name|LinkedBlockingQueue argument_list|< name|FillInfo argument_list|> argument_list|() decl_stmt|; annotation|@ name|Override DECL|method|fillQueueForKey (String keyName, Queue<String> keyQueue, int numValues) specifier|public name|void name|fillQueueForKey parameter_list|( name|String name|keyName parameter_list|, name|Queue argument_list|< name|String argument_list|> name|keyQueue parameter_list|, name|int name|numValues parameter_list|) throws|throws name|IOException block|{ name|fillCalls operator|. name|add argument_list|( operator|new name|FillInfo argument_list|( name|numValues argument_list|, name|keyName argument_list|) argument_list|) expr_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|numValues condition|; name|i operator|++ control|) block|{ name|keyQueue operator|. name|add argument_list|( literal|"test" argument_list|) expr_stmt|; block|} block|} DECL|method|getTop () specifier|public name|FillInfo name|getTop parameter_list|() throws|throws name|InterruptedException block|{ return|return name|fillCalls operator|. name|poll argument_list|( literal|500 argument_list|, name|TimeUnit operator|. name|MILLISECONDS argument_list|) return|; block|} block|} DECL|method|waitForRefill (ValueQueue<?> valueQueue, String queueName, int queueSize) specifier|private name|void name|waitForRefill parameter_list|( name|ValueQueue argument_list|< name|? argument_list|> name|valueQueue parameter_list|, name|String name|queueName parameter_list|, name|int name|queueSize parameter_list|) throws|throws name|TimeoutException throws|, name|InterruptedException block|{ name|GenericTestUtils operator|. name|waitFor argument_list|( parameter_list|() lambda|-> block|{ name|int name|size init|= name|valueQueue operator|. name|getSize argument_list|( name|queueName argument_list|) decl_stmt|; if|if condition|( name|size operator|!= name|queueSize condition|) block|{ name|LOG operator|. name|info argument_list|( literal|"Current ValueQueue size is " operator|+ name|size argument_list|) expr_stmt|; return|return literal|false return|; block|} return|return literal|true return|; block|} argument_list|, literal|100 argument_list|, literal|3000 argument_list|) expr_stmt|; block|} comment|/** * Verifies that Queue is initially filled to "numInitValues" */ annotation|@ name|Test argument_list|( name|timeout operator|= literal|30000 argument_list|) DECL|method|testInitFill () specifier|public name|void name|testInitFill parameter_list|() throws|throws name|Exception block|{ name|MockFiller name|filler init|= operator|new name|MockFiller argument_list|() decl_stmt|; name|ValueQueue argument_list|< name|String argument_list|> name|vq init|= operator|new name|ValueQueue argument_list|< name|String argument_list|> argument_list|( literal|10 argument_list|, literal|0.1f argument_list|, literal|30000 argument_list|, literal|1 argument_list|, name|SyncGenerationPolicy operator|. name|ALL argument_list|, name|filler argument_list|) decl_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|"test" argument_list|, name|vq operator|. name|getNext argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|1 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; name|vq operator|. name|shutdown argument_list|() expr_stmt|; block|} comment|/** * Verifies that Queue is initialized (Warmed-up) for provided keys */ annotation|@ name|Test argument_list|( name|timeout operator|= literal|30000 argument_list|) DECL|method|testWarmUp () specifier|public name|void name|testWarmUp parameter_list|() throws|throws name|Exception block|{ name|MockFiller name|filler init|= operator|new name|MockFiller argument_list|() decl_stmt|; name|ValueQueue argument_list|< name|String argument_list|> name|vq init|= operator|new name|ValueQueue argument_list|< name|String argument_list|> argument_list|( literal|10 argument_list|, literal|0.5f argument_list|, literal|30000 argument_list|, literal|1 argument_list|, name|SyncGenerationPolicy operator|. name|ALL argument_list|, name|filler argument_list|) decl_stmt|; name|vq operator|. name|initializeQueuesForKeys argument_list|( literal|"k1" argument_list|, literal|"k2" argument_list|, literal|"k3" argument_list|) expr_stmt|; name|FillInfo index|[] name|fillInfos init|= block|{ name|filler operator|. name|getTop argument_list|() block|, name|filler operator|. name|getTop argument_list|() block|, name|filler operator|. name|getTop argument_list|() block|} decl_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|5 argument_list|, name|fillInfos index|[ literal|0 index|] operator|. name|num argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|5 argument_list|, name|fillInfos index|[ literal|1 index|] operator|. name|num argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|5 argument_list|, name|fillInfos index|[ literal|2 index|] operator|. name|num argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( name|Sets operator|. name|newHashSet argument_list|( literal|"k1" argument_list|, literal|"k2" argument_list|, literal|"k3" argument_list|) argument_list|, name|Sets operator|. name|newHashSet argument_list|( name|fillInfos index|[ literal|0 index|] operator|. name|key argument_list|, name|fillInfos index|[ literal|1 index|] operator|. name|key argument_list|, name|fillInfos index|[ literal|2 index|] operator|. name|key argument_list|) argument_list|) expr_stmt|; name|vq operator|. name|shutdown argument_list|() expr_stmt|; block|} comment|/** * Verifies that the refill task is executed after "checkInterval" if * num values below "lowWatermark" */ annotation|@ name|Test argument_list|( name|timeout operator|= literal|30000 argument_list|) DECL|method|testRefill () specifier|public name|void name|testRefill parameter_list|() throws|throws name|Exception block|{ name|MockFiller name|filler init|= operator|new name|MockFiller argument_list|() decl_stmt|; name|ValueQueue argument_list|< name|String argument_list|> name|vq init|= operator|new name|ValueQueue argument_list|< name|String argument_list|> argument_list|( literal|100 argument_list|, literal|0.1f argument_list|, literal|30000 argument_list|, literal|1 argument_list|, name|SyncGenerationPolicy operator|. name|ALL argument_list|, name|filler argument_list|) decl_stmt|; comment|// Trigger a prefill (10) and an async refill (91) name|Assert operator|. name|assertEquals argument_list|( literal|"test" argument_list|, name|vq operator|. name|getNext argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|10 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|100 argument_list|) expr_stmt|; comment|// Refill task should add 91 values to get to a full queue (10 produced by comment|// the prefill to the low watermark, 1 consumed by getNext()) name|Assert operator|. name|assertEquals argument_list|( literal|91 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; name|vq operator|. name|shutdown argument_list|() expr_stmt|; block|} comment|/** * Verifies that the No refill Happens after "checkInterval" if * num values above "lowWatermark" */ annotation|@ name|Test argument_list|( name|timeout operator|= literal|30000 argument_list|) DECL|method|testNoRefill () specifier|public name|void name|testNoRefill parameter_list|() throws|throws name|Exception block|{ name|MockFiller name|filler init|= operator|new name|MockFiller argument_list|() decl_stmt|; name|ValueQueue argument_list|< name|String argument_list|> name|vq init|= operator|new name|ValueQueue argument_list|< name|String argument_list|> argument_list|( literal|10 argument_list|, literal|0.5f argument_list|, literal|30000 argument_list|, literal|1 argument_list|, name|SyncGenerationPolicy operator|. name|ALL argument_list|, name|filler argument_list|) decl_stmt|; comment|// Trigger a prefill (5) and an async refill (6) name|Assert operator|. name|assertEquals argument_list|( literal|"test" argument_list|, name|vq operator|. name|getNext argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|5 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; comment|// Refill task should add 6 values to get to a full queue (5 produced by comment|// the prefill to the low watermark, 1 consumed by getNext()) name|Assert operator|. name|assertEquals argument_list|( literal|6 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Take another value, queue is still above the watermark name|Assert operator|. name|assertEquals argument_list|( literal|"test" argument_list|, name|vq operator|. name|getNext argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; comment|// Wait a while to make sure that no async refills are triggered try|try block|{ name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|TimeoutException name|ignored parameter_list|) block|{ comment|// This is the correct outcome - no refill is expected block|} name|Assert operator|. name|assertEquals argument_list|( literal|null argument_list|, name|filler operator|. name|getTop argument_list|() argument_list|) expr_stmt|; name|vq operator|. name|shutdown argument_list|() expr_stmt|; block|} comment|/** * Verify getAtMost when SyncGeneration Policy = ALL */ annotation|@ name|Test argument_list|( name|timeout operator|= literal|30000 argument_list|) DECL|method|testgetAtMostPolicyALL () specifier|public name|void name|testgetAtMostPolicyALL parameter_list|() throws|throws name|Exception block|{ name|MockFiller name|filler init|= operator|new name|MockFiller argument_list|() decl_stmt|; specifier|final name|ValueQueue argument_list|< name|String argument_list|> name|vq init|= operator|new name|ValueQueue argument_list|< name|String argument_list|> argument_list|( literal|10 argument_list|, literal|0.1f argument_list|, literal|30000 argument_list|, literal|1 argument_list|, name|SyncGenerationPolicy operator|. name|ALL argument_list|, name|filler argument_list|) decl_stmt|; comment|// Trigger a prefill (1) and an async refill (10) name|Assert operator|. name|assertEquals argument_list|( literal|"test" argument_list|, name|vq operator|. name|getNext argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|1 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; comment|// Refill task should add 10 values to get to a full queue (1 produced by comment|// the prefill to the low watermark, 1 consumed by getNext()) name|Assert operator|. name|assertEquals argument_list|( literal|10 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Drain completely, no further refills triggered name|vq operator|. name|drain argument_list|( literal|"k1" argument_list|) expr_stmt|; comment|// Wait a while to make sure that no async refills are triggered try|try block|{ name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|TimeoutException name|ignored parameter_list|) block|{ comment|// This is the correct outcome - no refill is expected block|} name|Assert operator|. name|assertNull argument_list|( name|filler operator|. name|getTop argument_list|() argument_list|) expr_stmt|; comment|// Synchronous call: comment|// 1. Synchronously fill returned list comment|// 2. Start another async task to fill the queue in the cache name|Assert operator|. name|assertEquals argument_list|( literal|"Failed in sync call." argument_list|, literal|10 argument_list|, name|vq operator|. name|getAtMost argument_list|( literal|"k1" argument_list|, literal|10 argument_list|) operator|. name|size argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|"Sync call filler got wrong number." argument_list|, literal|10 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; comment|// Refill task should add 10 values to get to a full queue name|Assert operator|. name|assertEquals argument_list|( literal|"Failed in async call." argument_list|, literal|10 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Drain completely after filled by the async thread name|vq operator|. name|drain argument_list|( literal|"k1" argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|"Failed to drain completely after async." argument_list|, literal|0 argument_list|, name|vq operator|. name|getSize argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; comment|// Synchronous call name|Assert operator|. name|assertEquals argument_list|( literal|"Failed to get all 19." argument_list|, literal|19 argument_list|, name|vq operator|. name|getAtMost argument_list|( literal|"k1" argument_list|, literal|19 argument_list|) operator|. name|size argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|"Failed in sync call." argument_list|, literal|19 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; name|vq operator|. name|shutdown argument_list|() expr_stmt|; block|} comment|/** * Verify getAtMost when SyncGeneration Policy = ALL */ annotation|@ name|Test argument_list|( name|timeout operator|= literal|30000 argument_list|) DECL|method|testgetAtMostPolicyATLEAST_ONE () specifier|public name|void name|testgetAtMostPolicyATLEAST_ONE parameter_list|() throws|throws name|Exception block|{ name|MockFiller name|filler init|= operator|new name|MockFiller argument_list|() decl_stmt|; name|ValueQueue argument_list|< name|String argument_list|> name|vq init|= operator|new name|ValueQueue argument_list|< name|String argument_list|> argument_list|( literal|10 argument_list|, literal|0.3f argument_list|, literal|30000 argument_list|, literal|1 argument_list|, name|SyncGenerationPolicy operator|. name|ATLEAST_ONE argument_list|, name|filler argument_list|) decl_stmt|; comment|// Trigger a prefill (3) and an async refill (8) name|Assert operator|. name|assertEquals argument_list|( literal|"test" argument_list|, name|vq operator|. name|getNext argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|3 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; comment|// Refill task should add 8 values to get to a full queue (3 produced by comment|// the prefill to the low watermark, 1 consumed by getNext()) name|Assert operator|. name|assertEquals argument_list|( literal|"Failed in async call." argument_list|, literal|8 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Drain completely, no further refills triggered name|vq operator|. name|drain argument_list|( literal|"k1" argument_list|) expr_stmt|; comment|// Queue is empty, sync will return a single value and trigger a refill name|Assert operator|. name|assertEquals argument_list|( literal|1 argument_list|, name|vq operator|. name|getAtMost argument_list|( literal|"k1" argument_list|, literal|10 argument_list|) operator|. name|size argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|1 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; comment|// Refill task should add 10 values to get to a full queue name|Assert operator|. name|assertEquals argument_list|( literal|"Failed in async call." argument_list|, literal|10 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; name|vq operator|. name|shutdown argument_list|() expr_stmt|; block|} comment|/** * Verify getAtMost when SyncGeneration Policy = LOW_WATERMARK */ annotation|@ name|Test argument_list|( name|timeout operator|= literal|30000 argument_list|) DECL|method|testgetAtMostPolicyLOW_WATERMARK () specifier|public name|void name|testgetAtMostPolicyLOW_WATERMARK parameter_list|() throws|throws name|Exception block|{ name|MockFiller name|filler init|= operator|new name|MockFiller argument_list|() decl_stmt|; name|ValueQueue argument_list|< name|String argument_list|> name|vq init|= operator|new name|ValueQueue argument_list|< name|String argument_list|> argument_list|( literal|10 argument_list|, literal|0.3f argument_list|, literal|30000 argument_list|, literal|1 argument_list|, name|SyncGenerationPolicy operator|. name|LOW_WATERMARK argument_list|, name|filler argument_list|) decl_stmt|; comment|// Trigger a prefill (3) and an async refill (8) name|Assert operator|. name|assertEquals argument_list|( literal|"test" argument_list|, name|vq operator|. name|getNext argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|3 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; comment|// Refill task should add 8 values to get to a full queue (3 produced by comment|// the prefill to the low watermark, 1 consumed by getNext()) name|Assert operator|. name|assertEquals argument_list|( literal|"Failed in async call." argument_list|, literal|8 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Drain completely, no further refills triggered name|vq operator|. name|drain argument_list|( literal|"k1" argument_list|) expr_stmt|; comment|// Queue is empty, sync will return 3 values and trigger a refill name|Assert operator|. name|assertEquals argument_list|( literal|3 argument_list|, name|vq operator|. name|getAtMost argument_list|( literal|"k1" argument_list|, literal|10 argument_list|) operator|. name|size argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|3 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; comment|// Refill task should add 10 values to get to a full queue name|Assert operator|. name|assertEquals argument_list|( literal|"Failed in async call." argument_list|, literal|10 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; name|vq operator|. name|shutdown argument_list|() expr_stmt|; block|} annotation|@ name|Test argument_list|( name|timeout operator|= literal|30000 argument_list|) DECL|method|testDrain () specifier|public name|void name|testDrain parameter_list|() throws|throws name|Exception block|{ name|MockFiller name|filler init|= operator|new name|MockFiller argument_list|() decl_stmt|; name|ValueQueue argument_list|< name|String argument_list|> name|vq init|= operator|new name|ValueQueue argument_list|< name|String argument_list|> argument_list|( literal|10 argument_list|, literal|0.1f argument_list|, literal|30000 argument_list|, literal|1 argument_list|, name|SyncGenerationPolicy operator|. name|ALL argument_list|, name|filler argument_list|) decl_stmt|; comment|// Trigger a prefill (1) and an async refill (10) name|Assert operator|. name|assertEquals argument_list|( literal|"test" argument_list|, name|vq operator|. name|getNext argument_list|( literal|"k1" argument_list|) argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( literal|1 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Wait for the async task to finish name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; comment|// Refill task should add 10 values to get to a full queue (1 produced by comment|// the prefill to the low watermark, 1 consumed by getNext()) name|Assert operator|. name|assertEquals argument_list|( literal|10 argument_list|, name|filler operator|. name|getTop argument_list|() operator|. name|num argument_list|) expr_stmt|; comment|// Drain completely, no further refills triggered name|vq operator|. name|drain argument_list|( literal|"k1" argument_list|) expr_stmt|; comment|// Wait a while to make sure that no async refills are triggered try|try block|{ name|waitForRefill argument_list|( name|vq argument_list|, literal|"k1" argument_list|, literal|10 argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|TimeoutException name|ignored parameter_list|) block|{ comment|// This is the correct outcome - no refill is expected block|} name|Assert operator|. name|assertNull argument_list|( name|filler operator|. name|getTop argument_list|() argument_list|) expr_stmt|; name|vq operator|. name|shutdown argument_list|() expr_stmt|; block|} block|} end_class end_unit
/* * Copyright (C) 2013-2017 microG Project 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.microg.gms; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import com.google.android.gms.common.internal.GetServiceRequest; import com.google.android.gms.common.internal.IGmsCallbacks; import com.google.android.gms.common.internal.IGmsServiceBroker; import org.microg.gms.common.GmsService; import java.util.Arrays; import java.util.EnumSet; public abstract class BaseService extends Service { private final IGmsServiceBroker broker; protected final String TAG; public BaseService(String tag, GmsService supportedService, GmsService... supportedServices) { this.TAG = tag; EnumSet<GmsService> services = EnumSet.of(supportedService); services.addAll(Arrays.asList(supportedServices)); broker = new AbstractGmsServiceBroker(services) { @Override public void handleServiceRequest(IGmsCallbacks callback, GetServiceRequest request, GmsService service) throws RemoteException { try { request.extras.keySet(); // call to unparcel() } catch (Exception e) { // Sometimes we need to define the correct ClassLoader before unparcel(). Ignore those. } Log.d(TAG, "bound by: " + request); BaseService.this.handleServiceRequest(callback, request, service); } }; } @Override public IBinder onBind(Intent intent) { Log.d(TAG, "onBind: " + intent); return broker.asBinder(); } public abstract void handleServiceRequest(IGmsCallbacks callback, GetServiceRequest request, GmsService service) throws RemoteException; }
/* * Copyright (c) 2018 - Manifold Systems LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package manifold.api.json; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import javax.script.ScriptException; import manifold.api.fs.IFile; import manifold.api.json.schema.IllegalSchemaTypeName; import manifold.internal.javac.IIssue; import manifold.internal.javac.IIssueContainer; import manifold.util.StreamUtil; /** */ public class JsonIssueContainer implements IIssueContainer { private final IFile _file; private final List<IIssue> _issues; @SuppressWarnings("unused") public JsonIssueContainer() { _issues = Collections.emptyList(); _file = null; } /** * Format of errors reported in ScriptException is: * <pre> * Found Errors:\n * [line:column] first error\n * [line:column] second error\n * ... * </pre> */ @SuppressWarnings("WeakerAccess") public JsonIssueContainer( ScriptException cause, IFile file ) { _issues = new ArrayList<>(); _file = file; addIssues( cause ); } @SuppressWarnings("WeakerAccess") public JsonIssueContainer( IFile file ) { _issues = new ArrayList<>(); _file = file; } private int findOffset( IFile file, int lineNum, int column ) { try { int offset = 0; String content = StreamUtil.getContent( new InputStreamReader( file.openInputStream() ) ); for( int i = 1; i < lineNum; i++ ) { if( content.length() > offset ) { offset = content.indexOf( '\n', offset ) + 1; } } return offset + column - 1; } catch( IOException e ) { throw new RuntimeException( e ); } } private int parseNum( String line, char delim ) { StringBuilder num = new StringBuilder(); for( int i = 0; i < line.length(); i++ ) { char c = line.charAt( i ); if( c != delim ) { num.append( c ); } else { try { return Integer.parseInt( num.toString() ); } catch( Exception e ) { return -1; } } } return -1; } @Override public List<IIssue> getIssues() { return _issues; } @Override public List<IIssue> getWarnings() { return Collections.emptyList(); } @Override public List<IIssue> getErrors() { return getIssues(); } @SuppressWarnings("WeakerAccess") public void addIssues( ScriptException cause ) { String message = cause.getMessage(); for( StringTokenizer tokenizer = new StringTokenizer( message, "\r\n" ); tokenizer.hasMoreTokens(); ) { String line = tokenizer.nextToken(); if( line.startsWith( "[" ) ) { int lineNum = parseNum( line.substring( 1 ), ':' ); int column = parseNum( line.substring( line.indexOf( ':' ) + 1 ) + 1, ']' ); int offset = findOffset( _file, lineNum, column ); String msg = line.substring( line.indexOf( ']' ) + 1 ); _issues.add( new JsonIssue( IIssue.Kind.Error, offset, lineNum, column, msg ) ); } } } @SuppressWarnings("WeakerAccess") public void addIssues( IllegalSchemaTypeName cause ) { Token token = cause.getToken(); int lineNum = token.getLineNumber(); int column = token.getColumn(); int offset = token.getOffset(); String msg = "Unknown schema type: " + cause.getTypeName(); _issues.add( new JsonIssue( IIssue.Kind.Error, offset, lineNum, column, msg ) ); } @Override public boolean isEmpty() { return _issues == null; } }
package by.bsuir.verkpavel.db.ui; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import by.bsuir.verkpavel.db.dao.db.threadpool.DBTask; import by.bsuir.verkpavel.db.dao.db.threadpool.DBThreadPool; import by.bsuir.verkpavel.db.fileutils.FileWriter; import by.bsuir.verkpavel.db.logic.RequestGenerator; public class MainView extends JFrame { private static final long serialVersionUID = 2883993883146596569L; private static final String SAVED_DATA = "savedData.txt"; private JPanel mainPanel; private JTextField connectionStringTextField; private JTextField userNameTextField; private JTextField passwordTextField; private JTextArea requestTextArea; public void showView() { this.setSize(460, 500); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - this.getWidth()) / 2); int y = (int) ((dimension.getHeight() - this.getHeight()) / 2); this.setLocation(x, y); this.setVisible(true); fillFieldsFromFile(); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent windowEvent) { System.exit(0); } }); } private void fillFieldsFromFile() { try { String fileData = FileWriter.read(SAVED_DATA); String[] fieldValues = fileData.split("~"); connectionStringTextField.setText(fieldValues[0]); userNameTextField.setText(fieldValues[1]); passwordTextField.setText(fieldValues[2]); requestTextArea.setText(fieldValues[3]); } catch (Exception e) { } } public MainView() { configureDefaultLayot(); } private void configureDefaultLayot() { setTitle("Генератор запросов"); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); mainPanel = new JPanel(); setContentPane(mainPanel); mainPanel.setLayout(null); final JCheckBox transactionCheckBox = new JCheckBox("Транзакция"); transactionCheckBox.setFont(new Font("Dialog", Font.PLAIN, 11)); transactionCheckBox.setBounds(14, 135, 85, 23); mainPanel.add(transactionCheckBox); final JSpinner countOfOperatorsSpinner = new JSpinner(); countOfOperatorsSpinner.setModel(new SpinnerNumberModel(1, 1, 1000, 1)); countOfOperatorsSpinner.setBounds(224, 136, 55, 20); mainPanel.add(countOfOperatorsSpinner); JLabel countOperators = new JLabel("Операторов в запросе"); countOperators.setFont(new Font("Dialog", Font.PLAIN, 11)); countOperators.setBounds(103, 139, 123, 14); mainPanel.add(countOperators); JLabel countOfThreadsLb = new JLabel("Кол-во потоков"); countOfThreadsLb.setFont(new Font("Dialog", Font.PLAIN, 11)); countOfThreadsLb.setBounds(289, 139, 94, 14); mainPanel.add(countOfThreadsLb); final JSpinner countOfThreadsSpinner = new JSpinner(); countOfThreadsSpinner.setModel(new SpinnerNumberModel(1, 1, 10, 1)); countOfThreadsSpinner.setBounds(382, 137, 34, 20); mainPanel.add(countOfThreadsSpinner); requestTextArea = new JTextArea(); requestTextArea.setLineWrap(true); requestTextArea.setWrapStyleWord(true); requestTextArea.setColumns(1); requestTextArea.setBounds(14, 177, 418, 187); JLabel label = new JLabel("Кол-во запросов"); label.setFont(new Font("Dialog", Font.PLAIN, 11)); label.setBounds(27, 406, 108, 14); mainPanel.add(label); final JSpinner countOfRequestSpinner = new JSpinner(); countOfRequestSpinner.setModel(new SpinnerNumberModel(1, 1, 1000, 1)); countOfRequestSpinner.setBounds(148, 403, 78, 20); mainPanel.add(countOfRequestSpinner); JButton button = new JButton("Запустить"); button.setBounds(265, 403, 129, 23); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String connectionString = connectionStringTextField.getText(); String userName = userNameTextField.getText(); String password = passwordTextField.getText(); String request = requestTextArea.getText(); saveDataInFile(connectionString, userName, password, request); int countOperatorsInRequest = (int) countOfOperatorsSpinner.getValue(); RequestGenerator requestGenerator = new RequestGenerator(countOperatorsInRequest, request); int countOfThreads = (int) countOfThreadsSpinner.getValue(); DBThreadPool dbThreadPool = new DBThreadPool(countOfThreads, connectionString, userName, password); if (dbThreadPool.isSuccessfullyCreated) { dbThreadPool.startTreads(); int countOfRequest = (int) countOfRequestSpinner.getValue(); boolean isTransaction = transactionCheckBox.isSelected(); for (int i = 0; i < countOfRequest; i++) { dbThreadPool.addTask(new DBTask(requestGenerator.getParametrazedQuery(), isTransaction, i)); } } } private void saveDataInFile(String connectionString, String userName, String password, String request) { // WARNING Data not encrypted FileWriter.write(SAVED_DATA, String.format("%s~%s~%s~%s", connectionString, userName, password, request)); } }); mainPanel.add(button); connectionStringTextField = new JTextField(); connectionStringTextField.setBounds(140, 11, 276, 20); connectionStringTextField.setFont(new Font("Dialog", Font.PLAIN, 11)); mainPanel.add(connectionStringTextField); connectionStringTextField.setColumns(10); JLabel connectionStringLabel = new JLabel("Строка подключения "); connectionStringLabel.setBounds(14, 14, 121, 14); connectionStringLabel.setFont(new Font("Dialog", Font.PLAIN, 11)); mainPanel.add(connectionStringLabel); userNameTextField = new JTextField(); userNameTextField.setColumns(10); userNameTextField.setFont(new Font("Dialog", Font.PLAIN, 11)); userNameTextField.setBounds(140, 42, 276, 20); mainPanel.add(userNameTextField); JLabel userNameLabel = new JLabel("Имя пользователя"); userNameLabel.setBounds(14, 45, 121, 14); userNameLabel.setFont(new Font("Dialog", Font.PLAIN, 11)); mainPanel.add(userNameLabel); passwordTextField = new JPasswordField(); passwordTextField.setColumns(10); passwordTextField.setFont(new Font("Dialog", Font.PLAIN, 11)); passwordTextField.setBounds(140, 73, 276, 20); mainPanel.add(passwordTextField); JLabel passwordLabel = new JLabel("Пароль"); passwordLabel.setBounds(14, 76, 121, 14); passwordLabel.setFont(new Font("Dialog", Font.PLAIN, 11)); mainPanel.add(passwordLabel); JScrollPane scrollPane = new JScrollPane(requestTextArea); scrollPane.setBounds(14, 177, 418, 187); mainPanel.add(scrollPane); } }
package com.iot.security.api.vo.log; import java.io.Serializable; import java.util.Date; public class LogInfo implements Serializable{ private String menu; private String opt; private String uri; private Date crtTime; private String crtUser; private String crtName; private String crtHost; public LogInfo(String menu, String option, String uri, Date crtTime, String crtUser, String crtName, String crtHost) { this.menu = menu; this.opt = option; this.uri = uri; this.crtTime = crtTime; this.crtUser = crtUser; this.crtName = crtName; this.crtHost = crtHost; } public LogInfo() { } public String getMenu() { return menu; } public void setMenu(String menu) { this.menu = menu; } public String getOpt() { return opt; } public void setOpt(String option) { this.opt = option; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Date getCrtTime() { return crtTime; } public void setCrtTime(Date crtTime) { this.crtTime = crtTime; } public String getCrtUser() { return crtUser; } public void setCrtUser(String crtUser) { this.crtUser = crtUser; } public String getCrtName() { return crtName; } public void setCrtName(String crtName) { this.crtName = crtName; } public String getCrtHost() { return crtHost; } public void setCrtHost(String crtHost) { this.crtHost = crtHost; } }
package com.xudre.dogosfromouterspace; import android.content.pm.ActivityInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView scoreView; private GameView gameView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); scoreView = findViewById(R.id.scoreView); gameView = findViewById(R.id.gameView); gameView.Main = this; } @Override protected void onPause() { super.onPause(); gameView.Paused = true; } @Override protected void onResume() { super.onResume(); gameView.Paused = false; } public void setScore(final int score) { runOnUiThread(new Runnable() { @Override public void run() { scoreView.setText(score + " pts"); } }); } }
package com.mmonteiroc.addesso.manager.entity; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.mmonteiroc.addesso.entity.Category; import com.mmonteiroc.addesso.exceptions.entity.CategoryNotFoundException; import com.mmonteiroc.addesso.exceptions.petition.NotRecivedRequiredParamsException; import com.mmonteiroc.addesso.repository.CategoryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Set; /** * Code created by: mmonteiroc * Email: miguelmonteiroclaveri@gmail.com * Github: https://github.com/mmonteiroc * LinkedIn: https://www.linkedin.com/in/mmonteiroc/?locale=en_US * Date of creation: 04/06/2020 * Package: com.mmonteiroc.addesso.manager.entity * Project: addesso */ @Service public class CategoryManager { @Autowired private CategoryRepository categoryRepository; @Autowired private Gson gson; public Category findById(Long id) throws CategoryNotFoundException { Category cat = this.categoryRepository.findByIdCategory(id); if (cat == null) throw new CategoryNotFoundException("Category with ID [" + id + "] was not found"); return cat; } public Set<Category> findAll() { return this.categoryRepository.findAll(); } public Category createFromJson(String json) { try { return this.createFromJson(json, false); } catch (NotRecivedRequiredParamsException e) { e.printStackTrace(); return null; } } public Category createFromJson(String json, boolean requiredParams) throws NotRecivedRequiredParamsException { JsonObject jsonObject = gson.fromJson(json, JsonObject.class); Category category = new Category(); if (jsonObject.get("idCategory") != null) { try { category = this.findById(jsonObject.get("idCategory").getAsLong()); } catch (CategoryNotFoundException e) { e.printStackTrace(); } } if (jsonObject.get("name") != null) { category.setName(jsonObject.get("name").getAsString()); } else if (requiredParams) { throw new NotRecivedRequiredParamsException("Param name missing"); } if (jsonObject.get("description") != null) { category.setDescription(jsonObject.get("description").getAsString()); } else if (requiredParams) { throw new NotRecivedRequiredParamsException("Param description missing"); } return category; } public void createOrUpdate(Category... categories) { Iterable<Category> iterable = Arrays.asList(categories); this.categoryRepository.saveAll(iterable); } public void remove(Category... categories) { Iterable<Category> iterable = Arrays.asList(categories); this.categoryRepository.deleteAll(iterable); } }
package others; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class CustomerWithMoviesAndSalesStand { private Integer customerId; private String customerName; private String customerSurname; private Integer customerAge; private String customerEmail; private Integer customerLoyaltyCardId; private String movieTitle; private String movieGenre; private BigDecimal ticketPrice; private Integer movieDuration; private LocalDate movieReleaseDate; private LocalDateTime startDateTime; }
package com.wan.web.controller.system; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.wan.common.domain.Page; import com.wan.common.util.ExcelUtil; import com.wan.common.util.FileUtil; import com.wan.system.domain.SysLog; import com.wan.system.domain.SysLoginLog; import com.wan.system.service.SysLogService; import com.wan.system.service.SysLoginLogService; import com.wan.web.controller.common.BaseController; /** * 操作日志 * @author wmj * */ @Controller @RequestMapping("/system/log") public class SysLogController extends BaseController { @Autowired private SysLogService logService; @Autowired private SysLoginLogService loginLogService; private String prefix = "system/log"; @GetMapping("/operLog") @PreAuthorize("hasAuthority('open:log:manage')") public String operLog() { return prefix + "/operLog"; } @GetMapping("/loginLog") @PreAuthorize("hasAuthority('open:log:manage')") public String loginLog() { return prefix + "/loginLog"; } @GetMapping("/errorLog") @PreAuthorize("hasAuthority('open:log:manage')") public String errorLog() { return prefix + "/errorLog"; } @GetMapping("/list") @ResponseBody @PreAuthorize("hasAuthority('open:log:manage')") public PageInfo<SysLog> list(SysLog log, Page page) { startPage(page); List<SysLog> list = logService.listLogs(log); PageInfo<SysLog> pageInfo = new PageInfo<>(list); return pageInfo; } @GetMapping("/loginList") @ResponseBody @PreAuthorize("hasAuthority('open:log:manage')") public PageInfo<SysLoginLog> loginList(SysLoginLog loginLog, Page page) { startPage(page); List<SysLoginLog> list = loginLogService.listLoginLogs(loginLog); PageInfo<SysLoginLog> pageInfo = new PageInfo<>(list); return pageInfo; } @GetMapping("/detail/{id}") @PreAuthorize("hasAuthority('open:log:manage')") public String detail(@PathVariable("id") Long id, ModelMap map) { SysLog log = logService.getLog(id); map.put("log", log); return prefix + "/detail"; } @GetMapping("/export") @PreAuthorize("hasAuthority('open:log:manage')") public void export(SysLog log, String fileName, HttpServletResponse response) { List<SysLog> list = logService.listLogs(log); ExcelUtil.exportHtmlExcel(list, SysLog.class, response, fileName + FileUtil.getRandomFileName(), null); } @GetMapping("/loginExport") @PreAuthorize("hasAuthority('open:log:manage')") public void loginExport(SysLoginLog loginLog, String fileName, HttpServletResponse response) { List<SysLoginLog> list = loginLogService.listLoginLogs(loginLog); ExcelUtil.exportHtmlExcel(list, SysLoginLog.class, response, fileName + FileUtil.getRandomFileName(), null); } }
/*L * Copyright Northwestern University. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.io/psc/LICENSE.txt for details. */ package edu.northwestern.bioinformatics.studycalendar.utility.osgimosis; import edu.northwestern.bioinformatics.studycalendar.utility.osgimosis.people.DefaultPerson; import edu.northwestern.bioinformatics.studycalendar.utility.osgimosis.people.Person; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.LinkedList; import java.util.List; /** * An executable to help in characterizing PermGen use by osgimosis. It's intended to be run * in a profiler. * * @author Rhett Sutphin */ public class MembraneLeak { @SuppressWarnings( { "InfiniteLoopStatement" }) public static void main(String[] args) throws Exception { ClassLoader a = new FileClassLoader("A", root()); ClassLoader b = new FileClassLoader("B", root()); List<Object> people = createPeopleOnCL(a); Membrane membrane = new DefaultMembrane(b, Person.class.getPackage().getName()); for (Object aPerson : people) { Object bPerson = membrane.farToNear(aPerson); System.out.println(bPerson + " once existed"); } System.out.println("Waiting"); while (true) { Thread.sleep(500); } } private static List<Object> createPeopleOnCL(ClassLoader a) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { List<Object> people = new LinkedList<Object>(); Class<?> aPersonClass = a.loadClass(DefaultPerson.class.getName()); Constructor<?> aPersonConstructor = aPersonClass.getConstructor(String.class, String.class); for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { for (int k = 0; k < 26; k++) { String n = new StringBuilder(). append((char) ('A' + i)).append((char) ('a' + j)).append((char) ('a' + k)). toString(); people.add(aPersonConstructor.newInstance(n, "Dude " + people .size())); } } } return people; } private static File root() { File root = new File("target/test/classes"); if (!root.exists()) { root = new File("utility/osgimosis", root.getPath()); if (!root.exists()) { throw new IllegalStateException("Could not determine class directory"); } } return root; } }
/* * 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.aliyuncs.edas.transform.v20170801; import com.aliyuncs.edas.model.v20170801.ModifyScalingRuleResponse; import com.aliyuncs.transform.UnmarshallerContext; public class ModifyScalingRuleResponseUnmarshaller { public static ModifyScalingRuleResponse unmarshall(ModifyScalingRuleResponse modifyScalingRuleResponse, UnmarshallerContext _ctx) { modifyScalingRuleResponse.setCode(_ctx.integerValue("ModifyScalingRuleResponse.Code")); modifyScalingRuleResponse.setMessage(_ctx.stringValue("ModifyScalingRuleResponse.Message")); return modifyScalingRuleResponse; } }
/* Copyright 2013, 2020 Nationale-Nederlanden, 2020 WeAreFrank! 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 nl.nn.adapterframework.pipes; import org.apache.commons.lang3.StringUtils; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.IPipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.doc.IbisDoc; import nl.nn.adapterframework.stream.Message; /** * Puts the input in the PipeLineSession, under the key specified by * <code>{@link #setSessionKey(String) sessionKey}</code>. * * @author Johan Verrips */ public class PutInSession extends FixedForwardPipe { private String sessionKey; private String value; @Override public void configure() throws ConfigurationException { super.configure(); if (StringUtils.isEmpty(getSessionKey())) { throw new ConfigurationException("attribute sessionKey must be specified"); } } @Override public PipeRunResult doPipe(Message message, IPipeLineSession session) throws PipeRunException { Object v; if (getValue() == null) { v = message.asObject(); } else { v = value; } session.put(getSessionKey(), v); if (log.isDebugEnabled()) log.debug(getLogPrefix(session) + "stored [" + v + "] in pipeLineSession under key [" + getSessionKey() + "]"); return new PipeRunResult(getForward(), message); } @IbisDoc({"1", "Key of the session variable to store the input in", "" }) public void setSessionKey(String newSessionKey) { sessionKey = newSessionKey; } public String getSessionKey() { return sessionKey; } @IbisDoc({"2", "Value to store in the <code>pipeLineSession</code>. If not set, the input of the pipe is stored", "" }) public void setValue(String value) { this.value = value; } public String getValue() { return value; } }