text
stringlengths 7
1.01M
|
|---|
/*
* Copyright Terracotta, 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.ehcache.clustered.lock.server.messages;
import org.ehcache.clustered.common.internal.lock.LockMessaging;
import org.terracotta.entity.MessageCodecException;
import org.terracotta.entity.SyncMessageCodec;
/**
* LockSyncMessaging
*/
public class LockSyncMessaging {
public static SyncMessageCodec<LockMessaging.LockOperation> syncCodec() {
return SYNC_CODEC;
}
private static final SyncMessageCodec<LockMessaging.LockOperation> SYNC_CODEC = new SyncMessageCodec<LockMessaging.LockOperation>() {
@Override
public byte[] encode(int i, LockMessaging.LockOperation message) {
throw new AssertionError();
}
@Override
public LockMessaging.LockOperation decode(int i, byte[] bytes) {
throw new AssertionError();
}
};
}
|
// Targeted by JavaCPP version 1.5.3: DO NOT EDIT THIS FILE
package org.bytedeco.tensorflow;
import org.bytedeco.tensorflow.Allocator;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.tensorflow.global.tensorflow.*;
// The session state remembers the tensors we choose to keep across
// multiple run calls.
@Namespace("tensorflow") @Properties(inherit = org.bytedeco.tensorflow.presets.tensorflow.class)
public class SessionState extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public SessionState() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public SessionState(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public SessionState(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public SessionState position(long position) {
return (SessionState)super.position(position);
}
// Get a tensor from the session state.
public native @ByVal Status GetTensor(@StdString BytePointer handle, Tensor tensor);
public native @ByVal Status GetTensor(@StdString String handle, Tensor tensor);
// Store a tensor in the session state.
public native @ByVal Status AddTensor(@StdString BytePointer handle, @Const @ByRef Tensor tensor);
public native @ByVal Status AddTensor(@StdString String handle, @Const @ByRef Tensor tensor);
// Delete a tensdor from the session state.
public native @ByVal Status DeleteTensor(@StdString BytePointer handle);
public native @ByVal Status DeleteTensor(@StdString String handle);
public native @Cast("tensorflow::int64") long GetNewId();
public static native @Cast("const char*") BytePointer kTensorHandleResourceTypeName(); public static native void kTensorHandleResourceTypeName(BytePointer setter);
}
|
package com.github.budsterblue.revolutap;
public class DataParserTester {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String path = "18260 Masayoshi Minoshima feat nomico - Bad Apple!!/Masayoshi Minoshima feat. nomico - Bad Apple!! (ouranhshc) [lepidon! - Taiko Oni].osu";
DataParser dp = new DataParser(path);
// Info
System.out.println(dp.df.getArtist());
System.out.println(dp.df.getBPMRange());
System.out.println(dp.df.getFilename());
System.out.println(dp.df.getNotesDataDifficulties());
System.out.println(dp.df.getOffset());
System.out.println(dp.df.getPath());
System.out.println(dp.df.getTitle());
System.out.println(dp.df.getMusic());
System.out.println(dp.df.notesData.size());
dp.setNotesDataIndex(0);
// Notes Data info
DataNotesData nd = dp.getNotesData();
System.out.println(nd.getDescription());
System.out.println(nd.getDifficultyMeter());
System.out.println(nd.getDifficulty());
System.out.println(nd.getNotesType());
// NotesData
//DataNotesData nd = dp.getNotesData();
//System.out.println(nd.getNotesData());
///*
dp.loadNotes(true, true, true);
/*
for (DataNote n : dp.df.notesData.get(0).notes) {
System.out.println(n);
}
*/
//*/
/*
while (dp.hasNext()) {
System.out.println(dp.next());
}
*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.neusoft.library.common.utils;
import java.text.DecimalFormat;
/**
* <p>
* 文件大小工具类.
* </p>
*
*/
public class FileSizeHelper {
public static long ONE_KB = 1024;
public static long ONE_MB = ONE_KB * 1024;
public static long ONE_GB = ONE_MB * 1024;
public static long ONE_TB = ONE_GB * (long)1024;
public static long ONE_PB = ONE_TB * (long)1024;
public static String getHumanReadableFileSize(Long fileSize) {
if(fileSize == null) return null;
return getHumanReadableFileSize(fileSize.longValue());
}
public static String getHumanReadableFileSize(long fileSize) {
if(fileSize < 0) {
return String.valueOf(fileSize);
}
String result = getHumanReadableFileSize(fileSize, ONE_PB, "PB");
if(result != null) {
return result;
}
result = getHumanReadableFileSize(fileSize, ONE_TB, "TB");
if(result != null) {
return result;
}
result = getHumanReadableFileSize(fileSize, ONE_GB, "GB");
if(result != null) {
return result;
}
result = getHumanReadableFileSize(fileSize, ONE_MB, "MB");
if(result != null) {
return result;
}
result = getHumanReadableFileSize(fileSize, ONE_KB, "KB");
if(result != null) {
return result;
}
return String.valueOf(fileSize)+"B";
}
private static String getHumanReadableFileSize(long fileSize, long unit, String unitName) {
if(fileSize == 0) return "0";
if(fileSize / unit >= 1) {
double value = fileSize / (double)unit;
DecimalFormat df = new DecimalFormat("######.##"+unitName);
return df.format(value);
}
return null;
}
}
|
/*
* 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.s3.endpoint;
import org.apache.hadoop.ozone.OzoneAcl;
import org.apache.hadoop.ozone.s3.endpoint.S3BucketAcl.Grant;
import org.apache.hadoop.ozone.s3.endpoint.S3BucketAcl.Grantee;
import org.apache.hadoop.ozone.s3.exception.OS3Exception;
import org.apache.hadoop.ozone.s3.exception.S3ErrorTable;
import org.apache.hadoop.ozone.security.acl.IAccessAuthorizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import static org.apache.hadoop.ozone.s3.exception.S3ErrorTable.INVALID_ARGUMENT;
import static org.apache.hadoop.ozone.s3.exception.S3ErrorTable.NOT_IMPLEMENTED;
/**
* TODO: javadoc.
*/
public final class S3Acl {
private static final Logger LOG = LoggerFactory.getLogger(S3Acl.class);
// ACL put related headers
public static final String GRANT_READ = "x-amz-grant-read";
public static final String GRANT_WRITE = "x-amz-grant-write";
public static final String GRANT_READ_CAP = "x-amz-grant-read-acp";
public static final String GRANT_WRITE_CAP = "x-amz-grant-write-acp";
public static final String GRANT_FULL_CONTROL = "x-amz-grant-full-control";
// Not supported headers at current stage, may support it in future
public static final String CANNED_ACL_HEADER = "x-amz-acl";
/**
* https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html.
*/
enum ACLType {
// Allows grantee to list the objects in the bucket
READ("READ"),
// Allows grantee to create, overwrite, and delete any object in the bucket
WRITE("WRITE"),
// Allows grantee to write the bucket ACL
READ_ACP("READ_ACP"),
// Allows grantee to write the ACL for the applicable bucket
WRITE_ACP("WRITE_ACP"),
// Allows grantee above all permissions on the bucket
FULL_CONTROL("FULL_CONTROL");
public String getValue() {
return value;
}
/**
* String value for this Enum.
*/
private final String value;
/**
* @param val String type for this enum.
*/
ACLType(String val) {
value = val;
}
public static ACLType getType(String typeStr) {
for (ACLType type: ACLType.values()) {
if (type.getValue().equals(typeStr)) {
return type;
}
}
return null;
}
}
/**
* TODO: javadoc.
*/
enum ACLIdentityType {
USER("CanonicalUser", true, "id"),
GROUP("Group", false, "url"),
USER_BY_EMAIL("AmazonCustomerByEmail", false, "emailAddress");
public String getGranteeType() {
return granteeType;
}
public String getHeaderType() {
return granteeInHeader;
}
/**
* Grantee type in body XML.
*/
private final String granteeType;
/**
* Is this type supported or not.
*/
private final boolean supported;
/**
* Grantee type in header.
*/
private final String granteeInHeader;
/**
* Init OzoneACLtypes enum.
*
* @param val String type for this enum.
*/
ACLIdentityType(String val, boolean support, String headerType) {
granteeType = val;
supported = support;
granteeInHeader = headerType;
}
boolean isSupported() {
return supported;
}
public static ACLIdentityType getTypeFromGranteeType(String typeStr) {
for (ACLIdentityType type: ACLIdentityType.values()) {
if (type.getGranteeType().equals(typeStr)) {
return type;
}
}
return null;
}
public static ACLIdentityType getTypeFromHeaderType(String typeStr) {
for (ACLIdentityType type: ACLIdentityType.values()) {
if (type.getHeaderType().equals(typeStr)) {
return type;
}
}
return null;
}
}
private S3Acl() {
}
public static boolean isGranteeTypeSupported(String typeStr) {
ACLIdentityType type = ACLIdentityType.getTypeFromGranteeType(typeStr);
return type == null ? false : type.isSupported();
}
public static boolean isHeaderTypeSupported(String typeStr) {
ACLIdentityType type = ACLIdentityType.getTypeFromHeaderType(typeStr);
return type == null ? false : type.isSupported();
}
public static List<Grant> ozoneNativeAclToS3Acl(OzoneAcl ozoneAcl) {
// Since currently only "CanonicalUser" is supported, which maps to Ozone
// "USER"
List<Grant> grantList = new ArrayList<>();
if (ozoneAcl.getType() != IAccessAuthorizer.ACLIdentityType.USER) {
return grantList;
}
Grantee grantee = new Grantee();
grantee.setDisplayName(ozoneAcl.getName());
grantee.setId(ozoneAcl.getName());
List<IAccessAuthorizer.ACLType> acls = ozoneAcl.getAclList();
if (acls.contains(IAccessAuthorizer.ACLType.ALL)) {
Grant grant = new Grant();
grant.setGrantee(grantee);
grant.setPermission(ACLType.FULL_CONTROL.toString());
grantList.add(grant);
} else if (acls.contains(IAccessAuthorizer.ACLType.WRITE_ACL)) {
Grant grant = new Grant();
grant.setGrantee(grantee);
grant.setPermission(ACLType.WRITE_ACP.toString());
grantList.add(grant);
} else if (acls.contains(IAccessAuthorizer.ACLType.READ_ACL)) {
Grant grant = new Grant();
grant.setGrantee(grantee);
grant.setPermission(ACLType.READ_ACP.toString());
grantList.add(grant);
} else if (acls.contains(IAccessAuthorizer.ACLType.WRITE) &&
acls.contains(IAccessAuthorizer.ACLType.DELETE) &&
acls.contains(IAccessAuthorizer.ACLType.CREATE)) {
Grant grant = new Grant();
grant.setGrantee(grantee);
grant.setPermission(ACLType.WRITE.toString());
grantList.add(grant);
} else if (acls.contains(IAccessAuthorizer.ACLType.READ) &&
acls.contains(IAccessAuthorizer.ACLType.LIST)) {
Grant grant = new Grant();
grant.setGrantee(grantee);
grant.setPermission(ACLType.READ.toString());
grantList.add(grant);
} else {
LOG.error("Cannot find a good mapping for Ozone ACL {} to S3",
ozoneAcl.toString());
}
return grantList;
}
public static List<OzoneAcl> s3AclToOzoneNativeAclOnBucket(
S3BucketAcl bucketAcl) throws OS3Exception {
List<OzoneAcl> ozoneAclList = new ArrayList<>();
List<Grant> grantList = bucketAcl.getAclList().getGrantList();
for (Grant grant : grantList) {
// Only "CanonicalUser" is supported, which maps to Ozone "USER"
ACLIdentityType identityType = ACLIdentityType.getTypeFromGranteeType(
grant.getGrantee().getXsiType());
if (identityType != null && identityType.isSupported()) {
String permission = grant.getPermission();
BitSet acls = getOzoneAclOnBucketFromS3Permission(permission);
OzoneAcl defaultOzoneAcl = new OzoneAcl(
IAccessAuthorizer.ACLIdentityType.USER,
grant.getGrantee().getId(), acls,
OzoneAcl.AclScope.DEFAULT);
OzoneAcl accessOzoneAcl = new OzoneAcl(
IAccessAuthorizer.ACLIdentityType.USER,
grant.getGrantee().getId(), acls,
OzoneAcl.AclScope.ACCESS);
ozoneAclList.add(defaultOzoneAcl);
ozoneAclList.add(accessOzoneAcl);
} else {
LOG.error("Grantee type {} is not supported",
grant.getGrantee().getXsiType());
throw S3ErrorTable.newError(NOT_IMPLEMENTED,
grant.getGrantee().getXsiType());
}
}
return ozoneAclList;
}
public static BitSet getOzoneAclOnBucketFromS3Permission(String permission)
throws OS3Exception {
ACLType permissionType = ACLType.getType(permission);
if (permissionType == null) {
throw S3ErrorTable.newError(S3ErrorTable.INVALID_ARGUMENT, permission);
}
BitSet acls = new BitSet(IAccessAuthorizer.ACLType.getNoOfAcls());
switch (permissionType) {
case FULL_CONTROL:
acls.set(IAccessAuthorizer.ACLType.ALL.ordinal());
break;
case WRITE_ACP:
acls.set(IAccessAuthorizer.ACLType.WRITE_ACL.ordinal());
break;
case READ_ACP:
acls.set(IAccessAuthorizer.ACLType.READ_ACL.ordinal());
break;
case WRITE:
acls.set(IAccessAuthorizer.ACLType.WRITE.ordinal());
acls.set(IAccessAuthorizer.ACLType.DELETE.ordinal());
acls.set(IAccessAuthorizer.ACLType.CREATE.ordinal());
break;
case READ:
acls.set(IAccessAuthorizer.ACLType.READ.ordinal());
acls.set(IAccessAuthorizer.ACLType.LIST.ordinal());
break;
default:
LOG.error("Failed to recognize S3 permission {}", permission);
throw S3ErrorTable.newError(INVALID_ARGUMENT, permission);
}
return acls;
}
public static List<OzoneAcl> s3AclToOzoneNativeAclOnVolume(
S3BucketAcl bucketAcl) throws OS3Exception {
List<OzoneAcl> ozoneAclList = new ArrayList<>();
List<Grant> grantList = bucketAcl.getAclList().getGrantList();
for (Grant grant : grantList) {
// Only "CanonicalUser" is supported, which maps to Ozone "USER"
ACLIdentityType identityType = ACLIdentityType.getTypeFromGranteeType(
grant.getGrantee().getXsiType());
if (identityType != null && identityType.isSupported()) {
String permission = grant.getPermission();
BitSet acls = getOzoneAclOnVolumeFromS3Permission(permission);
OzoneAcl accessOzoneAcl = new OzoneAcl(
IAccessAuthorizer.ACLIdentityType.USER,
grant.getGrantee().getId(), acls,
OzoneAcl.AclScope.ACCESS);
ozoneAclList.add(accessOzoneAcl);
} else {
LOG.error("Grantee type {} is not supported",
grant.getGrantee().getXsiType());
throw S3ErrorTable.newError(NOT_IMPLEMENTED,
grant.getGrantee().getXsiType());
}
}
return ozoneAclList;
}
// User privilege on volume follows the "lest privilege" principle.
public static BitSet getOzoneAclOnVolumeFromS3Permission(String permission)
throws OS3Exception {
BitSet acls = new BitSet(IAccessAuthorizer.ACLType.getNoOfAcls());
ACLType permissionType = ACLType.getType(permission);
if (permissionType == null) {
throw S3ErrorTable.newError(S3ErrorTable.INVALID_ARGUMENT, permission);
}
switch (permissionType) {
case FULL_CONTROL:
acls.set(IAccessAuthorizer.ACLType.READ.ordinal());
acls.set(IAccessAuthorizer.ACLType.WRITE.ordinal());
acls.set(IAccessAuthorizer.ACLType.READ_ACL.ordinal());
acls.set(IAccessAuthorizer.ACLType.WRITE_ACL.ordinal());
break;
case WRITE_ACP:
acls.set(IAccessAuthorizer.ACLType.READ.ordinal());
acls.set(IAccessAuthorizer.ACLType.READ_ACL.ordinal());
acls.set(IAccessAuthorizer.ACLType.WRITE_ACL.ordinal());
break;
case READ_ACP:
acls.set(IAccessAuthorizer.ACLType.READ.ordinal());
acls.set(IAccessAuthorizer.ACLType.READ_ACL.ordinal());
break;
case WRITE:
acls.set(IAccessAuthorizer.ACLType.READ.ordinal());
acls.set(IAccessAuthorizer.ACLType.WRITE.ordinal());
break;
case READ:
acls.set(IAccessAuthorizer.ACLType.READ.ordinal());
break;
default:
LOG.error("Failed to recognize S3 permission {}", permission);
throw S3ErrorTable.newError(INVALID_ARGUMENT, permission);
}
return acls;
}
}
|
package okio;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
public interface BufferedSource extends Source, ReadableByteChannel {
Buffer buffer();
boolean exhausted() throws IOException;
long indexOf(byte b) throws IOException;
long indexOf(byte b, long j) throws IOException;
long indexOf(byte b, long j, long j2) throws IOException;
long indexOf(ByteString byteString) throws IOException;
long indexOf(ByteString byteString, long j) throws IOException;
long indexOfElement(ByteString byteString) throws IOException;
long indexOfElement(ByteString byteString, long j) throws IOException;
InputStream inputStream();
boolean rangeEquals(long j, ByteString byteString) throws IOException;
boolean rangeEquals(long j, ByteString byteString, int i, int i2) throws IOException;
int read(byte[] bArr) throws IOException;
int read(byte[] bArr, int i, int i2) throws IOException;
long readAll(Sink sink) throws IOException;
byte readByte() throws IOException;
byte[] readByteArray() throws IOException;
byte[] readByteArray(long j) throws IOException;
ByteString readByteString() throws IOException;
ByteString readByteString(long j) throws IOException;
long readDecimalLong() throws IOException;
void readFully(Buffer buffer, long j) throws IOException;
void readFully(byte[] bArr) throws IOException;
long readHexadecimalUnsignedLong() throws IOException;
int readInt() throws IOException;
int readIntLe() throws IOException;
long readLong() throws IOException;
long readLongLe() throws IOException;
short readShort() throws IOException;
short readShortLe() throws IOException;
String readString(long j, Charset charset) throws IOException;
String readString(Charset charset) throws IOException;
String readUtf8() throws IOException;
String readUtf8(long j) throws IOException;
int readUtf8CodePoint() throws IOException;
String readUtf8Line() throws IOException;
String readUtf8LineStrict() throws IOException;
String readUtf8LineStrict(long j) throws IOException;
boolean request(long j) throws IOException;
void require(long j) throws IOException;
int select(Options options) throws IOException;
void skip(long j) throws IOException;
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.security.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The security automation model state property bag. */
@Fluent
public final class AutomationValidationStatusInner {
@JsonIgnore private final ClientLogger logger = new ClientLogger(AutomationValidationStatusInner.class);
/*
* Indicates whether the model is valid or not.
*/
@JsonProperty(value = "isValid")
private Boolean isValid;
/*
* The validation message.
*/
@JsonProperty(value = "message")
private String message;
/**
* Get the isValid property: Indicates whether the model is valid or not.
*
* @return the isValid value.
*/
public Boolean isValid() {
return this.isValid;
}
/**
* Set the isValid property: Indicates whether the model is valid or not.
*
* @param isValid the isValid value to set.
* @return the AutomationValidationStatusInner object itself.
*/
public AutomationValidationStatusInner withIsValid(Boolean isValid) {
this.isValid = isValid;
return this;
}
/**
* Get the message property: The validation message.
*
* @return the message value.
*/
public String message() {
return this.message;
}
/**
* Set the message property: The validation message.
*
* @param message the message value to set.
* @return the AutomationValidationStatusInner object itself.
*/
public AutomationValidationStatusInner withMessage(String message) {
this.message = message;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.hadoop.shim.common.format.parquet;
import org.apache.hadoop.conf.Configuration;
//#if shim_type=="HDP" || shim_type=="EMR" || shim_type=="HDI"
import org.apache.parquet.hadoop.api.WriteSupport;
//#endif
//#if shim_type=="CDH" || shim_type=="MAPR"
//$import parquet.hadoop.api.WriteSupport;
//#endif
import org.pentaho.di.core.util.Assert;
import org.junit.Test;
import org.pentaho.hadoop.shim.api.format.SchemaDescription;
import org.pentaho.hadoop.shim.common.format.ParquetUtils;
public class PentahoParquetWriteSupportTest {
@Test( expected = RuntimeException.class )
public void initParquetWriteSupportWhenSchemaIsNull() {
SchemaDescription schema = new SchemaDescription();
PentahoParquetWriteSupport writeSupport = new PentahoParquetWriteSupport( schema );
Configuration conf = new Configuration();
conf.set( "fs.defaultFS", "file:///" );
writeSupport.init( conf );
}
@Test
public void initParquetWriteSupportWhenSchemaIsNotNull() {
int pentahoValueMetaTypeFirstRow = 2;
boolean allowNullFirstRow = false;
int pentahoValueMetaTypeSecondRow = 5;
boolean allowNullSecondRow = false;
String schemaFromString = ParquetUtils
.createSchema( pentahoValueMetaTypeFirstRow, allowNullFirstRow, pentahoValueMetaTypeSecondRow,
allowNullSecondRow ).marshall();
SchemaDescription schema = SchemaDescription.unmarshall( schemaFromString );
PentahoParquetWriteSupport writeSupport = new PentahoParquetWriteSupport( schema );
Configuration conf = new Configuration();
conf.set( "fs.defaultFS", "file:///" );
WriteSupport.WriteContext writeContext = writeSupport.init( conf );
Assert.assertNotNull( writeContext );
}
}
|
//
// $Id: Filter.java,v 1.4 2010-01-05 13:49:58 ylafon Exp $
// From Sijtsche de Jong (sy.de.jong@let.rug.nl)
//
// (c) COPYRIGHT 1995-2000 World Wide Web Consortium (MIT, INRIA, Keio University)
// Please first read the full copyright statement at
// http://www.w3.org/Consortium/Legal/copyright-software-19980720
package org.w3c.css.properties.svg;
import org.w3c.css.parser.CssStyle;
import org.w3c.css.properties.css.CssProperty;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.InvalidParamException;
import org.w3c.css.values.CssExpression;
import org.w3c.css.values.CssIdent;
import org.w3c.css.values.CssURL;
import org.w3c.css.values.CssValue;
/**
* <P>
* <EM>Value:</EM> <uri> || none || inherit<BR>
* <EM>Initial:</EM>none<BR>
* <EM>Applies to:</EM>graphics and container elements<BR>
* <EM>Inherited:</EM>no<BR>
* <EM>Percentages:</EM>no<BR>
* <EM>Media:</EM>:visual
*/
public class Filter extends CssProperty {
CssValue value;
ApplContext ac;
CssIdent none = new CssIdent("none");
/**
* Create a new Filter
*/
public Filter() {
// nothing to do
}
/**
* Create a new Filter
*
* @param expression The expression for this property
* @exception InvalidParamException Values are incorrect
*/
public Filter(ApplContext ac, CssExpression expression,
boolean check) throws InvalidParamException {
this.ac = ac;
setByUser(); // tell this property is set by the user
CssValue val = expression.getValue();
if (val instanceof CssURL) {
value = val;
expression.next();
}
else if (val instanceof CssIdent) {
if (val.equals(inherit)) {
value = inherit;
expression.next();
} else if (val.equals(none)) {
value = none;
expression.next();
}
}
else {
throw new InvalidParamException("value", val.toString(), getPropertyName(), ac);
}
}
public Filter(ApplContext ac, CssExpression expression)
throws InvalidParamException {
this(ac, expression, false);
}
/**
* Add this property to the CssStyle.
*
* @param style The CssStyle
*/
public void addToStyle(ApplContext ac, CssStyle style) {
if (((SVGBasicStyle) style).filter != null)
style.addRedefinitionWarning(ac, this);
((SVGBasicStyle) style).filter = this;
}
/**
* Get this property in the style.
*
* @param style The style where the property is
* @param resolve if true, resolve the style to find this property
*/
public CssProperty getPropertyInStyle(CssStyle style, boolean resolve) {
if (resolve) {
return ((SVGBasicStyle) style).getFilter();
} else {
return ((SVGBasicStyle) style).filter;
}
}
/**
* Compares two properties for equality.
*
* @param value The other property.
*/
public boolean equals(CssProperty property) {
return (property instanceof Filter &&
value.equals( ((Filter) property).value));
}
/**
* Returns the name of this property
*/
public String getPropertyName() {
return "filter";
}
/**
* Returns the value of this property
*/
public Object get() {
return value;
}
/**
* Returns true if this property is "softly" inherited
*/
public boolean isSoftlyInherited() {
return value.equals(inherit);
}
/**
* Returns a string representation of the object
*/
public String toString() {
return value.toString();
}
/**
* Is the value of this property a default value
* It is used by all macro for the function <code>print</code>
*/
public boolean isDefault() {
return value == none;
}
}
|
package dev.vality.woody.thrift.impl.http;
import dev.vality.woody.rpc.Owner;
import dev.vality.woody.rpc.OwnerServiceSrv;
import dev.vality.woody.rpc.TestHttp;
import dev.vality.woody.thrift.impl.http.event.ClientEventListenerImpl;
import dev.vality.woody.thrift.impl.http.event.ServiceEventListenerImpl;
import org.apache.http.impl.client.HttpClients;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.server.TServlet;
import org.apache.thrift.transport.THttpClient;
import org.apache.thrift.transport.TTransportException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.*;
import javax.servlet.Servlet;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.stream.IntStream;
@Ignore
public class TestLoadThriftRPCClient {
private Server server;
@Before
public void startJetty() throws Exception {
server = new Server(8080);
ServletContextHandler context = new ServletContextHandler();
ServletHolder defaultServ = new ServletHolder("default", TestHttp.TServletExample.class);
context.addServlet(defaultServ, "/default");
THServiceBuilder serviceBuilder = new THServiceBuilder();
serviceBuilder.withEventListener(new ServiceEventListenerImpl());
Servlet rpcServlet = serviceBuilder.build(OwnerServiceSrv.Iface.class, new OwnerServiceImpl());
ServletHolder rpcServ = new ServletHolder("rpc", rpcServlet);
context.addServlet(defaultServ, "/rpc");
server.setHandler(context);
// Start Server
server.start();
}
@After
public void stopJetty() {
try {
server.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testServlet() throws TTransportException, TException, URISyntaxException {
String defaultServletUrl = "http://localhost:8080/default";
String rpcServletUrl = "http://localhost:8080/rpc";
OwnerServiceSrv.Iface tClient = createThriftClient(defaultServletUrl);
OwnerServiceSrv.Iface tRPCClient = createThriftRPCClient(rpcServletUrl);
Owner bean = tClient.getOwner(1);
Assert.assertEquals("name", bean.getName());
bean = tRPCClient.getOwner(1);
Assert.assertEquals("name", bean.getName());
IntStream.range(1, 1000).forEach(i -> {
try {
tClient.getOwner(i);
tRPCClient.getOwner(i);
} catch (TException e) {
e.printStackTrace();
}
});
int testCount = 20000;
runThriftRPC(testCount, tRPCClient);
runThrift(testCount, tClient);
System.out.println("Warmup ended.");
testCount = 10000;
runThriftRPC(testCount, tRPCClient);
runThrift(testCount, tClient);
testCount = 10000;
runThrift(testCount, tClient);
runThriftRPC(testCount, tRPCClient);
}
private void runThrift(int testCount, OwnerServiceSrv.Iface tClient) {
long start = System.currentTimeMillis();
IntStream.range(1, testCount).forEach(i -> {
try {
tClient.getOwner(i);
} catch (Exception e) {
e.printStackTrace();
}
});
System.out.printf("Thrift: %d iterations, %d time\n", testCount, System.currentTimeMillis() - start);
}
private void runThriftRPC(int testCount, OwnerServiceSrv.Iface tRPCClient) {
long start = System.currentTimeMillis();
IntStream.range(1, testCount).forEach(i -> {
try {
tRPCClient.getOwner(i);
} catch (Exception e) {
e.printStackTrace();
}
});
System.out.printf("Thrift RPC: %d iterations, %d time\n", testCount, System.currentTimeMillis() - start);
}
public static class TServletExample extends TServlet {
public TServletExample() {
super(
new OwnerServiceSrv.Processor(
new OwnerServiceImpl()),
new TBinaryProtocol.Factory()
);
}
}
private OwnerServiceSrv.Iface createThriftClient(String url) throws TTransportException {
THttpClient thc = new THttpClient(url, HttpClients.createMinimal());
TProtocol loPFactory = new TBinaryProtocol(thc);
return new OwnerServiceSrv.Client(loPFactory);
}
private OwnerServiceSrv.Iface createThriftRPCClient(String url) throws URISyntaxException {
THClientBuilder clientBuilder = new THClientBuilder();
clientBuilder.withAddress(new URI(url));
clientBuilder.withHttpClient(HttpClients.createMinimal());
clientBuilder.withEventListener(new ClientEventListenerImpl());
return clientBuilder.build(OwnerServiceSrv.Iface.class);
}
private static class OwnerServiceImpl extends OwnerServiceStub {
@Override
public Owner getOwner(int id) throws TException {
return new Owner(id, "name");
}
}
}
|
package com.lcy.xingchenmall.product.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcy.common.utils.PageUtils;
import com.lcy.common.utils.Query;
import com.lcy.xingchenmall.product.dao.SpuInfoDescDao;
import com.lcy.xingchenmall.product.entity.SpuInfoDescEntity;
import com.lcy.xingchenmall.product.service.SpuInfoDescService;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service("spuInfoDescService")
public class SpuInfoDescServiceImpl extends ServiceImpl<SpuInfoDescDao, SpuInfoDescEntity> implements SpuInfoDescService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<SpuInfoDescEntity> page = this.page(
new Query<SpuInfoDescEntity>().getPage(params),
new QueryWrapper<SpuInfoDescEntity>()
);
return new PageUtils(page);
}
@Override
public void saveSpuInfoDesc(SpuInfoDescEntity descEntity) {
this.baseMapper.insert(descEntity);
}
}
|
/* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the BSD New License, available at the root
* application directory.
*/
package org.geogit.web.api.commands;
import javax.annotation.Nullable;
import org.geogit.api.GeogitTransaction;
import org.geogit.api.ObjectId;
import org.geogit.api.Ref;
import org.geogit.api.RevCommit;
import org.geogit.api.plumbing.FindCommonAncestor;
import org.geogit.api.plumbing.RefParse;
import org.geogit.api.plumbing.RevParse;
import org.geogit.api.plumbing.merge.MergeScenarioReport;
import org.geogit.api.plumbing.merge.ReportMergeScenarioOp;
import org.geogit.api.porcelain.MergeOp;
import org.geogit.api.porcelain.MergeOp.MergeReport;
import org.geogit.web.api.AbstractWebAPICommand;
import org.geogit.web.api.CommandContext;
import org.geogit.web.api.CommandResponse;
import org.geogit.web.api.CommandSpecException;
import org.geogit.web.api.ResponseWriter;
import com.google.common.base.Optional;
import com.google.common.base.Suppliers;
/**
* Interface for the Merge operation in GeoGit.
*
* Web interface for {@link MergeOp}
*/
public class MergeWebOp extends AbstractWebAPICommand {
private boolean noCommit;
private String commit;
private Optional<String> authorName = Optional.absent();
private Optional<String> authorEmail = Optional.absent();
/**
* Mutator for the noCommit variable
*
* @param noCommit - true to merge without creating a commit afterwards
*/
public void setNoCommit(boolean noCommit) {
this.noCommit = noCommit;
}
/**
* Mutator for the commit variable
*
* @param commit - the commit to merge into the baseRef or the currently checked out ref
*/
public void setCommit(String commit) {
this.commit = commit;
}
/**
* @param authorName the author of the merge commit
*/
public void setAuthorName(@Nullable String authorName) {
this.authorName = Optional.fromNullable(authorName);
}
/**
* @param authorEmail the email of the author of the merge commit
*/
public void setAuthorEmail(@Nullable String authorEmail) {
this.authorEmail = Optional.fromNullable(authorEmail);
}
/**
* Runs the command and builds the appropriate response.
*
* @param context - the context to use for this command
*
* @throws CommandSpecException
*/
@Override
public void run(CommandContext context) {
if (this.getTransactionId() == null) {
throw new CommandSpecException(
"No transaction was specified, merge requires a transaction to preserve the stability of the repository.");
} else if (this.commit == null) {
throw new CommandSpecException("No commits were specified for merging.");
}
final GeogitTransaction transaction = (GeogitTransaction) this.getCommandLocator(context);
final Optional<Ref> currHead = transaction.command(RefParse.class).setName(Ref.HEAD).call();
if (!currHead.isPresent()) {
throw new CommandSpecException("Repository has no HEAD, can't merge.");
}
MergeOp merge = transaction.command(MergeOp.class);
merge.setAuthor(authorName.orNull(), authorEmail.orNull());
final Optional<ObjectId> oid = transaction.command(RevParse.class).setRefSpec(commit)
.call();
if (oid.isPresent()) {
merge.addCommit(Suppliers.ofInstance(oid.get()));
} else {
throw new CommandSpecException("Couldn't resolve '" + commit + "' to a commit.");
}
try {
final MergeReport report = merge.setNoCommit(noCommit).call();
context.setResponseContent(new CommandResponse() {
@Override
public void write(ResponseWriter out) throws Exception {
out.start();
out.writeMergeResponse(report.getReport().get(), transaction, report.getOurs(),
report.getPairs().get(0).getTheirs(), report.getPairs().get(0)
.getAncestor());
out.finish();
}
});
} catch (Exception e) {
final RevCommit ours = context.getGeoGIT().getRepository()
.getCommit(currHead.get().getObjectId());
final RevCommit theirs = context.getGeoGIT().getRepository().getCommit(oid.get());
final Optional<RevCommit> ancestor = transaction.command(FindCommonAncestor.class)
.setLeft(ours).setRight(theirs).call();
context.setResponseContent(new CommandResponse() {
final MergeScenarioReport report = transaction.command(ReportMergeScenarioOp.class)
.setMergeIntoCommit(ours).setToMergeCommit(theirs).call();
@Override
public void write(ResponseWriter out) throws Exception {
out.start();
out.writeMergeResponse(report, transaction, ours.getId(), theirs.getId(),
ancestor.get().getId());
out.finish();
}
});
}
}
}
|
package com.appleframework.pay.trade.utils.apple;
import java.io.Serializable;
import java.util.List;
public class AppleReceiptBean implements Serializable {
private static final long serialVersionUID = -3566773423244003397L;
private String receipt_type;
private Long adam_id;
private Integer app_item_id;
private String bundle_id;
private String application_version;
private Long download_id;
private Long version_external_identifier;
private String receipt_creation_date;
private String receipt_creation_date_ms;
private String receipt_creation_date_pst;
private String request_date;
private String request_date_ms;
private String request_date_pst;
private String original_purchase_date;
private String original_purchase_date_ms;
private String original_purchase_date_pst;
private String original_application_version;
private List<AppleInAppBean> in_app;
public String getReceipt_type() {
return receipt_type;
}
public void setReceipt_type(String receipt_type) {
this.receipt_type = receipt_type;
}
public Long getAdam_id() {
return adam_id;
}
public void setAdam_id(Long adam_id) {
this.adam_id = adam_id;
}
public Integer getApp_item_id() {
return app_item_id;
}
public void setApp_item_id(Integer app_item_id) {
this.app_item_id = app_item_id;
}
public String getBundle_id() {
return bundle_id;
}
public void setBundle_id(String bundle_id) {
this.bundle_id = bundle_id;
}
public String getApplication_version() {
return application_version;
}
public void setApplication_version(String application_version) {
this.application_version = application_version;
}
public Long getDownload_id() {
return download_id;
}
public void setDownload_id(Long download_id) {
this.download_id = download_id;
}
public Long getVersion_external_identifier() {
return version_external_identifier;
}
public void setVersion_external_identifier(Long version_external_identifier) {
this.version_external_identifier = version_external_identifier;
}
public String getReceipt_creation_date() {
return receipt_creation_date;
}
public void setReceipt_creation_date(String receipt_creation_date) {
this.receipt_creation_date = receipt_creation_date;
}
public String getReceipt_creation_date_ms() {
return receipt_creation_date_ms;
}
public void setReceipt_creation_date_ms(String receipt_creation_date_ms) {
this.receipt_creation_date_ms = receipt_creation_date_ms;
}
public String getReceipt_creation_date_pst() {
return receipt_creation_date_pst;
}
public void setReceipt_creation_date_pst(String receipt_creation_date_pst) {
this.receipt_creation_date_pst = receipt_creation_date_pst;
}
public String getRequest_date() {
return request_date;
}
public void setRequest_date(String request_date) {
this.request_date = request_date;
}
public String getRequest_date_ms() {
return request_date_ms;
}
public void setRequest_date_ms(String request_date_ms) {
this.request_date_ms = request_date_ms;
}
public String getRequest_date_pst() {
return request_date_pst;
}
public void setRequest_date_pst(String request_date_pst) {
this.request_date_pst = request_date_pst;
}
public String getOriginal_purchase_date() {
return original_purchase_date;
}
public void setOriginal_purchase_date(String original_purchase_date) {
this.original_purchase_date = original_purchase_date;
}
public String getOriginal_purchase_date_ms() {
return original_purchase_date_ms;
}
public void setOriginal_purchase_date_ms(String original_purchase_date_ms) {
this.original_purchase_date_ms = original_purchase_date_ms;
}
public String getOriginal_purchase_date_pst() {
return original_purchase_date_pst;
}
public void setOriginal_purchase_date_pst(String original_purchase_date_pst) {
this.original_purchase_date_pst = original_purchase_date_pst;
}
public String getOriginal_application_version() {
return original_application_version;
}
public void setOriginal_application_version(String original_application_version) {
this.original_application_version = original_application_version;
}
public List<AppleInAppBean> getIn_app() {
return in_app;
}
public void setIn_app(List<AppleInAppBean> in_app) {
this.in_app = in_app;
}
}
|
/*
* 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.computeoptimizer.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes a filter that returns a more specific list of Amazon Elastic Block Store (Amazon EBS) volume
* recommendations. Use this filter with the <a>GetEBSVolumeRecommendations</a> action.
* </p>
* <p>
* You can use <code>LambdaFunctionRecommendationFilter</code> with the <a>GetLambdaFunctionRecommendations</a> action,
* <code>JobFilter</code> with the <a>DescribeRecommendationExportJobs</a> action, and <code>Filter</code> with the
* <a>GetAutoScalingGroupRecommendations</a> and <a>GetEC2InstanceRecommendations</a> actions.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/compute-optimizer-2019-11-01/EBSFilter" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EBSFilter implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the filter.
* </p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for example,
* <code>NotOptimized</code>).
* </p>
*/
private String name;
/**
* <p>
* The value of the filter.
* </p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
* </p>
*/
private java.util.List<String> values;
/**
* <p>
* The name of the filter.
* </p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for example,
* <code>NotOptimized</code>).
* </p>
*
* @param name
* The name of the filter.</p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for
* example, <code>NotOptimized</code>).
* @see EBSFilterName
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the filter.
* </p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for example,
* <code>NotOptimized</code>).
* </p>
*
* @return The name of the filter.</p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for
* example, <code>NotOptimized</code>).
* @see EBSFilterName
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the filter.
* </p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for example,
* <code>NotOptimized</code>).
* </p>
*
* @param name
* The name of the filter.</p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for
* example, <code>NotOptimized</code>).
* @return Returns a reference to this object so that method calls can be chained together.
* @see EBSFilterName
*/
public EBSFilter withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The name of the filter.
* </p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for example,
* <code>NotOptimized</code>).
* </p>
*
* @param name
* The name of the filter.</p>
* <p>
* Specify <code>Finding</code> to return recommendations with a specific finding classification (for
* example, <code>NotOptimized</code>).
* @return Returns a reference to this object so that method calls can be chained together.
* @see EBSFilterName
*/
public EBSFilter withName(EBSFilterName name) {
this.name = name.toString();
return this;
}
/**
* <p>
* The value of the filter.
* </p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
* </p>
*
* @return The value of the filter.</p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
*/
public java.util.List<String> getValues() {
return values;
}
/**
* <p>
* The value of the filter.
* </p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
* </p>
*
* @param values
* The value of the filter.</p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
*/
public void setValues(java.util.Collection<String> values) {
if (values == null) {
this.values = null;
return;
}
this.values = new java.util.ArrayList<String>(values);
}
/**
* <p>
* The value of the filter.
* </p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setValues(java.util.Collection)} or {@link #withValues(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param values
* The value of the filter.</p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public EBSFilter withValues(String... values) {
if (this.values == null) {
setValues(new java.util.ArrayList<String>(values.length));
}
for (String ele : values) {
this.values.add(ele);
}
return this;
}
/**
* <p>
* The value of the filter.
* </p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
* </p>
*
* @param values
* The value of the filter.</p>
* <p>
* The valid values are <code>Optimized</code>, or <code>NotOptimized</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public EBSFilter withValues(java.util.Collection<String> values) {
setValues(values);
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 (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getValues() != null)
sb.append("Values: ").append(getValues());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof EBSFilter == false)
return false;
EBSFilter other = (EBSFilter) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getValues() == null ^ this.getValues() == null)
return false;
if (other.getValues() != null && other.getValues().equals(this.getValues()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getValues() == null) ? 0 : getValues().hashCode());
return hashCode;
}
@Override
public EBSFilter clone() {
try {
return (EBSFilter) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.computeoptimizer.model.transform.EBSFilterMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appium.uiautomator2.common.exceptions;
import io.netty.handler.codec.http.HttpResponseStatus;
public class UnknownCommandException extends UiAutomator2Exception {
public UnknownCommandException() {
super("The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource");
}
public UnknownCommandException(String message) {
super(message);
}
@Override
public String getError() {
return "unknown command";
}
@Override
public HttpResponseStatus getHttpStatus() {
return HttpResponseStatus.NOT_FOUND;
}
}
|
/*
* Copyright 2016 Alexander Shitikov
*
* 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 ru.objective.jni.tasks;
import org.apache.commons.cli.CommandLine;
import ru.objective.jni.utils.OJNIClassLoader;
import ru.objective.jni.utils.Utils;
import java.io.IOException;
import java.util.HashSet;
/**
* Created by ashitikov on 28.11.15.
*/
public class TaskManager {
public TaskManager() {
}
public void run(CommandLine cmd) throws Exception {
String[] classPaths = cmd.getOptionValues("classpath");
String[] excludes = cmd.getOptionValues("exclude");
String[] excludesPackages = cmd.getOptionValues("excludepackage");
String[] classes = cmd.getOptionValues("class");
String[] packages = cmd.getOptionValues("package");
String output = cmd.getOptionValue("output", ".");
String prefix = cmd.getOptionValue("prefix", "");
ITask task = null;
if (cmd.getOptions().length == 0 || cmd.hasOption("help")) {
task = new HelpTask();
} else if (cmd.hasOption("version")) {
task = new VersionTask();
} else {
OJNIClassLoader.getInstance().setClassPaths(Utils.classPathsFromStrings(classPaths));
task = new DefaultTask(classPaths, excludes, excludesPackages, classes, packages, output, prefix);
}
task.run();
}
}
|
package com.codedrinker.controller;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Created by codedrinker on 05/05/2018.
*/
public class LuckyMoneyCache {
private static final Logger logger = LoggerFactory.getLogger(LuckyMoneyCache.class);
private static LoadingCache<String, Optional<Map<String, Integer>>> loadingCache;
static {
loadingCache = CacheBuilder
.newBuilder()
.expireAfterWrite(3, TimeUnit.DAYS)
.removalListener((RemovalListener<String, Optional<Map<String, Integer>>>) listener -> {
if (listener.getValue().isPresent()) {
Map<String, Integer> stringIntegerMap = listener.getValue().get();
if (stringIntegerMap.containsKey(listener.getKey())) {
logger.info("key -> {} is expired at count -> {}", listener.getKey(), stringIntegerMap.get(listener.getKey()));
}
}
})
.build(new CacheLoader<String, Optional<Map<String, Integer>>>() {
@Override
public Optional<Map<String, Integer>> load(String key) throws Exception {
HashMap<String, Integer> reference = new HashMap<>();
reference.put(key, 0);
return Optional.fromNullable(reference);
}
});
}
public Integer count(String url) {
try {
if (loadingCache.get(url).isPresent()) {
return loadingCache.get(url).get().get(url);
}
} catch (ExecutionException e) {
e.printStackTrace();
}
return 0;
}
public void incCount(String url) {
try {
if (loadingCache.get(url).isPresent()) {
Map<String, Integer> map = loadingCache.get(url).get();
if (map.containsKey(url)) {
map.put(url, map.get(url) + 1);
} else {
map.put(url, 1);
}
}
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public Map<String, Integer> getCurrentCache() {
ConcurrentMap<String, Optional<Map<String, Integer>>> caches = loadingCache.asMap();
Set<String> keys = caches.keySet();
Map<String, Integer> map = new HashMap();
for (String key : keys) {
Optional<Map<String, Integer>> mapOptional = caches.get(key);
if (mapOptional.isPresent()) {
Map<String, Integer> stringIntegerMap = mapOptional.get();
if (stringIntegerMap.containsKey(key)) {
map.put(key, stringIntegerMap.get(key));
}
}
}
return map;
}
public static void main(String[] args) {
String url = "http://www.baidu.com";
LuckyMoneyCache luckyMoneyCache = new LuckyMoneyCache();
System.out.println(luckyMoneyCache.count(url));
luckyMoneyCache.incCount(url);
System.out.println(luckyMoneyCache.count(url));
luckyMoneyCache.incCount(url);
System.out.println(luckyMoneyCache.count(url));
luckyMoneyCache.incCount(url);
System.out.println(luckyMoneyCache.count(url));
System.out.println(luckyMoneyCache.getCurrentCache());
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
luckyMoneyCache.incCount(url);
System.out.println(luckyMoneyCache.count(url));
luckyMoneyCache.incCount(url);
System.out.println(luckyMoneyCache.count(url));
System.out.println(luckyMoneyCache.getCurrentCache());
}
}
|
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2022 iText Group NV
Authors: iText Software.
This program is offered under a commercial and under the AGPL license.
For commercial licensing, contact us at https://itextpdf.com/sales. For AGPL licensing, see below.
AGPL licensing:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.itextpdf.html2pdf.css.w3c.css_backgrounds.reference;
import com.itextpdf.html2pdf.css.w3c.W3CCssTest;
public class BoxShadowInsetSpreadWithoutBRTest extends W3CCssTest {
@Override
protected String getHtmlFileName() {
return "box-shadow-inset-spread-without-border-radius.html";
}
}
|
package com.xiao.learn.service.zuul;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
/**
* Created by guoxiaoxiao on 2019/6/6.
* Desc:
*/
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceZuulApplication {
public static void main(String[] args) {
SpringApplication.run( ServiceZuulApplication.class, args );
}
}
|
public class PlanetTester
{
public static void main(String[] args)
{
Planet mercury = new Planet("Mercury");
Planet venus = new Planet("Venus");
Planet earth = new Planet("Earth");
Planet mars = new Planet("Mars");
Planet jupiter = new Planet("Jupiter");
Planet saturn = new Planet("Saturn");
Planet uranus = new Planet("Uranus");
Planet neptune = new Planet("Neptune");
Planet pluto = new Planet("Pluto");
Planet[] solarSystemPlanets = new Planet[9];
solarSystemPlanets[0] = mercury;
solarSystemPlanets[1] = venus;
solarSystemPlanets[2] = earth;
solarSystemPlanets[3] = mars;
solarSystemPlanets[4] = jupiter;
solarSystemPlanets[5] = saturn;
solarSystemPlanets[6] = uranus;
solarSystemPlanets[7] = neptune;
solarSystemPlanets[8] = pluto;
printPlanet(solarSystemPlanets);
}
private static void printPlanet(Planet[] Planet)
{
for (Planet planet : Planet)
{
System.out.println(planet.getName());
}
}
}
|
/*
* Copyright 2018 - 2020 Valtech GmbH
*
* 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 de.valtech.aecu.core.groovy.console.bindings.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.jcr.query.Query;
import javax.servlet.http.HttpServletResponse;
import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.icfolson.aem.groovy.console.api.ScriptContext;
import de.valtech.aecu.api.groovy.console.bindings.ContentUpgrade;
import de.valtech.aecu.api.groovy.console.bindings.CustomResourceAction;
import de.valtech.aecu.api.groovy.console.bindings.filters.ANDFilter;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterBy;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterByHasProperty;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterByMultiValuePropContains;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterByNodeName;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterByNodeNameRegex;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterByPathRegex;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterByProperties;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterByProperty;
import de.valtech.aecu.api.groovy.console.bindings.filters.FilterByPropertyRegex;
import de.valtech.aecu.api.service.AecuException;
import de.valtech.aecu.core.groovy.console.bindings.actions.Action;
import de.valtech.aecu.core.groovy.console.bindings.actions.multivalue.AddMultiValues;
import de.valtech.aecu.core.groovy.console.bindings.actions.multivalue.RemoveMultiValues;
import de.valtech.aecu.core.groovy.console.bindings.actions.multivalue.ReplaceMultiValues;
import de.valtech.aecu.core.groovy.console.bindings.actions.page.AddPageTagsAction;
import de.valtech.aecu.core.groovy.console.bindings.actions.page.DeletePageAction;
import de.valtech.aecu.core.groovy.console.bindings.actions.page.RemovePageTagsAction;
import de.valtech.aecu.core.groovy.console.bindings.actions.page.RenderPageAction;
import de.valtech.aecu.core.groovy.console.bindings.actions.page.ReplicatePageAction;
import de.valtech.aecu.core.groovy.console.bindings.actions.page.SetPageTagsAction;
import de.valtech.aecu.core.groovy.console.bindings.actions.page.TreeActivatePageAction;
import de.valtech.aecu.core.groovy.console.bindings.actions.print.PrintJson;
import de.valtech.aecu.core.groovy.console.bindings.actions.print.PrintPath;
import de.valtech.aecu.core.groovy.console.bindings.actions.print.PrintProperty;
import de.valtech.aecu.core.groovy.console.bindings.actions.properties.CopyPropertyToRelativePath;
import de.valtech.aecu.core.groovy.console.bindings.actions.properties.DeleteProperty;
import de.valtech.aecu.core.groovy.console.bindings.actions.properties.MovePropertyToRelativePath;
import de.valtech.aecu.core.groovy.console.bindings.actions.properties.RenameProperty;
import de.valtech.aecu.core.groovy.console.bindings.actions.properties.SetProperty;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.CopyResourceToRelativePath;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.CreateResource;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.CustomAction;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.DeleteResource;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.MoveResourceToPathRegex;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.MoveResourceToRelativePath;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.RenameResource;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.ReplaceResourcePropertyValues;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.ReplaceResourcePropertyValuesRegex;
import de.valtech.aecu.core.groovy.console.bindings.actions.resource.ReplicateResourceAction;
import de.valtech.aecu.core.groovy.console.bindings.traversers.ForChildResourcesOf;
import de.valtech.aecu.core.groovy.console.bindings.traversers.ForDescendantResourcesOf;
import de.valtech.aecu.core.groovy.console.bindings.traversers.ForQuery;
import de.valtech.aecu.core.groovy.console.bindings.traversers.ForResources;
import de.valtech.aecu.core.groovy.console.bindings.traversers.TraversData;
/**
* Implements the content upgrade API.
*
* @author Roxana Muresan
* @author Roland Gruber
*/
public class ContentUpgradeImpl implements ContentUpgrade {
private static final Logger LOG = LoggerFactory.getLogger(ContentUpgrade.class);
private BindingContext context = null;
private ScriptContext scriptContext;
private List<TraversData> traversals = new ArrayList<>();
private FilterBy filter = null;
private List<Action> actions = new ArrayList<>();
/**
* Constructor
*
* @param resourceResolver resolver
* @param scriptContext Groovy context
*/
public ContentUpgradeImpl(@Nonnull ResourceResolver resourceResolver, ScriptContext scriptContext) {
this.context = new BindingContext(resourceResolver);
this.scriptContext = scriptContext;
}
@Override
public ContentUpgrade forResources(@Nonnull String[] paths) {
traversals.add(new ForResources(paths));
return this;
}
@Override
public ContentUpgrade forChildResourcesOf(@Nonnull String path) {
traversals.add(new ForChildResourcesOf(path));
return this;
}
@Override
public ContentUpgrade forDescendantResourcesOf(@Nonnull String path) {
traversals.add(new ForDescendantResourcesOf(path, false));
return this;
}
@Override
public ContentUpgrade forResourcesInSubtree(@Nonnull String path) {
traversals.add(new ForDescendantResourcesOf(path, true));
return this;
}
@Override
public ContentUpgrade forResourcesBySql2Query(String query) {
traversals.add(new ForQuery(query, Query.JCR_SQL2));
return this;
}
@Override
public ContentUpgrade filterByProperties(@Nonnull Map<String, Object> conditionProperties) {
addFilter(new FilterByProperties(conditionProperties));
return this;
}
@Override
public ContentUpgrade filterByProperty(@Nonnull String name, Object value) {
addFilter(new FilterByProperty(name, value));
return this;
}
@Override
public ContentUpgrade filterByPropertyRegex(String name, String regex) {
addFilter(new FilterByPropertyRegex(name, regex));
return this;
}
@Override
public ContentUpgrade filterByAnyPropertyRegex(String regex) {
addFilter(new FilterByPropertyRegex(null, regex));
return this;
}
@Override
public ContentUpgrade filterByHasProperty(@Nonnull String name) {
addFilter(new FilterByHasProperty(name));
return this;
}
@Override
public ContentUpgrade filterByMultiValuePropContains(@Nonnull String name, @Nonnull Object[] conditionValues) {
addFilter(new FilterByMultiValuePropContains(name, conditionValues));
return this;
}
@Override
public ContentUpgrade filterByNodeName(@Nonnull String nodeName) {
addFilter(new FilterByNodeName(nodeName));
return this;
}
@Override
public ContentUpgrade filterByNodeNameRegex(@Nonnull String regex) {
addFilter(new FilterByNodeNameRegex(regex));
return this;
}
@Override
public ContentUpgrade filterByPathRegex(@Nonnull String regex) {
addFilter(new FilterByPathRegex(regex));
return this;
}
@Override
public ContentUpgrade filterWith(@Nonnull FilterBy filter) {
addFilter(filter);
return this;
}
/**
* Adds another filter. If there is already a filter then an AND filter will be created.
*
* @param filter filter
*/
private void addFilter(@Nonnull FilterBy filter) {
if (this.filter == null) {
this.filter = filter;
return;
}
if (this.filter instanceof ANDFilter) {
((ANDFilter) this.filter).addFilter(filter);
}
ANDFilter newFilter = new ANDFilter(Arrays.asList(this.filter, filter));
this.filter = newFilter;
}
@Override
public ContentUpgrade doSetProperty(@Nonnull String name, Object value) {
actions.add(new SetProperty(name, value));
return this;
}
@Override
public ContentUpgrade doDeleteProperty(@Nonnull String name) {
actions.add(new DeleteProperty(name));
return this;
}
@Override
public ContentUpgrade doRenameProperty(@Nonnull String oldName, @Nonnull String newName) {
actions.add(new RenameProperty(oldName, newName));
return this;
}
@Override
public ContentUpgrade doCopyPropertyToRelativePath(@Nonnull String name, String newName,
@Nonnull String relativeResourcePath) {
actions.add(new CopyPropertyToRelativePath(name, newName, context.getResolver(), relativeResourcePath));
return this;
}
@Override
public ContentUpgrade doMovePropertyToRelativePath(@Nonnull String name, String newName,
@Nonnull String relativeResourcePath) {
actions.add(new MovePropertyToRelativePath(name, newName, context.getResolver(), relativeResourcePath));
return this;
}
@Override
public ContentUpgrade doAddValuesToMultiValueProperty(@Nonnull String name, @Nonnull String[] values) {
actions.add(new AddMultiValues(name, values));
return this;
}
@Override
public ContentUpgrade doRemoveValuesOfMultiValueProperty(@Nonnull String name, @Nonnull String[] values) {
actions.add(new RemoveMultiValues(name, values));
return this;
}
@Override
public ContentUpgrade doReplaceValuesOfMultiValueProperty(@Nonnull String name, @Nonnull String[] oldValues,
@Nonnull String[] newValues) {
actions.add(new ReplaceMultiValues(name, oldValues, newValues));
return this;
}
@Override
public ContentUpgrade doReplaceValueInAllProperties(String oldValue, String newValue) {
actions.add(new ReplaceResourcePropertyValues(oldValue, newValue, Collections.emptyList()));
return this;
}
@Override
public ContentUpgrade doReplaceValueInProperties(String oldValue, String newValue, String[] propertyNames) {
actions.add(new ReplaceResourcePropertyValues(oldValue, newValue, Arrays.asList(propertyNames)));
return this;
}
@Override
public ContentUpgrade doReplaceValueInAllPropertiesRegex(String searchRegex, String replacement) {
actions.add(new ReplaceResourcePropertyValuesRegex(searchRegex, replacement, Collections.emptyList()));
return this;
}
@Override
public ContentUpgrade doReplaceValueInPropertiesRegex(String searchRegex, String replacement, String[] propertyNames) {
actions.add(new ReplaceResourcePropertyValuesRegex(searchRegex, replacement, Arrays.asList(propertyNames)));
return this;
}
@Override
public ContentUpgrade doRename(String newName) {
actions.add(new RenameResource(context.getResolver(), newName));
return this;
}
@Override
public ContentUpgrade doCopyResourceToRelativePath(@Nonnull String relativePath) {
actions.add(new CopyResourceToRelativePath(relativePath, context.getResolver()));
return this;
}
@Override
public ContentUpgrade doMoveResourceToRelativePath(@Nonnull String relativePath) {
actions.add(new MoveResourceToRelativePath(relativePath, context));
return this;
}
@Override
public ContentUpgrade doMoveResourceToPathRegex(@Nonnull String matchPattern, @Nonnull String targetPathExpr) {
actions.add(new MoveResourceToPathRegex(matchPattern, targetPathExpr, context));
return this;
}
@Override
public ContentUpgrade doDeleteResource(String... children) {
actions.add(new DeleteResource(context.getResolver(), children));
return this;
}
@Override
public ContentUpgrade doCreateResource(String name, String primaryType) {
Map<String, Object> propertyMap = new HashMap<>();
propertyMap.put(JcrConstants.JCR_PRIMARYTYPE, primaryType);
actions.add(new CreateResource(name, propertyMap, null, context.getResolver()));
return this;
}
@Override
public ContentUpgrade doCreateResource(String name, String primaryType, Map<String, Object> properties) {
Map<String, Object> propertyMap = (properties == null) ? new HashMap<>() : properties;
propertyMap.put(JcrConstants.JCR_PRIMARYTYPE, primaryType);
actions.add(new CreateResource(name, propertyMap, null, context.getResolver()));
return this;
}
@Override
public ContentUpgrade doCreateResource(String name, String primaryType, String relativePath) {
Map<String, Object> propertyMap = new HashMap<>();
propertyMap.put(JcrConstants.JCR_PRIMARYTYPE, primaryType);
actions.add(new CreateResource(name, propertyMap, relativePath, context.getResolver()));
return this;
}
@Override
public ContentUpgrade doCreateResource(String name, String primaryType, Map<String, Object> properties, String relativePath) {
Map<String, Object> propertyMap = (properties == null) ? new HashMap<>() : properties;
propertyMap.put(JcrConstants.JCR_PRIMARYTYPE, primaryType);
actions.add(new CreateResource(name, propertyMap, relativePath, context.getResolver()));
return this;
}
@Override
public ContentUpgrade doActivateResource() {
actions.add(new ReplicateResourceAction(true, context));
return this;
}
@Override
public ContentUpgrade doDeactivateResource() {
actions.add(new ReplicateResourceAction(false, context));
return this;
}
@Override
public ContentUpgrade doCustomResourceBasedAction(CustomResourceAction action) {
actions.add(new CustomAction(action));
return this;
}
@Override
public ContentUpgrade doActivateContainingPage() {
actions.add(new ReplicatePageAction(true, context));
return this;
}
@Override
public ContentUpgrade doTreeActivateContainingPage() {
actions.add(new TreeActivatePageAction(false, context));
return this;
}
@Override
public ContentUpgrade doTreeActivateContainingPage(boolean skipDeactivated) {
actions.add(new TreeActivatePageAction(skipDeactivated, context));
return this;
}
@Override
public ContentUpgrade doDeactivateContainingPage() {
actions.add(new ReplicatePageAction(false, context));
return this;
}
@Override
public ContentUpgrade doDeleteContainingPage() {
actions.add(new DeletePageAction(context));
return this;
}
@Override
public ContentUpgrade doAddTagsToContainingPage(String... tags) {
actions.add(new AddPageTagsAction(context, tags));
return this;
}
@Override
public ContentUpgrade doSetTagsForContainingPage(String... tags) {
actions.add(new SetPageTagsAction(context, tags));
return this;
}
@Override
public ContentUpgrade doRemoveTagsFromContainingPage(String... tags) {
actions.add(new RemovePageTagsAction(context, tags));
return this;
}
@Override
public ContentUpgrade doCheckPageRendering() {
return doCheckPageRendering(HttpServletResponse.SC_OK);
}
@Override
public ContentUpgrade doCheckPageRendering(int code) {
actions.add(new RenderPageAction(context, code, null, null));
return this;
}
@Override
public ContentUpgrade doCheckPageRendering(String textPresent) {
return doCheckPageRendering(textPresent, null);
}
@Override
public ContentUpgrade doCheckPageRendering(String textPresent, String textNotPresent) {
actions.add(new RenderPageAction(context, HttpServletResponse.SC_OK, textPresent, textNotPresent));
return this;
}
@Override
public ContentUpgrade printPath() {
LOG.debug("printPath");
actions.add(new PrintPath());
return this;
}
@Override
public ContentUpgrade printProperty(@Nonnull String property) {
LOG.debug("printProperty {}", property);
actions.add(new PrintProperty(property));
return this;
}
@Override
public ContentUpgrade printJson() {
LOG.debug("printJson");
actions.add(new PrintJson());
return this;
}
@Override
public void run() throws PersistenceException, AecuException {
LOG.debug("apply content upgrade");
run(false);
}
@Override
public void dryRun() throws PersistenceException, AecuException {
LOG.debug("apply content upgrade dry");
run(true);
}
@Override
public void run(boolean dryRun) throws PersistenceException, AecuException {
context.setDryRun(dryRun);
StringBuilder output = new StringBuilder("Running content upgrade " + (dryRun ? "DRY" : "") + "...\n");
for (TraversData traversal : traversals) {
traversal.traverse(context, filter, actions, output, dryRun);
}
if (!dryRun) {
context.getResolver().commit();
}
output.append("\n\n");
scriptContext.getPrintStream().append(output);
}
}
|
package com.kangning.demo.service.impl;
import com.alibaba.fastjson.JSONArray;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author 加康宁 Date: 2018-08-28 Time: 22:07
* @version $Id$
*/
public abstract class BasePushCService<T> extends Thread {
private volatile static boolean isRunning = false;
private volatile static boolean isStopConsume = false;
private volatile static boolean isStopProduce = false;
private static List<Object> queue = new ArrayList<>();
private static int length = 10000;
public void pushByDelay(List<T> dataList) throws InterruptedException {
if (!isRunning) {
System.out.println("开始执行消费行为");
this.start();
}
synchronized (queue) {
System.out.println("开始——添加——推送消息");
if (queue.size() >= length) {
isStopProduce = true;
queue.wait();
}
isStopProduce = false;
System.out.println("当前生产者线程id : " + Thread.currentThread().getId());
queue.addAll(dataList);
if (isStopConsume) {
queue.notifyAll();
}
}
}
@Override
public void run() {
while (true) {
try {
List<T> list = new ArrayList<>();
synchronized (queue) {
isRunning = true;
System.out.println("开始——消费——推送消息");
if (queue.size() == 0) {
isStopConsume = true;
if (isStopProduce) {
queue.notifyAll();
}
System.out.println("\n======消费完毕====== :" + queue.size());
queue.wait();
}
isStopConsume = false;
int romoveCount = 5 < queue.size() ? 5 : queue.size();
for (int i = 0; i < romoveCount; i++) {
list.add((T) queue.remove(0));
}
}
pushDataList(list);
Thread.sleep(100 * 3);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}
protected void pushDataList(List<T> list) throws IOException, InterruptedException {
System.out.println("当前消费线程id" + Thread.currentThread().getId());
String syncUrl = getSyncUrl();
String body = JSONArray.toJSONString(list);
Thread.sleep(1000 * 3);
dealWithResponse(list);
}
protected abstract String getSyncUrl();
protected abstract void dealWithResponse(List<T> list);
}
|
/*
* Copyright 2002-2018 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.web.reactive.result.method.annotation;
import java.util.Collections;
import java.util.Map;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.ServerErrorException;
import org.springframework.web.server.ServerWebExchange;
/**
* Resolves method arguments annotated with @{@link PathVariable}.
*
* <p>An @{@link PathVariable} is a named value that gets resolved from a URI
* prototype variable. It is always required and does not have a default value
* to fall back on. See the base class
* {@link org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver}
* for more information on how named values are processed.
*
* <p>If the method parameter type is {@link Map}, the name specified in the
* annotation is used to resolve the URI variable String value. The value is
* then converted to a {@link Map} via type conversion, assuming a suitable
* {@link Converter}.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 5.0
* @see PathVariableMapMethodArgumentResolver
*/
public class PathVariableMethodArgumentResolver extends AbstractNamedValueSyncArgumentResolver {
/**
* Create a new {@link PathVariableMethodArgumentResolver}.
* @param factory a bean factory to use for resolving {@code ${...}}
* placeholder and {@code #{...}} SpEL expressions in default values;
* or {@code null} if default values are not expected to contain expressions
* @param registry for checking reactive type wrappers
*/
public PathVariableMethodArgumentResolver(@Nullable ConfigurableBeanFactory factory,
ReactiveAdapterRegistry registry) {
super(factory, registry);
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return checkAnnotatedParamNoReactiveWrapper(parameter, PathVariable.class, this::singlePathVariable);
}
private boolean singlePathVariable(PathVariable pathVariable, Class<?> type) {
return !Map.class.isAssignableFrom(type) || StringUtils.hasText(pathVariable.name());
}
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
PathVariable ann = parameter.getParameterAnnotation(PathVariable.class);
Assert.state(ann != null, "No PathVariable annotation");
return new PathVariableNamedValueInfo(ann);
}
@Override
@SuppressWarnings("unchecked")
protected Object resolveNamedValue(String name, MethodParameter parameter, ServerWebExchange exchange) {
String attributeName = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
return exchange.getAttributeOrDefault(attributeName, Collections.emptyMap()).get(name);
}
@Override
protected void handleMissingValue(String name, MethodParameter parameter) {
throw new ServerErrorException(name, parameter, null);
}
@Override
@SuppressWarnings("unchecked")
protected void handleResolvedValue(
@Nullable Object arg, String name, MethodParameter parameter, Model model, ServerWebExchange exchange) {
// TODO: View.PATH_VARIABLES ?
}
private static class PathVariableNamedValueInfo extends NamedValueInfo {
public PathVariableNamedValueInfo(PathVariable annotation) {
super(annotation.name(), annotation.required(), ValueConstants.DEFAULT_NONE);
}
}
}
|
package com.example.Gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Since;
/**
* Created by ifei on 2017/9/9.
*/
public class VersioningSupportDemos {
static class VersionedClass {
@Since(1.1) private final String newerField;
@Since(1.0) private final String newField;
private final String field;
public VersionedClass() {
this.newerField = "newer";
this.newField = "new";
this.field = "old";
}
}
public static void main(String args[]){
VersionedClass versionedObject = new VersionedClass();
Gson gson = new GsonBuilder().setVersion(1.0).create();
String jsonOutput = gson.toJson(versionedObject);
System.out.println(jsonOutput);
System.out.println();
gson = new Gson();
jsonOutput = gson.toJson(versionedObject);
System.out.println(jsonOutput);
}
}
|
package Object_01.Object_02_Account;
public class Account {
String fullNane ;
long accountNum ;
double blacnce ;
public Account(String fullNane, long accountNum, double blacnce) {
this.fullNane = fullNane;
this.accountNum = accountNum;
this.blacnce = blacnce;
}
public Account(String fullNane, long accountNum) {
this(fullNane, accountNum, 5000.0);
}
public Account() {
super();
}
void open(String fullNane, long accountNum, double blacnce) {
this.fullNane = fullNane;
this.accountNum = accountNum;
this.blacnce = blacnce;
}
void deposit(double deposit) {
if (deposit > 0) {
blacnce += deposit;
System.out.println("存入 " + deposit + "\n");
}else {
System.out.println("輸入錯誤");
}
}
void withdraw(double withdraw) {
if (withdraw > 0 && withdraw <= blacnce) {
blacnce -= withdraw;
}else if (withdraw < 0) {
System.out.println("輸入錯誤");
}else {
System.out.println("超過餘額");
}
}
void showAccount() {
System.out.println("帳戶 " + fullNane);
System.out.println("帳號 " + accountNum);
System.out.println("餘額 " + blacnce);
}
double showBlance() {
return blacnce;
}
}
|
package test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.math.BigInteger;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import monero.common.MoneroConnectionManager;
import monero.common.MoneroConnectionManagerListener;
import monero.common.MoneroRpcConnection;
import monero.daemon.MoneroDaemon;
import monero.daemon.MoneroDaemonRpc;
import monero.daemon.model.MoneroNetworkType;
import monero.daemon.model.MoneroTx;
import monero.wallet.MoneroWalletFull;
import monero.wallet.MoneroWalletRpc;
import monero.wallet.model.MoneroOutputWallet;
import monero.wallet.model.MoneroTxConfig;
import monero.wallet.model.MoneroTxWallet;
import monero.wallet.model.MoneroWalletConfig;
import monero.wallet.model.MoneroWalletListener;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import utils.TestUtils;
/**
* Test the sample code for README.md.
*/
public class TestSampleCode {
private static boolean FUNDS_RECEIVED = false;
@BeforeAll
public static void setUpBeforeClass() throws Exception {
// all wallets need to wait for txs to confirm to reliably sync
TestUtils.WALLET_TX_TRACKER.reset();
// pre-create test wallet
MoneroWalletRpc wallet = TestUtils.getWalletRpc();
wallet.close();
// create directory for test wallets if it doesn't exist
File testWalletsDir = new File(TestUtils.TEST_WALLETS_DIR);
if (!testWalletsDir.exists()) testWalletsDir.mkdirs();
}
// Sample code demonstration
@SuppressWarnings("unused")
@Test
public void testSampleCode() throws InterruptedException {
// connect to daemon
MoneroDaemon daemon = new MoneroDaemonRpc("http://localhost:38081", "superuser", "abctesting123");
long height = daemon.getHeight(); // 1523651
BigInteger feeEstimate = daemon.getFeeEstimate(); // 1014313512
List<MoneroTx> txsInPool = daemon.getTxPool(); // get transactions in the pool
// open wallet on monero-wallet-rpc
MoneroWalletRpc walletRpc = new MoneroWalletRpc(TestUtils.WALLET_RPC_URI, TestUtils.WALLET_RPC_USERNAME, TestUtils.WALLET_RPC_PASSWORD); // *** REPLACE WITH CONSTANTS IN README ***
walletRpc.openWallet("test_wallet_1", "supersecretpassword123"); // *** CHANGE README TO "sample_wallet_rpc" ***
String primaryAddress = walletRpc.getPrimaryAddress(); // 555zgduFhmKd2o8rPUz...
BigInteger balance = walletRpc.getBalance(); // 533648366742
List<MoneroTxWallet> txs = walletRpc.getTxs(); // get transactions containing transfers to/from the wallet
// create wallet from mnemonic phrase using JNI bindings to monero-project
MoneroWalletFull walletFull = MoneroWalletFull.createWallet(new MoneroWalletConfig()
.setPath("./test_wallets/" + UUID.randomUUID().toString()) // *** CHANGE README TO "sample_wallet_full" ***
.setPassword("supersecretpassword123")
.setNetworkType(MoneroNetworkType.STAGENET)
.setServerUri("http://localhost:38081")
.setServerUsername("superuser")
.setServerPassword("abctesting123")
.setMnemonic(TestUtils.MNEMONIC) // *** REPLACE WITH MNEMONIC IN README ***
.setRestoreHeight(TestUtils.FIRST_RECEIVE_HEIGHT)); // *** REPLACE WITH FIRST RECEIVE HEIGHT IN README ***
// synchronize the wallet and receive progress notifications
walletFull.sync(new MoneroWalletListener() {
@Override
public void onSyncProgress(long height, long startHeight, long endHeight, double percentDone, String message) {
// feed a progress bar?
}
});
// synchronize in the background every 5 seconds
walletFull.startSyncing(5000l);
// receive notifications when funds are received, confirmed, and unlocked
walletFull.addListener(new MoneroWalletListener() {
@Override
public void onOutputReceived(MoneroOutputWallet output) {
BigInteger amount = output.getAmount();
String txHash = output.getTx().getHash();
Boolean isConfirmed = output.getTx().isConfirmed();
Boolean isLocked = output.getTx().isLocked();
FUNDS_RECEIVED = true;
}
});
// send funds from RPC wallet to full wallet
TestUtils.WALLET_TX_TRACKER.waitForWalletTxsToClearPool(walletRpc); // *** REMOVE FROM README SAMPLE ***
TestUtils.WALLET_TX_TRACKER.waitForUnlockedBalance(walletRpc, 0, null, new BigInteger("250000000000")); // *** REMOVE FROM README SAMPLE ***
MoneroTxWallet createdTx = walletRpc.createTx(new MoneroTxConfig()
.setAccountIndex(0)
.setAddress(walletFull.getAddress(1, 0))
.setAmount("250000000000") // send 0.25 XMR (denominated in atomic units)
.setRelay(false)); // create transaction and relay to the network if true
BigInteger fee = createdTx.getFee(); // "Are you sure you want to send... ?"
walletRpc.relayTx(createdTx); // relay the transaction
// recipient receives unconfirmed funds within 5 seconds
TimeUnit.SECONDS.sleep(5);
assertTrue(FUNDS_RECEIVED);
// save and close full wallet
walletFull.close(true);
}
// Connection manager demonstration
@SuppressWarnings("unused")
@Test
public void testConnectionManagerDemo() {
// create connection manager
MoneroConnectionManager connectionManager = new MoneroConnectionManager();
// add managed connections with priorities
connectionManager.addConnection(new MoneroRpcConnection("http://localhost:38081").setPriority(1)); // use localhost as first priority
connectionManager.addConnection(new MoneroRpcConnection("http://example.com")); // default priority is prioritized last
// set current connection
connectionManager.setConnection(new MoneroRpcConnection("http://foo.bar", "admin", "password")); // connection is added if new
// check connection status
connectionManager.checkConnection();
System.out.println("Connection manager is connected: " + connectionManager.isConnected());
System.out.println("Connection is online: " + connectionManager.getConnection().isOnline());
System.out.println("Connection is authenticated: " + connectionManager.getConnection().isAuthenticated());
// receive notifications of any changes to current connection
connectionManager.addListener(new MoneroConnectionManagerListener() {
@Override
public void onConnectionChanged(MoneroRpcConnection connection) {
System.out.println("Connection changed to: " + connection);
}
});
// check connection status every 10 seconds
connectionManager.startCheckingConnection(10000l);
// automatically switch to best available connection if disconnected
connectionManager.setAutoSwitch(true);
// get best available connection in order of priority then response time
MoneroRpcConnection bestConnection = connectionManager.getBestAvailableConnection();
// check status of all connections
connectionManager.checkConnections();
// get connections in order of current connection, online status from last check, priority, and name
List<MoneroRpcConnection> connections = connectionManager.getConnections();
// clear connection manager
connectionManager.clear();
}
}
|
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
/*
*
*
*
*
*
*/
/*
Copyright 2009-2013 Attila Szegedi
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 copyright holder nor the names of
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 COPYRIGHT HOLDER
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 jdk.dynalink.beans;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import jdk.dynalink.beans.GuardedInvocationComponent.ValidationType;
import jdk.dynalink.linker.support.Lookup;
/**
* A linker for java.lang.Class objects. Provides a synthetic property "static" that allows access to static fields and
* methods on the class (respecting property getter/setter conventions). Note that Class objects are not recognized by
* the Dynalink as constructors for the instances of the class, {@link StaticClass} is used for this purpose.
*/
class ClassLinker extends BeanLinker {
ClassLinker() {
super(Class.class);
// Map "classObject.static" to StaticClass.forClass(classObject). Can use EXACT_CLASS since class Class is final.
setPropertyGetter("static", FOR_CLASS, ValidationType.EXACT_CLASS);
}
private static final MethodHandle FOR_CLASS = Lookup.PUBLIC.findStatic(StaticClass.class,
"forClass", MethodType.methodType(StaticClass.class, Class.class));
}
|
<<<<<<< HEAD
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
class WinnerWasCalled extends Exception {
}
class Log {
public static void info() {
System.out.println("");
}
public static void info(String message) {
System.out.println(message);
}
}
class Dice {
private int sides;
public int roll(int sides) {
Random rand = new Random();
int result = rand.nextInt(sides()) + 1;
Log.info("Dice roll: " + result);
return result;
}
public Dice (){}
public Dice (int sides){
System.out.println ("Give the number of sides of dice: ");
Scanner scanner= new Scanner(System.in);
int sides = scanner.nextInt();
return sides;
}
}
class Pawn {
private int position;
private String name;
public Pawn(){};
public Pawn(String name, int position) {
this.position = 0;
this.name = name;
Log.info(this.name + " joined the game.");
}
}
class Board {
private int max_position;
private ArrayList<Pawn> pawns;
private Dice dice;
private Pawn winner;
private int turnsCounter;
public Board(){};
public Board(int max_position) {
System.out.println ("Enter the value of the maximum position: ");
Scanner scanner= new Scanner(System.in);
int max_position = scanner.nextInt();
return max_position;
}
public Board(ArrayList<Pawn> pawns, Dice dice, Pawn winner, int turnsCounter) {
this.pawns = pawns;
this.dice = dice;
this.winner = null;
this.turnsCounter = 0;
}
public void performTurn(int max_position, int position, String name ) throws WinnerWasCalled {
this.turnsCounter++;
Log.info();
Log.info("Turn " + this.turnsCounter);
for (Pawn pawn : this.pawns) {
int rollResult = this.dice.roll();
pawn.position += rollResult;
Log.info(pawn.name + " new position: " + pawn.position);
if (pawn.position >= Board.max_position) {
this.winner = pawn;
throw new WinnerWasCalled();
}
}
}
}
public class Main {
public static void main(String[] args,Dice dice) {
Board board = new Board();
board.dice = new Dice();
int PawnsNumber=9;
int TurnsNumber=2;
try {
while (true) {
} catch (WinnerWasCalled exception) {
Log.info();
Log.info(board.winner.name + " won.");
}
try{
if(TurnsNumber < 2)
{
throw new TurnsNumberError();
}
System.out.println("The number of turns in the game has been set" +TurnsNumber);
}
catch (TurnsNumberError){
System.out.println("An error occured.The number of turns in the game has NOT been set");
}
}
try {
if (PawnsNumber < 3 || PawnsNumber > 10)
throw new PawnsNumberError();
for ( int i=0; i < PawnsNumber; i++)
{
int rand = random.nextInt(names.size());
pawns.add(new Pawn(names.get(rand)));
names.remove(rand);
}
System.out.println("The pawns were added to the game");
}
catch (PawnsError exception)
{
System.out.println("An error occured.The pawns were NOT added to the game");
}
}
}
=======
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
class WinnerWasCalled extends Exception {
}
class Log {
public static void info() {
System.out.println("");
}
public static void info(String message) {
System.out.println(message);
}
}
class Dice {
private int sides;
public int roll(int sides) {
Random rand = new Random();
int result = rand.nextInt(sides()) + 1;
Log.info("Dice roll: " + result);
return result;
}
public Dice (){}
public Dice (int sides){
System.out.println ("Give the number of sides of dice: ");
Scanner scanner= new Scanner(System.in);
int sides = scanner.nextInt();
return sides;
}
}
class Pawn {
private int position;
private String name;
public Pawn(){};
public Pawn(String name, int position) {
this.position = 0;
this.name = name;
Log.info(this.name + " joined the game.");
}
}
class Board {
private int max_position;
private ArrayList<Pawn> pawns;
private Dice dice;
private Pawn winner;
private int turnsCounter;
public Board(){};
public Board(int max_position) {
System.out.println ("Enter the value of the maximum position: ");
Scanner scanner= new Scanner(System.in);
int max_position = scanner.nextInt();
return max_position;
}
public Board(ArrayList<Pawn> pawns, Dice dice, Pawn winner, int turnsCounter) {
this.pawns = pawns;
this.dice = dice;
this.winner = null;
this.turnsCounter = 0;
}
public void performTurn(int max_position, int position, String name ) throws WinnerWasCalled {
this.turnsCounter++;
Log.info();
Log.info("Turn " + this.turnsCounter);
for (Pawn pawn : this.pawns) {
int rollResult = this.dice.roll();
pawn.position += rollResult;
Log.info(pawn.name + " new position: " + pawn.position);
if (pawn.position >= Board.max_position) {
this.winner = pawn;
throw new WinnerWasCalled();
}
}
}
}
public class Main {
public static void main(String[] args,Dice dice) {
Board board = new Board();
board.dice = new Dice();
int PawnsNumber=9;
int TurnsNumber=2;
try {
while (true) {
} catch (WinnerWasCalled exception) {
Log.info();
Log.info(board.winner.name + " won.");
}
try{
if(TurnsNumber < 2)
{
throw new TurnsNumberError();
}
System.out.println("The number of turns in the game has been set" +TurnsNumber);
}
catch (TurnsNumberError){
System.out.println("An error occured.The number of turns in the game has NOT been set");
}
}
try {
if (PawnsNumber < 3 || PawnsNumber > 10)
throw new PawnsNumberError();
for ( int i=0; i < PawnsNumber; i++)
{
int rand = random.nextInt(names.size());
pawns.add(new Pawn(names.get(rand)));
names.remove(rand);
}
System.out.println("The pawns were added to the game");
}
catch (PawnsError exception)
{
System.out.println("An error occured.The pawns were NOT added to the game");
}
}
}
>>>>>>> bc40ed8e6b590238310d37c969c85ea2941485c5
|
package org.broadinstitute.dsm.db;
import lombok.Data;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.broadinstitute.ddp.db.SimpleResult;
import org.broadinstitute.dsm.model.KitRequestSettings;
import org.broadinstitute.dsm.model.KitType;
import org.broadinstitute.dsm.statics.DBConstants;
import org.broadinstitute.dsm.statics.QueryExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static org.broadinstitute.ddp.db.TransactionWrapper.inTransaction;
@Data
public class KitRequestCreateLabel {
private static final Logger logger = LoggerFactory.getLogger(KitRequestCreateLabel.class);
private final String dsmKitId;
private final String dsmKitRequestId;
private final String instanceID;
private final String instanceName;
private final String ddpParticipantId;
private final String addressIdTo;
private final String kitType;
private final String baseURL;
private final String participantCollaboratorId;
private final String collaboratorIdPrefix;
private final boolean hasAuth0Token;
private final KitRequestSettings kitRequestSettings;
private final KitType kitTyp;
private final String billingReference;
private final String participantIndexES;
public KitRequestCreateLabel(@NonNull String dsmKitId, @NonNull String dsmKitRequestId, @NonNull String instanceID,
@NonNull String instanceName, String ddpParticipantId,
String addressIdTo, @NonNull String kitType, String baseURL, String participantCollaboratorId,
String collaboratorIdPrefix, boolean hasAuth0Token, KitRequestSettings kitRequestSettings, KitType kitTyp,
String billingReference, String participantIndexES) {
this.dsmKitId = dsmKitId;
this.dsmKitRequestId = dsmKitRequestId;
this.instanceID = instanceID;
this.instanceName = instanceName;
this.ddpParticipantId = ddpParticipantId;
this.addressIdTo = addressIdTo;
this.kitType = kitType;
this.baseURL = baseURL;
this.participantCollaboratorId = participantCollaboratorId;
this.collaboratorIdPrefix = collaboratorIdPrefix;
this.hasAuth0Token = hasAuth0Token;
this.kitRequestSettings = kitRequestSettings;
this.kitTyp = kitTyp;
this.billingReference = billingReference;
this.participantIndexES = participantIndexES;
}
/**
* Set given kitRequests to need label
*/
public static void updateKitLabelRequested(KitRequestShipping[] kitRequests, @NonNull String userId) {
if (kitRequests.length > 0) {
for (KitRequestShipping kitRequest : kitRequests) {
KitRequestShipping.updateKit(kitRequest.getDsmKitId(), userId);
}
logger.info("Done triggering label creation");
}
}
/**
* Select all sample requests without kit per realm
* optional per kit type
*/
public static void updateKitLabelRequested(String realm, String type, @NonNull String userId) {
List<KitRequestCreateLabel> kitsNoLabel = new ArrayList<>();
SimpleResult results = inTransaction((conn) -> {
SimpleResult dbVals = new SimpleResult();
try (PreparedStatement bspStatement = getPreparedStatement(conn, realm, type)) {
try (ResultSet rs = bspStatement.executeQuery()) {
while (rs.next()) {
kitsNoLabel.add(new KitRequestCreateLabel(rs.getString(DBConstants.DSM_KIT_ID),
rs.getString(DBConstants.DSM_KIT_REQUEST_ID), rs.getString(DBConstants.DDP_INSTANCE_ID),
rs.getString(DBConstants.INSTANCE_NAME), rs.getString(DBConstants.DDP_PARTICIPANT_ID),
rs.getString(DBConstants.EASYPOST_ADDRESS_ID_TO), rs.getString(DBConstants.KIT_TYPE_NAME),
rs.getString(DBConstants.BASE_URL), rs.getString(DBConstants.COLLABORATOR_PARTICIPANT_ID),
rs.getString(DBConstants.COLLABORATOR_ID_PREFIX),
rs.getBoolean(DBConstants.NEEDS_AUTH0_TOKEN), null, null,
rs.getString(DBConstants.BILLING_REFERENCE),
rs.getString(DBConstants.ES_PARTICIPANT_INDEX)
));
}
}
}
catch (SQLException ex) {
dbVals.resultException = ex;
}
return dbVals;
});
if (results.resultException != null) {
throw new RuntimeException("Error looking up the latestKitRequests ", results.resultException);
}
logger.info("Found " + kitsNoLabel.size() + " kit requests which need a label");
if (!kitsNoLabel.isEmpty()) {
for (KitRequestCreateLabel uploadedKit : kitsNoLabel) {
KitRequestShipping.updateKit(uploadedKit.getDsmKitId(), userId);
}
}
logger.info("Done triggering label creation");
}
private static PreparedStatement getPreparedStatement(@NonNull Connection conn, String realm, String type) throws SQLException {
PreparedStatement stmt = null;
String query = KitRequestShipping.SQL_SELECT_KIT_REQUEST.concat(QueryExtension.KIT_NO_LABEL).concat(QueryExtension.KIT_LABEL_NOT_TRIGGERED);
if (StringUtils.isNotBlank(realm) && StringUtils.isNotBlank(type)) {
logger.info("Going to request label for all kits of realm " + realm + " and kit type " + type);
query = query.concat(QueryExtension.BY_REALM_AND_TYPE);
stmt = conn.prepareStatement(query);
stmt.setString(1, realm);
stmt.setString(2, type);
}
else if (StringUtils.isNotBlank(realm)) {
logger.info("Going to request label for all kits of realm " + realm);
query = query.concat(QueryExtension.BY_REALM);
stmt = conn.prepareStatement(query);
stmt.setString(1, realm);
}
else {
logger.info("Going to request label for all kits");
stmt = conn.prepareStatement(query);
}
return stmt;
}
}
|
package com.centerm.fud_demo.dao;
import com.centerm.fud_demo.entity.DownloadRecord;
import com.centerm.fud_demo.entity.FileRecord;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* File相关操作映射
* @author sheva
*/
@Component
public interface FileDao {
/**
* 根据md5查询文件
* @param fileMd5 文件md5值
* @param userId 用户id
* @return 文件信息
*/
FileRecord findFileByFileMd5(String fileMd5, Long userId) ;
/**
* 根据用户id获取上传文件
* @param userId 用户id
* @return 文件列表
*/
List<FileRecord> getFileByUserId(Long userId);
/**
* 上传第一个分片时的文件存储
* @param fileRecord 文件信息
* @return 结果
*/
Boolean saveFileBegin(FileRecord fileRecord);
/**
* 添加文件
* @param fileRecord 文件实体
* @return 文件
*/
Boolean saveFileSmall(FileRecord fileRecord);
/**
* 上传文成后的文件更新
* @param fileRecord 文件信息
* @return 结果
*/
Boolean saveFileEnd(FileRecord fileRecord);
/**
* 根据id获取文件
* @param id 文件id
* @return 文件信息
*/
FileRecord getFileById(Long id);
/**
* 通过文件名称获取文件信息
* @param fileName 文件名称
* @return 文件信息
*/
FileRecord getFileByName(String fileName);
/**
* 获取所有文件
* @return 文件列表
*/
List<FileRecord> getAllFile();
/**
* 添加下载记录
* @param downloadRecord 下载记录消息
* @return 结果
*/
Boolean addDownloadRecord(DownloadRecord downloadRecord);
/**
* 获取用户最热门下载
* @param userId 用户id
* @return fileRecord集合
*/
List<FileRecord> getMostDownloadRecordById(Long userId);
/**
* 获取最热门下载
* @return fileRecord集合
*/
List<FileRecord> getMostDownloadRecord();
/**
* 获取某个用户上传的文件的总下载次数
* @param userId 用户id
* @return 总下载次数
*/
Long getDownloadTimesByUserId(Long userId);
/**
* 获取下载次数
* @return 下载次数
*/
Long getDownloadTimes();
/**
* 获取上传次数
* @return 上传次数
*/
Long getUploadTimes();
/**
* 根据用户id与文件id删除文件
* @param userId 用户id
* @param fileId 文件id
* @return 结果
*/
Boolean deleteFileById(Long userId, Long fileId);
/**
* 根据文件id删除文件(管理员操作)
* @param fileId 文件id
* @return 结果
*/
Boolean deleteFile(Long fileId);
/**
* 根据文件名删除文件
* @param filePath 文件路径
*/
void deleteFileByPath(String filePath);
/**
* 更新文件信息(下载次数)
* @param fileId 文件id
* @return 结果
*/
Boolean updateFile(Long fileId);
/**
* 更新文件记录
* @param fileId 文件id
* @param fileSize 文件大小
* @param fileMd5 文件md5
* @param backupPath 文件备份地址
* @return 结果
*/
Boolean updateFileRecord(Long fileId, String fileSize, String fileMd5, String backupPath);
/**
* 删除下载信息
* @param fileId 文件id
* @return 结果
*/
Boolean deleteDownloadRecord(Long fileId);
/**
* 获取最新上传的前五个文件
* @param userId 用户id
* @return 文件集合
*/
List<FileRecord> getLatestUploaded(Long userId);
/**
* 获取最新下载的前五个文件
* @param userId 用户id
* @return 文件集合
*/
List<FileRecord> getLatestDownloaded(Long userId);
/**
* 搜索文件
* @param contents 关键词
* @param userId 用户id
* @return 文件列表
*/
List<FileRecord> getFileLikeContents(String contents,Long userId);
/**
* 给折线图传送用户上传信息
* @param userId 用户id
* @return 折线图信息
*/
List<Map<String,Object>> getUploadToMorrisJs(Long userId);
/**
* 给折线图传送用户下载信息
* @param userId 用户id
* @return 折线图信息
*/
List<Map<String,Object>> getDownloadToMorrisJs(Long userId);
/**
* 根据用户id搜索上传次数
* @param userId 用户id
* @return 上传次数
*/
Long getUploadTimesByCurrUser(Long userId);
/**
* 通过文件id获取文件名
* @param localUrl 文件url
* @return 文件id
*/
Long getFileIdByUrl(String localUrl);
/**
* 通过文件名称获取文件id
* @param fileName 文件名称
* @return 文件id
*/
Long getFileIdByFileName(String fileName);
/**
* 获取文件备份地址
* @param filePath 文件地址
* @return 文件备份地址
*/
String getFileBackupUrl(String filePath);
/**
* 添加文件记录
* @param fileRecord 文件记录
* @return 结果
*/
Boolean addFileRecord(FileRecord fileRecord);
/**
* 更新文件md5
* @param fileId 文件id
* @param fileMd5 文件md5
* @param backupPath 备份文件地址
* @return 结果
*/
Boolean updateFileMd5(Long fileId, String fileMd5, String backupPath);
/**
* 获取用户上传的文件数目
* @param userId 用户id
* @return 文件数目
*/
Integer getFileNumberById(Long userId);
/**
* 获取热门文件
* @return 文件列表
*/
List<FileRecord> getHotFile();
/**
* 把文件范围修改到public
* @param fileId 文件id
*/
void changeFileScopeToPublic(Long fileId);
/**
* 把文件范围修改到private
* @param fileId 文件id
*/
void changeFileScopeToPrivate(Long fileId);
}
|
package org.csanchez.jenkins.plugins.kubernetes;
public class InvalidDockerImageException extends RuntimeException {
public InvalidDockerImageException(String msg) {
super(msg);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.thespheres.betula.database;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import org.thespheres.betula.TermId;
import org.thespheres.betula.UnitId;
import org.thespheres.betula.document.DocumentId;
import org.thespheres.betula.document.Signee;
import org.thespheres.betula.util.CollectionUtil;
/**
*
* @author boris.heithecker
*/
@XmlRootElement(name = "db-admin-task")
//@XmlType(propOrder = {"path", "files", "messages", "version"})
@XmlAccessorType(XmlAccessType.FIELD)
public class DBAdminTask {
@XmlAttribute(name = "name")
private String name;
@XmlAttribute(name = "version")
private String version;
@XmlElementWrapper(name = "args")
@XmlElement(name = "arg")
private final List<Arg> args = new ArrayList<>();
public DBAdminTask() {
}
public DBAdminTask(final String name) {
this.name = name;
this.version = "1.0";
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public List<Arg> getArgs() {
return args;
}
public <V> V getArg(final String key, final Class<V> type) {
return args.stream()
.filter(a -> a.getKey().equals(key))
.collect(CollectionUtil.singleton())
.map(Arg::getValue)
.filter(type::isInstance)
.map(type::cast)
.orElse(null);
}
public <V> V getArg(final String key, final Class<V> type, V defaultValue) {
return args.stream()
.filter(a -> a.getKey().equals(key))
.collect(CollectionUtil.singleton())
.map(Arg::getValue)
.filter(type::isInstance)
.map(type::cast)
.orElse(defaultValue);
}
public <V, X extends Exception> V getArg(final String key, final Class<V> type, Supplier<? extends X> exception) throws X {
return args.stream()
.filter(a -> a.getKey().equals(key))
.collect(CollectionUtil.singleton())
.map(Arg::getValue)
.filter(type::isInstance)
.map(type::cast)
.orElseThrow(exception);
}
public <V> List<V> getArgs(final String key, final Class<V> type) {
return args.stream()
.filter(a -> a.getKey().equals(key))
.collect(CollectionUtil.singleton())
.map(Arg::getValues)
.map(Arrays::stream)
.orElse(Stream.empty())
.filter(type::isInstance)
.map(type::cast)
.collect(Collectors.toList());
}
public void setArg(final String key, final Object... value) {
final Iterator<Arg> it = args.iterator();
while (it.hasNext()) {
final Arg arg = it.next();
if (arg.getKey().equals(key)) {
it.remove();
}
}
args.add(new Arg(key, value));
}
@XmlAccessorType(XmlAccessType.FIELD)
public static class Arg {
@XmlAttribute(name = "key")
private String key;
//This is necessary to catch all unknown elements during unmarshalling,
//so they will be marshalled again back into the document and don't get lost.
//Loss might otherwise occur if the user unmarshals the document
//with specific modules disabled that would add additional ColumnProperty classes.
@XmlAnyElement
public org.w3c.dom.Element[] otherElements;
// @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlElements(value = {
@XmlElement(name = "string-value", type = String.class),
@XmlElement(name = "boolean-value", type = Boolean.class),
@XmlElement(name = "int-value", type = Integer.class),
@XmlElement(name = "double-value", type = Double.class),
@XmlElement(name = "term-value", type = TermId.class),
@XmlElement(name = "signee-value", type = Signee.class),
@XmlElement(name = "unit-value", type = UnitId.class),
@XmlElement(name = "document-value", type = DocumentId.class)
})
private Object[] value;
public Arg() {
}
Arg(final String key, final Object[] value) {
this.key = key;
this.value = value;
}
String getKey() {
return key;
}
Object getValue() {
return (value != null && value.length == 1) ? value[0] : null;
}
Object[] getValues() {
return value;
}
}
}
|
/*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.execution.jobs;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.IndicesService;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.concurrent.atomic.AtomicInteger;
@NotThreadSafe
public class SharedShardContext {
private static final Logger LOGGER = Loggers.getLogger(SharedShardContext.class);
private final IndicesService indicesService;
private final ShardId shardId;
private final int readerId;
private RefCountSearcher searcher;
private IndexService indexService;
private IndexShard indexShard;
SharedShardContext(IndicesService indicesService, ShardId shardId, int readerId) {
this.indicesService = indicesService;
this.shardId = shardId;
this.readerId = readerId;
}
public Engine.Searcher acquireSearcher() throws IndexNotFoundException {
if (searcher == null) {
searcher = new RefCountSearcher(indexShard().acquireSearcher("shared-shard-context"));
}
searcher.inc();
return searcher;
}
public IndexShard indexShard() {
if (indexShard == null) {
indexShard = indexService().getShard(shardId.id());
}
return indexShard;
}
public IndexService indexService() throws IndexNotFoundException {
if (indexService == null) {
indexService = indicesService.indexServiceSafe(shardId.getIndex());
}
return indexService;
}
public int readerId() {
return readerId;
}
private static class RefCountSearcher extends Engine.Searcher {
private final AtomicInteger refs = new AtomicInteger();
private final Engine.Searcher searcher;
RefCountSearcher(Engine.Searcher searcher) {
super(searcher.source(), searcher.searcher());
this.searcher = searcher;
}
@Override
public String source() {
return searcher.source();
}
@Override
public IndexReader reader() {
return searcher.reader();
}
@Override
public IndexSearcher searcher() {
return searcher.searcher();
}
@Override
public void close() throws ElasticsearchException {
int remainingRefs = refs.decrementAndGet();
traceLog(remainingRefs, "Close called on RefCountSearcher; Remaining refs: {}");
if (remainingRefs == 0) {
searcher.close();
}
}
void inc() {
int newRefs = refs.incrementAndGet();
traceLog(newRefs, "Searcher refs increased: {}");
}
private void traceLog(int remainingRefs, String msg) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(msg, remainingRefs);
}
}
}
}
|
/*
* Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2016 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in
* http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of the Unicode data files and any associated documentation
* (the "Data Files") or Unicode software and any associated documentation
* (the "Software") to deal in the Data Files or Software
* without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, and/or sell copies of
* the Data Files or Software, and to permit persons to whom the Data Files
* or Software are furnished to do so, provided that
* (a) this copyright and permission notice appear with all copies
* of the Data Files or Software,
* (b) this copyright and permission notice appear in associated
* documentation, and
* (c) there is clear notice in each modified Data File or in the Software
* as well as in the documentation associated with the Data File(s) or
* Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE 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 OF THIRD PARTY RIGHTS.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
* NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
* DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale,
* use or other dealings in these Data Files or Software without prior
* written authorization of the copyright holder.
*/
package sun.util.resources.cldr.ext;
import sun.util.resources.OpenListResourceBundle;
public class CurrencyNames_zh extends OpenListResourceBundle {
@Override
protected final Object[][] getContents() {
final Object[][] data = new Object[][] {
{ "ADP", "ADP" },
{ "AED", "AED" },
{ "AFN", "AFN" },
{ "ALK", "ALK" },
{ "ALL", "ALL" },
{ "AMD", "AMD" },
{ "ANG", "ANG" },
{ "AOA", "AOA" },
{ "AOK", "AOK" },
{ "AON", "AON" },
{ "AOR", "AOR" },
{ "ARA", "ARA" },
{ "ARL", "ARL" },
{ "ARM", "ARM" },
{ "ARP", "ARP" },
{ "ARS", "ARS" },
{ "ATS", "ATS" },
{ "AUD", "AU$" },
{ "AWG", "AWG" },
{ "AZM", "AZM" },
{ "AZN", "AZN" },
{ "BAD", "BAD" },
{ "BAM", "BAM" },
{ "BAN", "BAN" },
{ "BBD", "BBD" },
{ "BDT", "BDT" },
{ "BEC", "BEC" },
{ "BEF", "BEF" },
{ "BEL", "BEL" },
{ "BGL", "BGL" },
{ "BGM", "BGM" },
{ "BGN", "BGN" },
{ "BGO", "BGO" },
{ "BHD", "BHD" },
{ "BIF", "BIF" },
{ "BMD", "BMD" },
{ "BND", "BND" },
{ "BOB", "BOB" },
{ "BOL", "BOL" },
{ "BOP", "BOP" },
{ "BOV", "BOV" },
{ "BRB", "BRB" },
{ "BRC", "BRC" },
{ "BRE", "BRE" },
{ "BRN", "BRN" },
{ "BRR", "BRR" },
{ "BRZ", "BRZ" },
{ "BSD", "BSD" },
{ "BTN", "BTN" },
{ "BWP", "BWP" },
{ "BYB", "BYB" },
{ "BYN", "BYN" },
{ "BYR", "BYR" },
{ "BZD", "BZD" },
{ "CDF", "CDF" },
{ "CHE", "CHE" },
{ "CHF", "CHF" },
{ "CHW", "CHW" },
{ "CLE", "CLE" },
{ "CLF", "CLF" },
{ "CLP", "CLP" },
{ "CNH", "CNH" },
{ "CNY", "\uffe5" },
{ "COP", "COP" },
{ "COU", "COU" },
{ "CRC", "CRC" },
{ "CSD", "CSD" },
{ "CSK", "CSK" },
{ "CUC", "CUC" },
{ "CUP", "CUP" },
{ "CVE", "CVE" },
{ "CYP", "CYP" },
{ "CZK", "CZK" },
{ "DDM", "DDM" },
{ "DEM", "DEM" },
{ "DJF", "DJF" },
{ "DKK", "DKK" },
{ "DOP", "DOP" },
{ "DZD", "DZD" },
{ "ECS", "ECS" },
{ "ECV", "ECV" },
{ "EEK", "EEK" },
{ "EGP", "EGP" },
{ "ERN", "ERN" },
{ "ESA", "ESA" },
{ "ESB", "ESB" },
{ "ESP", "ESP" },
{ "ETB", "ETB" },
{ "FIM", "FIM" },
{ "FJD", "FJD" },
{ "FKP", "FKP" },
{ "FRF", "FRF" },
{ "GEK", "GEK" },
{ "GEL", "GEL" },
{ "GHC", "GHC" },
{ "GHS", "GHS" },
{ "GIP", "GIP" },
{ "GMD", "GMD" },
{ "GNF", "GNF" },
{ "GNS", "GNS" },
{ "GQE", "GQE" },
{ "GRD", "GRD" },
{ "GTQ", "GTQ" },
{ "GWE", "GWE" },
{ "GWP", "GWP" },
{ "GYD", "GYD" },
{ "HNL", "HNL" },
{ "HRD", "HRD" },
{ "HRK", "HRK" },
{ "HTG", "HTG" },
{ "HUF", "HUF" },
{ "IDR", "IDR" },
{ "IEP", "IEP" },
{ "ILP", "ILP" },
{ "ILR", "ILS" },
{ "IQD", "IQD" },
{ "IRR", "IRR" },
{ "ISJ", "ISJ" },
{ "ISK", "ISK" },
{ "ITL", "ITL" },
{ "JMD", "JMD" },
{ "JOD", "JOD" },
{ "KES", "KES" },
{ "KGS", "KGS" },
{ "KHR", "KHR" },
{ "KMF", "KMF" },
{ "KPW", "KPW" },
{ "KRW", "\uffe6" },
{ "KWD", "KWD" },
{ "KYD", "KYD" },
{ "KZT", "KZT" },
{ "LAK", "LAK" },
{ "LBP", "LBP" },
{ "LKR", "LKR" },
{ "LRD", "LRD" },
{ "LSL", "LSL" },
{ "LTL", "LTL" },
{ "LTT", "LTT" },
{ "LUC", "LUC" },
{ "LUF", "LUF" },
{ "LUL", "LUL" },
{ "LVL", "LVL" },
{ "LVR", "LVR" },
{ "LYD", "LYD" },
{ "MAD", "MAD" },
{ "MAF", "MAF" },
{ "MCF", "MCF" },
{ "MDC", "MDC" },
{ "MDL", "MDL" },
{ "MGA", "MGA" },
{ "MGF", "MGF" },
{ "MKD", "MKD" },
{ "MKN", "MKN" },
{ "MLF", "MLF" },
{ "MMK", "MMK" },
{ "MNT", "MNT" },
{ "MOP", "MOP" },
{ "MRO", "MRO" },
{ "MTL", "MTL" },
{ "MTP", "MTP" },
{ "MUR", "MUR" },
{ "MVR", "MVR" },
{ "MWK", "MWK" },
{ "MXP", "MXP" },
{ "MXV", "MXV" },
{ "MYR", "MYR" },
{ "MZE", "MZE" },
{ "MZM", "MZM" },
{ "MZN", "MZN" },
{ "NAD", "NAD" },
{ "NGN", "NGN" },
{ "NIC", "NIC" },
{ "NIO", "NIO" },
{ "NLG", "NLG" },
{ "NOK", "NOK" },
{ "NPR", "NPR" },
{ "OMR", "OMR" },
{ "PAB", "PAB" },
{ "PEI", "PEI" },
{ "PEN", "PEN" },
{ "PES", "PES" },
{ "PGK", "PGK" },
{ "PHP", "PHP" },
{ "PKR", "PKR" },
{ "PLN", "PLN" },
{ "PLZ", "PLZ" },
{ "PTE", "PTE" },
{ "PYG", "PYG" },
{ "QAR", "QAR" },
{ "RHD", "RHD" },
{ "ROL", "ROL" },
{ "RON", "RON" },
{ "RSD", "RSD" },
{ "RUB", "RUB" },
{ "RUR", "RUR" },
{ "RWF", "RWF" },
{ "SAR", "SAR" },
{ "SBD", "SBD" },
{ "SCR", "SCR" },
{ "SDD", "SDD" },
{ "SDG", "SDG" },
{ "SDP", "SDP" },
{ "SEK", "SEK" },
{ "SGD", "SGD" },
{ "SHP", "SHP" },
{ "SIT", "SIT" },
{ "SKK", "SKK" },
{ "SLL", "SLL" },
{ "SOS", "SOS" },
{ "SRD", "SRD" },
{ "SRG", "SRG" },
{ "SSP", "SSP" },
{ "STD", "STD" },
{ "SUR", "SUR" },
{ "SVC", "SVC" },
{ "SYP", "SYP" },
{ "SZL", "SZL" },
{ "THB", "THB" },
{ "TJR", "TJR" },
{ "TJS", "TJS" },
{ "TMM", "TMM" },
{ "TMT", "TMT" },
{ "TND", "TND" },
{ "TOP", "TOP" },
{ "TRL", "TRL" },
{ "TRY", "TRY" },
{ "TTD", "TTD" },
{ "TZS", "TZS" },
{ "UAH", "UAH" },
{ "UAK", "UAK" },
{ "UGS", "UGS" },
{ "UGX", "UGX" },
{ "USN", "USN" },
{ "USS", "USS" },
{ "UYI", "UYI" },
{ "UYP", "UYP" },
{ "UYU", "UYU" },
{ "UZS", "UZS" },
{ "VEB", "VEB" },
{ "VEF", "VEF" },
{ "VUV", "VUV" },
{ "WST", "WST" },
{ "XEU", "XEU" },
{ "YDD", "YDD" },
{ "YER", "YER" },
{ "YUD", "YUD" },
{ "YUM", "YUM" },
{ "YUN", "YUN" },
{ "YUR", "YUR" },
{ "ZAL", "ZAL" },
{ "ZAR", "ZAR" },
{ "ZMK", "ZMK" },
{ "ZMW", "ZMW" },
{ "ZRN", "ZRN" },
{ "ZRZ", "ZRZ" },
{ "ZWD", "ZWD" },
{ "ZWL", "ZWL" },
{ "ZWR", "ZWR" },
{ "adp", "\u5b89\u9053\u5c14\u6bd4\u585e\u5854" },
{ "aed", "\u963f\u8054\u914b\u8fea\u62c9\u59c6" },
{ "afa", "\u963f\u5bcc\u6c57\u5c3c (1927\u20132002)" },
{ "afn", "\u963f\u5bcc\u6c57\u5c3c" },
{ "alk", "\u963f\u5c14\u5df4\u5c3c\u4e9a\u5217\u514b(1946\u20131965)" },
{ "all", "\u963f\u5c14\u5df4\u5c3c\u4e9a\u5217\u514b" },
{ "amd", "\u4e9a\u7f8e\u5c3c\u4e9a\u5fb7\u62c9\u59c6" },
{ "ang", "\u8377\u5c5e\u5b89\u7684\u5217\u65af\u76fe" },
{ "aoa", "\u5b89\u54e5\u62c9\u5bbd\u624e" },
{ "aok", "\u5b89\u54e5\u62c9\u5bbd\u624e (1977\u20131990)" },
{ "aon", "\u5b89\u54e5\u62c9\u65b0\u5bbd\u624e (1990\u20132000)" },
{ "aor", "\u5b89\u54e5\u62c9\u91cd\u65b0\u8c03\u6574\u5bbd\u624e (1995\u20131999)" },
{ "ara", "\u963f\u6839\u5ef7\u5965\u65af\u7279\u62c9\u5c14" },
{ "arl", "\u963f\u6839\u5ef7\u6cd5\u5b9a\u6bd4\u7d22 (1970\u20131983)" },
{ "arm", "\u963f\u6839\u5ef7\u6bd4\u7d22 (1881\u20131970)" },
{ "arp", "\u963f\u6839\u5ef7\u6bd4\u7d22 (1983\u20131985)" },
{ "ars", "\u963f\u6839\u5ef7\u6bd4\u7d22" },
{ "ats", "\u5965\u5730\u5229\u5148\u4ee4" },
{ "aud", "\u6fb3\u5927\u5229\u4e9a\u5143" },
{ "awg", "\u963f\u9c81\u5df4\u5f17\u7f57\u6797" },
{ "azm", "\u963f\u585e\u62dc\u7586\u9a6c\u7eb3\u7279 (1993\u20132006)" },
{ "azn", "\u963f\u585e\u62dc\u7586\u9a6c\u7eb3\u7279" },
{ "bad", "\u6ce2\u58eb\u5c3c\u4e9a-\u8d6b\u585e\u54e5\u7ef4\u7eb3\u7b2c\u7eb3\u5c14 (1992\u20131994)" },
{ "bam", "\u6ce2\u65af\u5c3c\u4e9a-\u9ed1\u585e\u54e5\u7ef4\u90a3\u53ef\u5151\u6362\u9a6c\u514b" },
{ "ban", "\u6ce2\u58eb\u5c3c\u4e9a-\u8d6b\u585e\u54e5\u7ef4\u7eb3\u65b0\u7b2c\u7eb3\u5c14 (1994\u20131997)" },
{ "bbd", "\u5df4\u5df4\u591a\u65af\u5143" },
{ "bdt", "\u5b5f\u52a0\u62c9\u5854\u5361" },
{ "bec", "\u6bd4\u5229\u65f6\u6cd5\u90ce\uff08\u53ef\u5151\u6362\uff09" },
{ "bef", "\u6bd4\u5229\u65f6\u6cd5\u90ce" },
{ "bel", "\u6bd4\u5229\u65f6\u6cd5\u90ce\uff08\u91d1\u878d\uff09" },
{ "bgl", "\u4fdd\u52a0\u5229\u4e9a\u786c\u5217\u5f17" },
{ "bgm", "\u4fdd\u52a0\u5229\u4e9a\u793e\u4f1a\u515a\u5217\u5f17" },
{ "bgn", "\u4fdd\u52a0\u5229\u4e9a\u5217\u5f17" },
{ "bgo", "\u4fdd\u52a0\u5229\u4e9a\u5217\u5f17 (1879\u20131952)" },
{ "bhd", "\u5df4\u6797\u7b2c\u7eb3\u5c14" },
{ "bif", "\u5e03\u9686\u8fea\u6cd5\u90ce" },
{ "bmd", "\u767e\u6155\u5927\u5143" },
{ "bnd", "\u6587\u83b1\u5143" },
{ "bob", "\u73bb\u5229\u7ef4\u4e9a\u8bfa" },
{ "bol", "\u73bb\u5229\u7ef4\u4e9a\u8bfa (1863\u20131963)" },
{ "bop", "\u73bb\u5229\u7ef4\u4e9a\u6bd4\u7d22" },
{ "bov", "\u73bb\u5229\u7ef4\u4e9a Mvdol\uff08\u8d44\u91d1\uff09" },
{ "brb", "\u5df4\u897f\u65b0\u514b\u9c81\u8d5b\u7f57 (1967\u20131986)" },
{ "brc", "\u5df4\u897f\u514b\u9c81\u624e\u591a (1986\u20131989)" },
{ "bre", "\u5df4\u897f\u514b\u9c81\u585e\u7f57 (1990\u20131993)" },
{ "brl", "\u5df4\u897f\u96f7\u4e9a\u5c14" },
{ "brn", "\u5df4\u897f\u65b0\u514b\u9c81\u624e\u591a (1989\u20131990)" },
{ "brr", "\u5df4\u897f\u514b\u9c81\u585e\u7f57 (1993\u20131994)" },
{ "brz", "\u5df4\u897f\u514b\u9c81\u585e\u7f57 (1942\u20131967)" },
{ "bsd", "\u5df4\u54c8\u9a6c\u5143" },
{ "btn", "\u4e0d\u4e39\u52aa\u5c14\u7279\u9c81\u59c6" },
{ "buk", "\u7f05\u5143" },
{ "bwp", "\u535a\u8328\u74e6\u7eb3\u666e\u62c9" },
{ "byb", "\u767d\u4fc4\u7f57\u65af\u65b0\u5362\u5e03 (1994\u20131999)" },
{ "byn", "\u767d\u4fc4\u7f57\u65af\u5362\u5e03" },
{ "byr", "\u767d\u4fc4\u7f57\u65af\u5362\u5e03 (2000\u20132016)" },
{ "bzd", "\u4f2f\u5229\u5179\u5143" },
{ "cad", "\u52a0\u62ff\u5927\u5143" },
{ "cdf", "\u521a\u679c\u6cd5\u90ce" },
{ "che", "\u6b27\u5143 (WIR)" },
{ "chf", "\u745e\u58eb\u6cd5\u90ce" },
{ "chw", "\u6cd5\u90ce (WIR)" },
{ "cle", "\u667a\u5229\u57c3\u65af\u5e93\u591a" },
{ "clf", "\u667a\u5229\uff08\u8d44\u91d1\uff09" },
{ "clp", "\u667a\u5229\u6bd4\u7d22" },
{ "cnh", "\u4eba\u6c11\u5e01\uff08\u79bb\u5cb8\uff09" },
{ "cny", "\u4eba\u6c11\u5e01" },
{ "cop", "\u54e5\u4f26\u6bd4\u4e9a\u6bd4\u7d22" },
{ "cou", "\u54e5\u4f26\u6bd4\u4e9a\u5e01" },
{ "crc", "\u54e5\u65af\u8fbe\u9ece\u52a0\u79d1\u6717" },
{ "csd", "\u65e7\u585e\u5c14\u7ef4\u4e9a\u7b2c\u7eb3\u5c14" },
{ "csk", "\u6377\u514b\u786c\u514b\u6717" },
{ "cuc", "\u53e4\u5df4\u53ef\u5151\u6362\u6bd4\u7d22" },
{ "cup", "\u53e4\u5df4\u6bd4\u7d22" },
{ "cve", "\u4f5b\u5f97\u89d2\u57c3\u65af\u5e93\u591a" },
{ "cyp", "\u585e\u6d66\u8def\u65af\u9551" },
{ "czk", "\u6377\u514b\u514b\u6717" },
{ "ddm", "\u4e1c\u5fb7\u5965\u65af\u7279\u9a6c\u514b" },
{ "dem", "\u5fb7\u56fd\u9a6c\u514b" },
{ "djf", "\u5409\u5e03\u63d0\u6cd5\u90ce" },
{ "dkk", "\u4e39\u9ea6\u514b\u6717" },
{ "dop", "\u591a\u7c73\u5c3c\u52a0\u6bd4\u7d22" },
{ "dzd", "\u963f\u5c14\u53ca\u5229\u4e9a\u7b2c\u7eb3\u5c14" },
{ "ecs", "\u5384\u74dc\u591a\u5c14\u82cf\u514b\u96f7" },
{ "ecv", "\u5384\u74dc\u591a\u5c14 (UVC)" },
{ "eek", "\u7231\u6c99\u5c3c\u4e9a\u514b\u6717" },
{ "egp", "\u57c3\u53ca\u9551" },
{ "ern", "\u5384\u7acb\u7279\u91cc\u4e9a\u7eb3\u514b\u6cd5" },
{ "esa", "\u897f\u73ed\u7259\u6bd4\u585e\u5854\uff08\u5e10\u6237 A\uff09" },
{ "esb", "\u897f\u73ed\u7259\u6bd4\u585e\u5854\uff08\u5151\u6362\u5e10\u6237\uff09" },
{ "esp", "\u897f\u73ed\u7259\u6bd4\u585e\u5854" },
{ "etb", "\u57c3\u585e\u4fc4\u6bd4\u4e9a\u6bd4\u5c14" },
{ "eur", "\u6b27\u5143" },
{ "fim", "\u82ac\u5170\u9a6c\u514b" },
{ "fjd", "\u6590\u6d4e\u5143" },
{ "fkp", "\u798f\u514b\u5170\u7fa4\u5c9b\u9551" },
{ "frf", "\u6cd5\u56fd\u6cd5\u90ce" },
{ "gbp", "\u82f1\u9551" },
{ "gek", "\u4e54\u6cbb\u4e9a\u5e93\u84ec\u62c9\u745e\u7279" },
{ "gel", "\u683c\u9c81\u5409\u4e9a\u62c9\u91cc" },
{ "ghc", "\u52a0\u7eb3\u585e\u7b2c" },
{ "ghs", "\u52a0\u7eb3\u585e\u5730" },
{ "gip", "\u76f4\u5e03\u7f57\u9640\u9551" },
{ "gmd", "\u5188\u6bd4\u4e9a\u8fbe\u62c9\u897f" },
{ "gnf", "\u51e0\u5185\u4e9a\u6cd5\u90ce" },
{ "gns", "\u51e0\u5185\u4e9a\u897f\u91cc" },
{ "gqe", "\u8d64\u9053\u51e0\u5185\u4e9a\u57c3\u594e\u52d2" },
{ "grd", "\u5e0c\u814a\u5fb7\u62c9\u514b\u9a6c" },
{ "gtq", "\u5371\u5730\u9a6c\u62c9\u683c\u67e5\u5c14" },
{ "gwe", "\u8461\u8404\u7259\u51e0\u5185\u4e9a\u57c3\u65af\u5e93\u591a" },
{ "gwp", "\u51e0\u5185\u4e9a\u6bd4\u7ecd\u6bd4\u7d22" },
{ "gyd", "\u572d\u4e9a\u90a3\u5143" },
{ "hkd", "\u6e2f\u5143" },
{ "hnl", "\u6d2a\u90fd\u62c9\u65af\u4f26\u76ae\u62c9" },
{ "hrd", "\u514b\u7f57\u5730\u4e9a\u7b2c\u7eb3\u5c14" },
{ "hrk", "\u514b\u7f57\u5730\u4e9a\u5e93\u7eb3" },
{ "htg", "\u6d77\u5730\u53e4\u5fb7" },
{ "huf", "\u5308\u7259\u5229\u798f\u6797" },
{ "idr", "\u5370\u5ea6\u5c3c\u897f\u4e9a\u76fe" },
{ "iep", "\u7231\u5c14\u5170\u9551" },
{ "ilp", "\u4ee5\u8272\u5217\u9551" },
{ "ilr", "\u4ee5\u8272\u5217\u8c22\u514b\u5c14(1980\u20131985)" },
{ "ils", "\u4ee5\u8272\u5217\u65b0\u8c22\u514b\u5c14" },
{ "inr", "\u5370\u5ea6\u5362\u6bd4" },
{ "iqd", "\u4f0a\u62c9\u514b\u7b2c\u7eb3\u5c14" },
{ "irr", "\u4f0a\u6717\u91cc\u4e9a\u5c14" },
{ "isj", "\u51b0\u5c9b\u514b\u6717(1918\u20131981)" },
{ "isk", "\u51b0\u5c9b\u514b\u6717" },
{ "itl", "\u610f\u5927\u5229\u91cc\u62c9" },
{ "jmd", "\u7259\u4e70\u52a0\u5143" },
{ "jod", "\u7ea6\u65e6\u7b2c\u7eb3\u5c14" },
{ "jpy", "\u65e5\u5143" },
{ "kes", "\u80af\u5c3c\u4e9a\u5148\u4ee4" },
{ "kgs", "\u5409\u5c14\u5409\u65af\u65af\u5766\u7d22\u59c6" },
{ "khr", "\u67ec\u57d4\u5be8\u745e\u5c14" },
{ "kmf", "\u79d1\u6469\u7f57\u6cd5\u90ce" },
{ "kpw", "\u671d\u9c9c\u5143" },
{ "krh", "\u97e9\u5143 (1953\u20131962)" },
{ "kro", "\u97e9\u5143 (1945\u20131953)" },
{ "krw", "\u97e9\u5143" },
{ "kwd", "\u79d1\u5a01\u7279\u7b2c\u7eb3\u5c14" },
{ "kyd", "\u5f00\u66fc\u5143" },
{ "kzt", "\u54c8\u8428\u514b\u65af\u5766\u575a\u6208" },
{ "lak", "\u8001\u631d\u57fa\u666e" },
{ "lbp", "\u9ece\u5df4\u5ae9\u9551" },
{ "lkr", "\u65af\u91cc\u5170\u5361\u5362\u6bd4" },
{ "lrd", "\u5229\u6bd4\u91cc\u4e9a\u5143" },
{ "lsl", "\u83b1\u7d22\u6258\u6d1b\u8482" },
{ "ltl", "\u7acb\u9676\u5b9b\u7acb\u7279" },
{ "ltt", "\u7acb\u9676\u5b9b\u5854\u54af\u5450\u53f8" },
{ "luc", "\u5362\u68ee\u5821\u53ef\u5151\u6362\u6cd5\u90ce" },
{ "luf", "\u5362\u68ee\u5821\u6cd5\u90ce" },
{ "lul", "\u5362\u68ee\u5821\u91d1\u878d\u6cd5\u90ce" },
{ "lvl", "\u62c9\u8131\u7ef4\u4e9a\u62c9\u7279" },
{ "lvr", "\u62c9\u8131\u7ef4\u4e9a\u5362\u5e03" },
{ "lyd", "\u5229\u6bd4\u4e9a\u7b2c\u7eb3\u5c14" },
{ "mad", "\u6469\u6d1b\u54e5\u8fea\u62c9\u59c6" },
{ "maf", "\u6469\u6d1b\u54e5\u6cd5\u90ce" },
{ "mcf", "\u6469\u7eb3\u54e5\u6cd5\u90ce" },
{ "mdc", "\u6469\u5c14\u591a\u74e6\u5e93\u90a6" },
{ "mdl", "\u6469\u5c14\u591a\u74e6\u5217\u4f0a" },
{ "mga", "\u9a6c\u8fbe\u52a0\u65af\u52a0\u963f\u91cc\u4e9a\u91cc" },
{ "mgf", "\u9a6c\u8fbe\u52a0\u65af\u52a0\u6cd5\u90ce" },
{ "mkd", "\u9a6c\u5176\u987f\u7b2c\u7eb3\u5c14" },
{ "mkn", "\u9a6c\u5176\u987f\u7b2c\u7eb3\u5c14 (1992\u20131993)" },
{ "mlf", "\u9a6c\u91cc\u6cd5\u90ce" },
{ "mmk", "\u7f05\u7538\u5143" },
{ "mnt", "\u8499\u53e4\u56fe\u683c\u91cc\u514b" },
{ "mop", "\u6fb3\u95e8\u5e01" },
{ "mro", "\u6bdb\u91cc\u5854\u5c3c\u4e9a\u4e4c\u5409\u4e9a (1973\u20132017)" },
{ "mru", "\u6bdb\u91cc\u5854\u5c3c\u4e9a\u4e4c\u5409\u4e9a" },
{ "mtl", "\u9a6c\u8033\u4ed6\u91cc\u62c9" },
{ "mtp", "\u9a6c\u8033\u4ed6\u9551" },
{ "mur", "\u6bdb\u91cc\u6c42\u65af\u5362\u6bd4" },
{ "mvp", "\u9a6c\u5c14\u4ee3\u592b\u5362\u6bd4(1947\u20131981)" },
{ "mvr", "\u9a6c\u5c14\u4ee3\u592b\u5362\u83f2\u4e9a" },
{ "mwk", "\u9a6c\u62c9\u7ef4\u514b\u74e6\u67e5" },
{ "mxn", "\u58a8\u897f\u54e5\u6bd4\u7d22" },
{ "mxp", "\u58a8\u897f\u54e5\u94f6\u6bd4\u7d22 (1861\u20131992)" },
{ "mxv", "\u58a8\u897f\u54e5\uff08\u8d44\u91d1\uff09" },
{ "myr", "\u9a6c\u6765\u897f\u4e9a\u6797\u5409\u7279" },
{ "mze", "\u83ab\u6851\u6bd4\u514b\u57c3\u65af\u5e93\u591a" },
{ "mzm", "\u65e7\u83ab\u6851\u6bd4\u514b\u7f8e\u63d0\u5361" },
{ "mzn", "\u83ab\u6851\u6bd4\u514b\u7f8e\u63d0\u5361" },
{ "nad", "\u7eb3\u7c73\u6bd4\u4e9a\u5143" },
{ "ngn", "\u5c3c\u65e5\u5229\u4e9a\u5948\u62c9" },
{ "nic", "\u5c3c\u52a0\u62c9\u74dc\u79d1\u591a\u5df4 (1988\u20131991)" },
{ "nio", "\u5c3c\u52a0\u62c9\u74dc\u79d1\u591a\u5df4" },
{ "nlg", "\u8377\u5170\u76fe" },
{ "nok", "\u632a\u5a01\u514b\u6717" },
{ "npr", "\u5c3c\u6cca\u5c14\u5362\u6bd4" },
{ "nzd", "\u65b0\u897f\u5170\u5143" },
{ "omr", "\u963f\u66fc\u91cc\u4e9a\u5c14" },
{ "pab", "\u5df4\u62ff\u9a6c\u5df4\u6ce2\u4e9a" },
{ "pei", "\u79d8\u9c81\u5370\u7b2c" },
{ "pen", "\u79d8\u9c81\u7d22\u5c14" },
{ "pes", "\u79d8\u9c81\u7d22\u5c14 (1863\u20131965)" },
{ "pgk", "\u5df4\u5e03\u4e9a\u65b0\u51e0\u5185\u4e9a\u57fa\u90a3" },
{ "php", "\u83f2\u5f8b\u5bbe\u6bd4\u7d22" },
{ "pkr", "\u5df4\u57fa\u65af\u5766\u5362\u6bd4" },
{ "pln", "\u6ce2\u5170\u5179\u7f57\u63d0" },
{ "plz", "\u6ce2\u5170\u5179\u7f57\u63d0 (1950\u20131995)" },
{ "pte", "\u8461\u8404\u7259\u57c3\u65af\u5e93\u591a" },
{ "pyg", "\u5df4\u62c9\u572d\u74dc\u62c9\u5c3c" },
{ "qar", "\u5361\u5854\u5c14\u91cc\u4e9a\u5c14" },
{ "rhd", "\u7f57\u5f97\u897f\u4e9a\u5143" },
{ "rol", "\u65e7\u7f57\u9a6c\u5c3c\u4e9a\u5217\u4f0a" },
{ "ron", "\u7f57\u9a6c\u5c3c\u4e9a\u5217\u4f0a" },
{ "rsd", "\u585e\u5c14\u7ef4\u4e9a\u7b2c\u7eb3\u5c14" },
{ "rub", "\u4fc4\u7f57\u65af\u5362\u5e03" },
{ "rur", "\u4fc4\u56fd\u5362\u5e03 (1991\u20131998)" },
{ "rwf", "\u5362\u65fa\u8fbe\u6cd5\u90ce" },
{ "sar", "\u6c99\u7279\u91cc\u4e9a\u5c14" },
{ "sbd", "\u6240\u7f57\u95e8\u7fa4\u5c9b\u5143" },
{ "scr", "\u585e\u820c\u5c14\u5362\u6bd4" },
{ "sdd", "\u82cf\u4e39\u7b2c\u7eb3\u5c14 (1992\u20132007)" },
{ "sdg", "\u82cf\u4e39\u9551" },
{ "sdp", "\u65e7\u82cf\u4e39\u9551" },
{ "sek", "\u745e\u5178\u514b\u6717" },
{ "sgd", "\u65b0\u52a0\u5761\u5143" },
{ "shp", "\u5723\u8d6b\u52d2\u62ff\u7fa4\u5c9b\u78c5" },
{ "sit", "\u65af\u6d1b\u6587\u5c3c\u4e9a\u6258\u62c9\u5c14" },
{ "skk", "\u65af\u6d1b\u4f10\u514b\u514b\u6717" },
{ "sll", "\u585e\u62c9\u5229\u6602\u5229\u6602" },
{ "sos", "\u7d22\u9a6c\u91cc\u5148\u4ee4" },
{ "srd", "\u82cf\u91cc\u5357\u5143" },
{ "srg", "\u82cf\u91cc\u5357\u76fe" },
{ "ssp", "\u5357\u82cf\u4e39\u9551" },
{ "std", "\u5723\u591a\u7f8e\u548c\u666e\u6797\u897f\u6bd4\u591a\u5e03\u62c9 (1977\u20132017)" },
{ "stn", "\u5723\u591a\u7f8e\u548c\u666e\u6797\u897f\u6bd4\u591a\u5e03\u62c9" },
{ "sur", "\u82cf\u8054\u5362\u5e03" },
{ "svc", "\u8428\u5c14\u74e6\u591a\u79d1\u6717" },
{ "syp", "\u53d9\u5229\u4e9a\u9551" },
{ "szl", "\u65af\u5a01\u58eb\u5170\u91cc\u5170\u5409\u5c3c" },
{ "thb", "\u6cf0\u94e2" },
{ "tjr", "\u5854\u5409\u514b\u65af\u5766\u5362\u5e03" },
{ "tjs", "\u5854\u5409\u514b\u65af\u5766\u7d22\u83ab\u5c3c" },
{ "tmm", "\u571f\u5e93\u66fc\u65af\u5766\u9a6c\u7eb3\u7279 (1993\u20132009)" },
{ "tmt", "\u571f\u5e93\u66fc\u65af\u5766\u9a6c\u7eb3\u7279" },
{ "tnd", "\u7a81\u5c3c\u65af\u7b2c\u7eb3\u5c14" },
{ "top", "\u6c64\u52a0\u6f58\u52a0" },
{ "tpe", "\u5e1d\u6c76\u57c3\u65af\u5e93\u591a" },
{ "trl", "\u571f\u8033\u5176\u91cc\u62c9 (1922\u20132005)" },
{ "try", "\u571f\u8033\u5176\u91cc\u62c9" },
{ "ttd", "\u7279\u7acb\u5c3c\u8fbe\u548c\u591a\u5df4\u54e5\u5143" },
{ "twd", "\u65b0\u53f0\u5e01" },
{ "tzs", "\u5766\u6851\u5c3c\u4e9a\u5148\u4ee4" },
{ "uah", "\u4e4c\u514b\u5170\u683c\u91cc\u592b\u7eb3" },
{ "uak", "\u4e4c\u514b\u5170\u5e01" },
{ "ugs", "\u4e4c\u5e72\u8fbe\u5148\u4ee4 (1966\u20131987)" },
{ "ugx", "\u4e4c\u5e72\u8fbe\u5148\u4ee4" },
{ "usd", "\u7f8e\u5143" },
{ "usn", "\u7f8e\u5143\uff08\u6b21\u65e5\uff09" },
{ "uss", "\u7f8e\u5143\uff08\u5f53\u65e5\uff09" },
{ "uyi", "\u4e4c\u62c9\u572d\u6bd4\u7d22\uff08\u7d22\u5f15\u5355\u4f4d\uff09" },
{ "uyp", "\u4e4c\u62c9\u572d\u6bd4\u7d22 (1975\u20131993)" },
{ "uyu", "\u4e4c\u62c9\u572d\u6bd4\u7d22" },
{ "uzs", "\u4e4c\u5179\u522b\u514b\u65af\u5766\u82cf\u59c6" },
{ "veb", "\u59d4\u5185\u745e\u62c9\u73bb\u5229\u74e6\u5c14 (1871\u20132008)" },
{ "vef", "\u59d4\u5185\u745e\u62c9\u73bb\u5229\u74e6\u5c14" },
{ "vnd", "\u8d8a\u5357\u76fe" },
{ "vnn", "\u8d8a\u5357\u76fe (1978\u20131985)" },
{ "vuv", "\u74e6\u52aa\u963f\u56fe\u74e6\u56fe" },
{ "wst", "\u8428\u6469\u4e9a\u5854\u62c9" },
{ "xaf", "\u4e2d\u975e\u6cd5\u90ce" },
{ "xag", "\u94f6" },
{ "xau", "\u9ec4\u91d1" },
{ "xba", "\u6b27\u6d32\u590d\u5408\u5355\u4f4d" },
{ "xbb", "\u6b27\u6d32\u8d27\u5e01\u8054\u76df" },
{ "xbc", "\u6b27\u6d32\u8ba1\u7b97\u5355\u4f4d (XBC)" },
{ "xbd", "\u6b27\u6d32\u8ba1\u7b97\u5355\u4f4d (XBD)" },
{ "xcd", "\u4e1c\u52a0\u52d2\u6bd4\u5143" },
{ "xdr", "\u7279\u522b\u63d0\u6b3e\u6743" },
{ "xeu", "\u6b27\u6d32\u8d27\u5e01\u5355\u4f4d" },
{ "xfo", "\u6cd5\u56fd\u91d1\u6cd5\u90ce" },
{ "xfu", "\u6cd5\u56fd\u6cd5\u90ce (UIC)" },
{ "xof", "\u897f\u975e\u6cd5\u90ce" },
{ "xpd", "\u94af" },
{ "xpf", "\u592a\u5e73\u6d0b\u6cd5\u90ce" },
{ "xpt", "\u94c2" },
{ "xre", "RINET \u57fa\u91d1" },
{ "xts", "\u6d4b\u8bd5\u8d27\u5e01\u4ee3\u7801" },
{ "xxx", "\u672a\u77e5\u8d27\u5e01" },
{ "ydd", "\u4e5f\u95e8\u7b2c\u7eb3\u5c14" },
{ "yer", "\u4e5f\u95e8\u91cc\u4e9a\u5c14" },
{ "yud", "\u5357\u65af\u62c9\u592b\u786c\u7b2c\u7eb3\u5c14 (1966\u20131990)" },
{ "yum", "\u5357\u65af\u62c9\u592b\u65b0\u7b2c\u7eb3\u5c14 (1994\u20132002)" },
{ "yun", "\u5357\u65af\u62c9\u592b\u53ef\u5151\u6362\u7b2c\u7eb3\u5c14 (1990\u20131992)" },
{ "yur", "\u5357\u65af\u62c9\u592b\u6539\u826f\u7b2c\u7eb3\u5c14 (1992\u20131993)" },
{ "zal", "\u5357\u975e\u5170\u7279 (\u91d1\u878d)" },
{ "zar", "\u5357\u975e\u5170\u7279" },
{ "zmk", "\u8d5e\u6bd4\u4e9a\u514b\u74e6\u67e5 (1968\u20132012)" },
{ "zmw", "\u8d5e\u6bd4\u4e9a\u514b\u74e6\u67e5" },
{ "zrn", "\u65b0\u624e\u4f0a\u5c14 (1993\u20131998)" },
{ "zrz", "\u624e\u4f0a\u5c14 (1971\u20131993)" },
{ "zwd", "\u6d25\u5df4\u5e03\u97e6\u5143 (1980\u20132008)" },
{ "zwl", "\u6d25\u5df4\u5e03\u97e6\u5143 (2009)" },
{ "zwr", "\u6d25\u5df4\u5e03\u97e6\u5143 (2008)" },
};
return data;
}
}
|
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work.integration.testapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import androidx.work.Result;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
/**
* A test worker that sleeps.
*/
public class SleepWorker extends Worker {
private static final String TAG = "SleepWorker";
public SleepWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@Override
public @NonNull Result doWork() {
try {
Log.i(TAG, "Sleeping");
Thread.sleep(200);
Log.i(TAG, "Completed");
} catch (InterruptedException ignore) {
Log.v(TAG, "Interrupted.");
}
return Result.success();
}
}
|
package snownee.kiwi.block.def;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Nullable;
import com.google.common.collect.Maps;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.Material;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.phys.HitResult;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.client.model.data.EmptyModelData;
import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
import snownee.kiwi.loader.Platform;
public class SimpleBlockDefinition implements BlockDefinition {
private static final MethodHandle GET_STATE_FOR_PLACEMENT;
static {
MethodHandle m = null;
try {
m = MethodHandles.lookup().unreflect(ObfuscationReflectionHelper.findMethod(BlockItem.class, "m_5965_", BlockPlaceContext.class));
} catch (Exception e) {
throw new RuntimeException("Report this to author", e);
}
GET_STATE_FOR_PLACEMENT = m;
}
@Nullable
private static BlockState getStateForPlacement(BlockItem blockItem, BlockPlaceContext context) {
try {
return (BlockState) GET_STATE_FOR_PLACEMENT.invokeExact(blockItem, context);
} catch (Throwable e) {
return null;
}
}
public enum Factory implements BlockDefinition.Factory<SimpleBlockDefinition> {
INSTANCE;
@Override
public SimpleBlockDefinition fromNBT(CompoundTag tag) {
BlockState state = NbtUtils.readBlockState(tag.getCompound(TYPE));
if (state.isAir())
return null;
return of(state);
}
@Override
public SimpleBlockDefinition fromBlock(BlockState state, BlockEntity blockEntity, LevelReader level, BlockPos pos) {
return of(state);
}
@Override
public SimpleBlockDefinition fromItem(ItemStack stack, BlockPlaceContext context) {
if (!(stack.getItem() instanceof BlockItem)) {
return null;
}
BlockItem blockItem = (BlockItem) stack.getItem();
if (context == null) {
return of(blockItem.getBlock().defaultBlockState());
}
context = blockItem.updatePlacementContext(context);
if (context == null) {
return null;
}
BlockState state = getStateForPlacement(blockItem, context);
if (state == null) {
return null;
}
return of(state);
}
@Override
public String getId() {
return TYPE;
}
}
public static final String TYPE = "Block";
private static final Map<BlockState, SimpleBlockDefinition> MAP = Maps.newIdentityHashMap();
public static SimpleBlockDefinition of(BlockState state) {
if (state.getBlock() == Blocks.GRASS_BLOCK) {
state = state.setValue(BlockStateProperties.SNOWY, false);
}
return MAP.computeIfAbsent(state, SimpleBlockDefinition::new);
}
public final BlockState state;
@OnlyIn(Dist.CLIENT)
private Material[] materials;
private SimpleBlockDefinition(BlockState state) {
this.state = state;
if (Platform.isPhysicalClient()) {
materials = new Material[7];
}
}
@Override
public BlockDefinition.Factory<?> getFactory() {
return Factory.INSTANCE;
}
@Override
@OnlyIn(Dist.CLIENT)
public BakedModel model() {
return Minecraft.getInstance().getBlockRenderer().getBlockModelShaper().getBlockModel(state);
}
@Override
@OnlyIn(Dist.CLIENT)
public Material renderMaterial(Direction direction) {
int index = direction == null ? 0 : direction.ordinal() + 1;
if (materials[index] == null) {
BakedModel model = model();
Random random = new Random();
random.setSeed(42L);
ResourceLocation particleIcon = model.getParticleIcon(EmptyModelData.INSTANCE).getName();
ResourceLocation sprite = particleIcon;
if (state.getBlock() == Blocks.GRASS_BLOCK) {
direction = Direction.UP;
}
if (direction != null) {
List<BakedQuad> quads = model.getQuads(state, direction, random, EmptyModelData.INSTANCE);
if (quads.isEmpty())
quads = model.getQuads(state, null, random, EmptyModelData.INSTANCE);
for (BakedQuad quad : quads) {
sprite = quad.getSprite().getName();
if (sprite.equals(particleIcon)) {
break;
}
}
}
materials[index] = ModelLoaderRegistry.blockMaterial(sprite);
}
return materials[index];
}
@Override
@OnlyIn(Dist.CLIENT)
public boolean canRenderInLayer(RenderType layer) {
return ItemBlockRenderTypes.canRenderInLayer(state, layer);
}
@Override
public boolean canOcclude() {
return state.canOcclude();
}
@Override
public void save(CompoundTag tag) {
tag.put(TYPE, NbtUtils.writeBlockState(state));
}
@Override
public String toString() {
return state.toString();
}
@Override
@OnlyIn(Dist.CLIENT)
public int getColor(BlockState blockState, BlockAndTintGetter level, BlockPos worldPosition, int index) {
return Minecraft.getInstance().getBlockColors().getColor(state, level, worldPosition, index);
}
@Override
public Component getDescription() {
return state.getBlock().getName();
}
@Override
public void place(Level level, BlockPos pos) {
BlockState state = this.state;
if (state.hasProperty(BlockStateProperties.LIT))
state = state.setValue(BlockStateProperties.LIT, false);
level.setBlockAndUpdate(pos, state);
}
@Override
public ItemStack createItem(HitResult target, BlockGetter world, BlockPos pos, Player player) {
return getBlockState().getCloneItemStack(target, world, pos, player);
}
@Override
public BlockState getBlockState() {
return state;
}
@Override
public SoundType getSoundType() {
return state.getSoundType();
}
public static void reload() {
for (SimpleBlockDefinition supplier : MAP.values()) {
Arrays.fill(supplier.materials, null);
}
}
}
|
/*
* Copyright 2000-2020 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.internal.nodefeature;
import org.junit.Assert;
import org.junit.Test;
public class LoadingIndicatorConfigurationMapTest
extends AbstractMapFeatureTest<LoadingIndicatorConfigurationMap> {
private final LoadingIndicatorConfigurationMap map = createFeature();
@Test
public void defaults() {
Assert.assertEquals(
LoadingIndicatorConfigurationMap.FIRST_DELAY_DEFAULT,
map.getFirstDelay());
Assert.assertEquals(
LoadingIndicatorConfigurationMap.SECOND_DELAY_DEFAULT,
map.getSecondDelay());
Assert.assertEquals(
LoadingIndicatorConfigurationMap.THIRD_DELAY_DEFAULT,
map.getThirdDelay());
Assert.assertEquals(
LoadingIndicatorConfigurationMap.DEFAULT_THEME_APPLIED_DEFAULT,
map.isApplyDefaultTheme());
}
@Test
public void setGetFirstDelay() {
testInt(map, LoadingIndicatorConfigurationMap.FIRST_DELAY_KEY,
map::setFirstDelay, map::getFirstDelay);
}
@Test
public void setGetSecondDelay() {
testInt(map, LoadingIndicatorConfigurationMap.SECOND_DELAY_KEY,
map::setSecondDelay, map::getSecondDelay);
}
@Test
public void setGetThirdDelay() {
testInt(map, LoadingIndicatorConfigurationMap.THIRD_DELAY_KEY,
map::setThirdDelay, map::getThirdDelay);
}
@Test
public void setGetDefaultThemeApplied() {
testBoolean(map, LoadingIndicatorConfigurationMap.DEFAULT_THEME_APPLIED_KEY,
map::setApplyDefaultTheme, map::isApplyDefaultTheme);
}
}
|
package org.intermine.bio.webservice;
/*
* Copyright (C) 2002-2014 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.intermine.api.InterMineAPI;
import org.intermine.bio.web.export.GFF3Exporter;
import org.intermine.bio.web.logic.SequenceFeatureExportUtil;
import org.intermine.bio.web.logic.SequenceFeatureExportUtil.InvalidQueryException;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.context.InterMineContext;
import org.intermine.webservice.server.exceptions.BadRequestException;
/**
* A service for exporting query results as gff3.
* @author Alexis Kalderimis.
*
*/
public class GFFQueryService extends BioQueryService
{
/**
* Constructor.
* @param im A reference to an InterMine API settings bundle.
*/
public GFFQueryService(InterMineAPI im) {
super(im);
}
@Override
protected String getSuffix() {
return ".gff3";
}
@Override
protected String getContentType() {
return "text/x-gff3";
}
/**
* @param pq pathquery
* @return the exporter
*/
@Override
protected GFF3Exporter getExporter(PathQuery pq) {
String sourceName = webProperties.getProperty("project.title");
Set<Integer> organisms = null;
List<Integer> indexes = new ArrayList<Integer>();
List<String> viewColumns = new ArrayList<String>(pq.getView());
for (int i = 0; i < viewColumns.size(); i++) {
indexes.add(Integer.valueOf(i));
}
removeFirstItemInPaths(viewColumns);
return new GFF3Exporter(
getPrintWriter(), indexes, getSoClassNames(),
viewColumns, sourceName, organisms, false, getQueryPaths(pq));
}
/**
*
* @return map of SO class names
*/
static Map<String, String> getSoClassNames() {
return new HashMap<String, String>(
(Map) InterMineContext.getAttribute(GFF3QueryServlet.SO_CLASS_NAMES));
}
/**
* @param paths paths
*/
static void removeFirstItemInPaths(List<String> paths) {
for (int i = 0; i < paths.size(); i++) {
String path = paths.get(i);
paths.set(i, path.substring(path.indexOf(".") + 1, path.length()));
}
}
@Override
protected void checkPathQuery(PathQuery pq) throws Exception {
try {
SequenceFeatureExportUtil.isValidSequenceFeatureQuery(pq);
} catch (InvalidQueryException e) {
throw new BadRequestException(e.getMessage(), e);
}
}
}
|
/**
* Copyright 2008 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.waveprotocol.wave.common.logging;
import org.waveprotocol.wave.common.logging.AbstractLogger.Level;
/**
* Base class for log entry sinks.
*
*/
public abstract class LogSink {
/**
* Outputs a log entry to this sink.
*
* @param level the level to log at
* @param message the message to log
*/
public abstract void log(Level level, String message);
/**
* All implementations of this method which are intended to run in the
* browser must buffer output before writing in order to avoid slowing
* down the UI. For these cases, messages must not be stringified until
* they are to be written.
*
* @param level the level to log at
* @param messages list of messages to (potentially lazily) stringify and
* concatenate
*
* NOTE: This method should not have a default implementation which does
* any stringification, because if a LogSink implementation were to
* neglect to override this method, and were used in the browser, there
* may be significant performance implications.
*/
public abstract void lazyLog(Level level, Object... messages);
/**
* Lazily logs a message and a throwable. This implementation XML-escapes
* the label, and the message from the throwable, and prints the stack trace as
* HTML. Sinks which are not intended to output HTML should override this method.
*
* @param level the level to log at
* @param label a label to log
* @param t the throwable to log
*
* NOTE: This method should not have a default implementation which does
* any stringification, because if a LogSink implementation were to
* neglect to override this method, and were used in the browser, there
* may be significant performance implications.
*/
public void lazyLog(Level level, String label, final Throwable t) {
lazyLog(level, label, ": ", new Object() {
@Override
public String toString() {
return LogUtils.xmlEscape(t.toString()) + "<br/>" + LogUtils.printStackTraceAsHtml(t);
}
});
}
}
|
package de.uni_kassel.vs.cn.planDesigner.view.editor.tab;
import de.uni_kassel.vs.cn.planDesigner.controller.MainWindowController;
import de.uni_kassel.vs.cn.planDesigner.view.I18NRepo;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.Tab;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.util.Pair;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractEditorTab extends Tab {
protected SimpleObjectProperty<List<Pair<Long, AbstractPlanElementContainer>>> selectedPlanElements;
private Pair<Long, Path> editablePathPair;
private ObservableList<Node> visualRepresentations;
//TODO onAddElement to scene
private final KeyCombination ctrlA = new KeyCodeCombination(KeyCode.A, KeyCombination.CONTROL_DOWN);
public AbstractEditorTab(Long planElementId) {
selectedPlanElements = new SimpleObjectProperty<>(new ArrayList<>());
selectedPlanElements.get().add(new Pair<>(planElementId, null));
}
// TODO: Review necessary, due to MVC pattern adaption.
public AbstractEditorTab(Pair<Long, Path> editablePathPair) {
// set Tab Caption to name of file, represented by this Tab
super(editablePathPair.getValue().getFileName().toString());
this.editablePathPair = editablePathPair;
initSelectedPlanElements(editablePathPair);
// onAddElement Ctrl+A handlerinterfaces to scene
EditorTabPane editorTabPane = MainWindowController.getInstance().getEditorTabPane();
editorTabPane.getScene().addEventHandler(KeyEvent.KEY_RELEASED, event -> {
if (ctrlA.match(event)) {
selectAllPlanElements(editorTabPane, event);
}
});
// onAddElement close tab handlerinterfaces
setClosable(true);
setOnCloseRequest(e -> {
// popup for trying to close dirty tab
if (dirty) {
IsDirtyWindowController.createIsDirtyWindow(this, e);
}
});
}
private void selectAllPlanElements(EditorTabPane editorTabPane, KeyEvent event) {
Tab selectedTab = editorTabPane.getSelectionModel().getSelectedItem();
if (selectedTab == null && !(selectedTab instanceof PlanTab)) {
return;
}
selectedPlanElements = new SimpleObjectProperty<>(FXCollections.observableArrayList());
visualRepresentations = FXCollections.observableArrayList();
selectedPlanElements.get().addListener(new ListChangeListener<Pair<Long, AbstractPlanElementContainer>>() {
@Override
public void onChanged(Change<? extends Pair<Long, AbstractPlanElementContainer>> change) {
while (change.next()) {
change.getAddedSubList().forEach(o -> {
o.getValue().setEffect(createSelectedEffect());
visualRepresentations.add(o.getValue().getVisualRepresentation());
});
}
}
});
PlanTab tab = (PlanTab) selectedTab;
tab.getPlanEditorGroup().getStateContainers().forEach(stateContainer -> {
selectedPlanElements.get()
.add(new Pair<Long, AbstractPlanElementContainer>(stateContainer.getModelElementId(), stateContainer));
});
tab.getPlanEditorGroup().getEntryPointContainers().forEach(epContainer -> {
selectedPlanElements.get()
.add(new Pair<Long, AbstractPlanElementContainer>(epContainer.getModelElementId(), epContainer));
});
tab.getPlanEditorGroup().getTransitionContainers().forEach(transitionContainer -> {
selectedPlanElements.get()
.add(new Pair<Long, AbstractPlanElementContainer>(transitionContainer.getModelElementId(), transitionContainer));
});
tab.getPlanEditorGroup().getSynchronisationContainers().forEach(syncContainer -> {
selectedPlanElements.get()
.add(new Pair<Long, AbstractPlanElementContainer>(syncContainer.getModelElementId(), syncContainer));
});
}
/**
* initialization for the selected element property, which indicates what elements are selected.
* specializations for specific selections of {@link AbstractPlanElementContainer}s can be found under
* {@link AbstractPlanElementContainer#getMouseClickedEventHandler(PlanElement)}
*
* @param editablePathPair
*/
// TODO: Review necessary, due to MVC pattern adaption.
protected void initSelectedPlanElements(Pair<Long, Path> editablePathPair) {
selectedPlanElements = new SimpleObjectProperty<>(FXCollections.observableArrayList());
selectedPlanElements.get().add(new Pair<>(editablePathPair.getKey(), null));
selectedPlanElements.addListener((observable, oldValue, newValue) -> {
if (newValue == null) {
// TODO: cannot return here because this avoid deleting selectedEffect on oldValue
return;
}
// set selectedEffect on selected elements...
// ... for state container and its containing elements (really special)
DropShadow selectedEffect = createSelectedEffect();
if (newValue.size() == 1 && newValue.get(0).getKey() instanceof AbstractPlan
&& newValue.get(0).getValue() != null
&& newValue.get(0).getValue() instanceof StateContainer) {
((StateContainer) newValue.get(0).getValue()).getStatePlans()
.stream()
.filter(abstractPlanHBox -> abstractPlanHBox.getAbstractPlan()
.equals(newValue.get(0).getKey()))
.findFirst().orElseGet(() -> new AbstractPlanHBox(newValue.get(0).getKey(),
(StateContainer) newValue.get(0).getValue()))
.setEffect(createSelectedEffect());
} else {
newValue.forEach(selectedPlanElementPair -> {
AbstractPlanElementContainer planElementContainer = selectedPlanElementPair.getValue();
if (planElementContainer != null) {
planElementContainer.setEffect(selectedEffect);
}
});
}
// ... for transitions
if (newValue.size() == 1 && newValue.get(0).getValue() instanceof TransitionContainer) {
((TransitionContainer) newValue.get(0).getValue()).setPotentialDraggableNodesVisible(true);
}
if ((oldValue == null)) {
return;
}
oldValue.forEach(selectedPlanElementPair -> {
AbstractPlanElementContainer planElementContainer = selectedPlanElementPair.getValue();
if (planElementContainer != null) {
// this is weird! If I use planElementContainer.setEffectToStandard() nothing happens..
if (planElementContainer.getModelElementId() == oldValue.get(0).getKey()) {
planElementContainer.setEffect(null);
}
if (planElementContainer instanceof StateContainer) {
((StateContainer) planElementContainer)
.getStatePlans()
.forEach(abstractPlanHBox -> {
if (abstractPlanHBox.getAbstractPlan() != newValue.get(0).getKey()) {
abstractPlanHBox.setEffect(null);
}
});
}
}
if (planElementContainer instanceof StateContainer) {
((StateContainer) planElementContainer)
.getStatePlans()
.forEach(abstractPlanHBox -> {
if (abstractPlanHBox.getAbstractPlan() != newValue.get(0).getKey()) {
abstractPlanHBox.setEffect(null);
}
});
}
});
if (oldValue.size() == 1 && oldValue.get(0).getValue() instanceof TransitionContainer) {
((TransitionContainer) oldValue.get(0).getValue()).setPotentialDraggableNodesVisible(false);
}
});
}
public void clearSelectedElements() {
selectedPlanElements.get().forEach(element -> {
if (element.getValue() == null) {
return;
}
element.getValue().setEffect(null);
});
selectedPlanElements.get().clear();
visualRepresentations.clear();
}
private DropShadow createSelectedEffect() {
DropShadow value = new DropShadow(StateContainer.STATE_RADIUS, new Color(0, 0.4, 0.9, 0.9));
value.setBlurType(BlurType.ONE_PASS_BOX);
value.setSpread(0.45);
return value;
}
public Path getFilePath() {
return editablePathPair.getValue();
}
// TODO: Review necessary, due to MVC pattern adaption.
public void save() {
try {
setText(getText().replace("*", ""));
//EMFModelUtils.saveAlicaFile(getEditable());
//getCommandStack().setSavedForAbstractPlan(editablePathPair.getKey());
} catch (IOException e) {
ErrorWindowController.createErrorWindow(I18NRepo.getInstance().getString("label.error.save"), e);
}
}
public Long getEditable() {
return editablePathPair.getKey();
}
public SimpleObjectProperty<List<Pair<Long, AbstractPlanElementContainer>>> getSelectedPlanElements() {
return selectedPlanElements;
}
private void setEditablePathPair(Pair<Long, Path> editablePathPair) {
this.editablePathPair = editablePathPair;
}
public Pair<Long, Path> getEditablePathPair() {
return editablePathPair;
}
}
|
package com.greenlearner.springbootbanner;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootbannerApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(SpringbootbannerApplication.class);
//springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.run(args);
}
}
|
package org.pitest.simpletest;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotationForTesting {
class NONE extends Throwable {
private NONE() {
}
private static final long serialVersionUID = 1L;
}
Class<? extends Throwable> expected() default NONE.class;
}
|
package com.expense.calculation.utils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class DateUtil {
public static final String DATE_FORMAT = "dd-MM-yyyy";
public static String getCurrentDate(){
return DateTime.now().toString(DATE_FORMAT);
}
public static ArrayList<String> getCurrentWeeksDates(){
ArrayList<String> dates = new ArrayList<>();
LocalDate now = new LocalDate();
for (int day = DateTimeConstants.MONDAY; day <= DateTimeConstants.SUNDAY; day++){
LocalDate localDate = now.withDayOfWeek(day);
dates.add(getFormattedDate(localDate, DATE_FORMAT));
}
return dates;
}
public static String currentMonthOfYear() {
String date = DateTime.now().toString(DATE_FORMAT);
String[] split = date.split("-");
return split[1] + "-" + split[2];
}
public static String getDayName(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = null;
try { date = formatter.parse(dateString); }
catch (ParseException e) {}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US);
}
private static String getFormattedDate(LocalDate date, String format){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(date.toDate());
}
}
|
/*
* Copyright 2015 floragunn UG (haftungsbeschränkt)
* Copyright 2015 PetalMD
*
* 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.petalmd.armor.http;
import com.petalmd.armor.authentication.User;
public interface SessionStore {
Session getSession(String id);
Session createSession(User authenticatedUser);
}
|
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.hd.BhApplyMaterial.service;
import me.zhengjie.hd.BhApplyMaterial.domain.BhApplyMaterial;
import me.zhengjie.hd.BhApplyMaterial.service.dto.BhApplyMaterialDto;
import me.zhengjie.hd.BhApplyMaterial.service.dto.BhApplyMaterialQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://el-admin.vip
* @description 服务接口
* @author fb
* @date 2020-08-11
**/
public interface BhApplyMaterialService {
/**
* 查询数据分页
* @param criteria 条件
* @param pageable 分页参数
* @return Map<String,Object>
*/
Map<String,Object> queryAll(BhApplyMaterialQueryCriteria criteria, Pageable pageable);
/**
* 查询所有数据不分页
* @param criteria 条件参数
* @return List<BhApplyMaterialDto>
*/
List<BhApplyMaterialDto> queryAll(BhApplyMaterialQueryCriteria criteria);
/**
* 根据ID查询
* @param id ID
* @return BhApplyMaterialDto
*/
BhApplyMaterialDto findById(String id);
/**
* 创建
* @param resources /
* @return BhApplyMaterialDto
*/
BhApplyMaterialDto create(BhApplyMaterial resources);
/**
* 编辑
* @param resources /
*/
void update(BhApplyMaterial resources);
/**
* 多选删除
* @param ids /
*/
void deleteAll(String[] ids);
/**
* 导出数据
* @param all 待导出的数据
* @param response /
* @throws IOException /
*/
void download(List<BhApplyMaterialDto> all, HttpServletResponse response) throws IOException;
}
|
/*
* Copyright 2020 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
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycenter/v1beta1/securitycenter_service.proto
package com.google.cloud.securitycenter.v1beta1;
public final class SecuritycenterService {
private SecuritycenterService() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_CreateFindingRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_CreateFindingRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_CreateSourceRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_CreateSourceRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_GetOrganizationSettingsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_GetOrganizationSettingsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_GetSourceRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_GetSourceRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_PropertiesEntry_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_PropertiesEntry_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_ListAssetsResult_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_ListAssetsResult_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_RunAssetDiscoveryRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_RunAssetDiscoveryRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_UpdateFindingRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_UpdateFindingRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_UpdateOrganizationSettingsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_UpdateOrganizationSettingsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_UpdateSourceRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_UpdateSourceRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_securitycenter_v1beta1_UpdateSecurityMarksRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_securitycenter_v1beta1_UpdateSecurityMarksRequest_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n@google/cloud/securitycenter/v1beta1/se"
+ "curitycenter_service.proto\022#google.cloud"
+ ".securitycenter.v1beta1\032\034google/api/anno"
+ "tations.proto\032\027google/api/client.proto\032\037"
+ "google/api/field_behavior.proto\032\031google/"
+ "api/resource.proto\032/google/cloud/securit"
+ "ycenter/v1beta1/asset.proto\0321google/clou"
+ "d/securitycenter/v1beta1/finding.proto\032?"
+ "google/cloud/securitycenter/v1beta1/orga"
+ "nization_settings.proto\0328google/cloud/se"
+ "curitycenter/v1beta1/security_marks.prot"
+ "o\0320google/cloud/securitycenter/v1beta1/s"
+ "ource.proto\032\036google/iam/v1/iam_policy.pr"
+ "oto\032\032google/iam/v1/policy.proto\032#google/"
+ "longrunning/operations.proto\032\036google/pro"
+ "tobuf/duration.proto\032\033google/protobuf/em"
+ "pty.proto\032 google/protobuf/field_mask.pr"
+ "oto\032\034google/protobuf/struct.proto\032\037googl"
+ "e/protobuf/timestamp.proto\"\261\001\n\024CreateFin"
+ "dingRequest\022<\n\006parent\030\001 \001(\tB,\340A\002\372A&\n$sec"
+ "uritycenter.googleapis.com/Source\022\027\n\nfin"
+ "ding_id\030\002 \001(\tB\003\340A\002\022B\n\007finding\030\003 \001(\0132,.go"
+ "ogle.cloud.securitycenter.v1beta1.Findin"
+ "gB\003\340A\002\"\241\001\n\023CreateSourceRequest\022H\n\006parent"
+ "\030\001 \001(\tB8\340A\002\372A2\n0cloudresourcemanager.goo"
+ "gleapis.com/Organization\022@\n\006source\030\002 \001(\013"
+ "2+.google.cloud.securitycenter.v1beta1.S"
+ "ourceB\003\340A\002\"j\n\036GetOrganizationSettingsReq"
+ "uest\022H\n\004name\030\001 \001(\tB:\340A\002\372A4\n2securitycent"
+ "er.googleapis.com/OrganizationSettings\"N"
+ "\n\020GetSourceRequest\022:\n\004name\030\001 \001(\tB,\340A\002\372A&"
+ "\n$securitycenter.googleapis.com/Source\"\220"
+ "\002\n\022GroupAssetsRequest\022H\n\006parent\030\001 \001(\tB8\340"
+ "A\002\372A2\n0cloudresourcemanager.googleapis.c"
+ "om/Organization\022\016\n\006filter\030\002 \001(\t\022\025\n\010group"
+ "_by\030\003 \001(\tB\003\340A\002\0223\n\020compare_duration\030\004 \001(\013"
+ "2\031.google.protobuf.Duration\022-\n\tread_time"
+ "\030\005 \001(\0132\032.google.protobuf.Timestamp\022\022\n\npa"
+ "ge_token\030\007 \001(\t\022\021\n\tpage_size\030\010 \001(\005\"\251\001\n\023Gr"
+ "oupAssetsResponse\022J\n\020group_by_results\030\001 "
+ "\003(\01320.google.cloud.securitycenter.v1beta"
+ "1.GroupResult\022-\n\tread_time\030\002 \001(\0132\032.googl"
+ "e.protobuf.Timestamp\022\027\n\017next_page_token\030"
+ "\003 \001(\t\"\321\001\n\024GroupFindingsRequest\022<\n\006parent"
+ "\030\001 \001(\tB,\340A\002\372A&\n$securitycenter.googleapi"
+ "s.com/Source\022\016\n\006filter\030\002 \001(\t\022\025\n\010group_by"
+ "\030\003 \001(\tB\003\340A\002\022-\n\tread_time\030\004 \001(\0132\032.google."
+ "protobuf.Timestamp\022\022\n\npage_token\030\005 \001(\t\022\021"
+ "\n\tpage_size\030\006 \001(\005\"\253\001\n\025GroupFindingsRespo"
+ "nse\022J\n\020group_by_results\030\001 \003(\01320.google.c"
+ "loud.securitycenter.v1beta1.GroupResult\022"
+ "-\n\tread_time\030\002 \001(\0132\032.google.protobuf.Tim"
+ "estamp\022\027\n\017next_page_token\030\003 \001(\t\"\275\001\n\013Grou"
+ "pResult\022T\n\nproperties\030\001 \003(\0132@.google.clo"
+ "ud.securitycenter.v1beta1.GroupResult.Pr"
+ "opertiesEntry\022\r\n\005count\030\002 \001(\003\032I\n\017Properti"
+ "esEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.go"
+ "ogle.protobuf.Value:\0028\001\"\205\001\n\022ListSourcesR"
+ "equest\022H\n\006parent\030\001 \001(\tB8\340A\002\372A2\n0cloudres"
+ "ourcemanager.googleapis.com/Organization"
+ "\022\022\n\npage_token\030\002 \001(\t\022\021\n\tpage_size\030\007 \001(\005\""
+ "l\n\023ListSourcesResponse\022<\n\007sources\030\001 \003(\0132"
+ "+.google.cloud.securitycenter.v1beta1.So"
+ "urce\022\027\n\017next_page_token\030\002 \001(\t\"\277\002\n\021ListAs"
+ "setsRequest\022H\n\006parent\030\001 \001(\tB8\340A\002\372A2\n0clo"
+ "udresourcemanager.googleapis.com/Organiz"
+ "ation\022\016\n\006filter\030\002 \001(\t\022\020\n\010order_by\030\003 \001(\t\022"
+ "-\n\tread_time\030\004 \001(\0132\032.google.protobuf.Tim"
+ "estamp\0223\n\020compare_duration\030\005 \001(\0132\031.googl"
+ "e.protobuf.Duration\0223\n\nfield_mask\030\007 \001(\0132"
+ "\032.google.protobuf.FieldMaskB\003\340A\001\022\022\n\npage"
+ "_token\030\010 \001(\t\022\021\n\tpage_size\030\t \001(\005\"\326\003\n\022List"
+ "AssetsResponse\022e\n\023list_assets_results\030\001 "
+ "\003(\0132H.google.cloud.securitycenter.v1beta"
+ "1.ListAssetsResponse.ListAssetsResult\022-\n"
+ "\tread_time\030\002 \001(\0132\032.google.protobuf.Times"
+ "tamp\022\027\n\017next_page_token\030\003 \001(\t\022\022\n\ntotal_s"
+ "ize\030\004 \001(\005\032\374\001\n\020ListAssetsResult\0229\n\005asset\030"
+ "\001 \001(\0132*.google.cloud.securitycenter.v1be"
+ "ta1.Asset\022]\n\005state\030\002 \001(\0162N.google.cloud."
+ "securitycenter.v1beta1.ListAssetsRespons"
+ "e.ListAssetsResult.State\"N\n\005State\022\025\n\021STA"
+ "TE_UNSPECIFIED\020\000\022\n\n\006UNUSED\020\001\022\t\n\005ADDED\020\002\022"
+ "\013\n\007REMOVED\020\003\022\n\n\006ACTIVE\020\004\"\200\002\n\023ListFinding"
+ "sRequest\022<\n\006parent\030\001 \001(\tB,\340A\002\372A&\n$securi"
+ "tycenter.googleapis.com/Source\022\016\n\006filter"
+ "\030\002 \001(\t\022\020\n\010order_by\030\003 \001(\t\022-\n\tread_time\030\004 "
+ "\001(\0132\032.google.protobuf.Timestamp\0223\n\nfield"
+ "_mask\030\005 \001(\0132\032.google.protobuf.FieldMaskB"
+ "\003\340A\001\022\022\n\npage_token\030\006 \001(\t\022\021\n\tpage_size\030\007 "
+ "\001(\005\"\262\001\n\024ListFindingsResponse\022>\n\010findings"
+ "\030\001 \003(\0132,.google.cloud.securitycenter.v1b"
+ "eta1.Finding\022-\n\tread_time\030\002 \001(\0132\032.google"
+ ".protobuf.Timestamp\022\027\n\017next_page_token\030\003"
+ " \001(\t\022\022\n\ntotal_size\030\004 \001(\005\"\322\001\n\026SetFindingS"
+ "tateRequest\022;\n\004name\030\001 \001(\tB-\340A\002\372A\'\n%secur"
+ "itycenter.googleapis.com/Finding\022F\n\005stat"
+ "e\030\002 \001(\01622.google.cloud.securitycenter.v1"
+ "beta1.Finding.StateB\003\340A\002\0223\n\nstart_time\030\003"
+ " \001(\0132\032.google.protobuf.TimestampB\003\340A\002\"d\n"
+ "\030RunAssetDiscoveryRequest\022H\n\006parent\030\001 \001("
+ "\tB8\340A\002\372A2\n0cloudresourcemanager.googleap"
+ "is.com/Organization\"\213\001\n\024UpdateFindingReq"
+ "uest\022B\n\007finding\030\001 \001(\0132,.google.cloud.sec"
+ "uritycenter.v1beta1.FindingB\003\340A\002\022/\n\013upda"
+ "te_mask\030\002 \001(\0132\032.google.protobuf.FieldMas"
+ "k\"\263\001\n!UpdateOrganizationSettingsRequest\022"
+ "]\n\025organization_settings\030\001 \001(\01329.google."
+ "cloud.securitycenter.v1beta1.Organizatio"
+ "nSettingsB\003\340A\002\022/\n\013update_mask\030\002 \001(\0132\032.go"
+ "ogle.protobuf.FieldMask\"\210\001\n\023UpdateSource"
+ "Request\022@\n\006source\030\001 \001(\0132+.google.cloud.s"
+ "ecuritycenter.v1beta1.SourceB\003\340A\002\022/\n\013upd"
+ "ate_mask\030\002 \001(\0132\032.google.protobuf.FieldMa"
+ "sk\"\316\001\n\032UpdateSecurityMarksRequest\022O\n\016sec"
+ "urity_marks\030\001 \001(\01322.google.cloud.securit"
+ "ycenter.v1beta1.SecurityMarksB\003\340A\002\022/\n\013up"
+ "date_mask\030\002 \001(\0132\032.google.protobuf.FieldM"
+ "ask\022.\n\nstart_time\030\003 \001(\0132\032.google.protobu"
+ "f.Timestamp2\353\036\n\016SecurityCenter\022\300\001\n\014Creat"
+ "eSource\0228.google.cloud.securitycenter.v1"
+ "beta1.CreateSourceRequest\032+.google.cloud"
+ ".securitycenter.v1beta1.Source\"I\202\323\344\223\0023\")"
+ "/v1beta1/{parent=organizations/*}/source"
+ "s:\006source\332A\rparent,source\022\333\001\n\rCreateFind"
+ "ing\0229.google.cloud.securitycenter.v1beta"
+ "1.CreateFindingRequest\032,.google.cloud.se"
+ "curitycenter.v1beta1.Finding\"a\202\323\344\223\002?\"4/v"
+ "1beta1/{parent=organizations/*/sources/*"
+ "}/findings:\007finding\332A\031parent,finding_id,"
+ "finding\022\233\001\n\014GetIamPolicy\022\".google.iam.v1"
+ ".GetIamPolicyRequest\032\025.google.iam.v1.Pol"
+ "icy\"P\202\323\344\223\002?\":/v1beta1/{resource=organiza"
+ "tions/*/sources/*}:getIamPolicy:\001*\332A\010res"
+ "ource\022\336\001\n\027GetOrganizationSettings\022C.goog"
+ "le.cloud.securitycenter.v1beta1.GetOrgan"
+ "izationSettingsRequest\0329.google.cloud.se"
+ "curitycenter.v1beta1.OrganizationSetting"
+ "s\"C\202\323\344\223\0026\0224/v1beta1/{name=organizations/"
+ "*/organizationSettings}\332A\004name\022\251\001\n\tGetSo"
+ "urce\0225.google.cloud.securitycenter.v1bet"
+ "a1.GetSourceRequest\032+.google.cloud.secur"
+ "itycenter.v1beta1.Source\"8\202\323\344\223\002+\022)/v1bet"
+ "a1/{name=organizations/*/sources/*}\332A\004na"
+ "me\022\273\001\n\013GroupAssets\0227.google.cloud.securi"
+ "tycenter.v1beta1.GroupAssetsRequest\0328.go"
+ "ogle.cloud.securitycenter.v1beta1.GroupA"
+ "ssetsResponse\"9\202\323\344\223\0023\"./v1beta1/{parent="
+ "organizations/*}/assets:group:\001*\022\337\001\n\rGro"
+ "upFindings\0229.google.cloud.securitycenter"
+ ".v1beta1.GroupFindingsRequest\032:.google.c"
+ "loud.securitycenter.v1beta1.GroupFinding"
+ "sResponse\"W\202\323\344\223\002?\":/v1beta1/{parent=orga"
+ "nizations/*/sources/*}/findings:group:\001*"
+ "\332A\017parent,group_by\022\257\001\n\nListAssets\0226.goog"
+ "le.cloud.securitycenter.v1beta1.ListAsse"
+ "tsRequest\0327.google.cloud.securitycenter."
+ "v1beta1.ListAssetsResponse\"0\202\323\344\223\002*\022(/v1b"
+ "eta1/{parent=organizations/*}/assets\022\301\001\n"
+ "\014ListFindings\0228.google.cloud.securitycen"
+ "ter.v1beta1.ListFindingsRequest\0329.google"
+ ".cloud.securitycenter.v1beta1.ListFindin"
+ "gsResponse\"<\202\323\344\223\0026\0224/v1beta1/{parent=org"
+ "anizations/*/sources/*}/findings\022\274\001\n\013Lis"
+ "tSources\0227.google.cloud.securitycenter.v"
+ "1beta1.ListSourcesRequest\0328.google.cloud"
+ ".securitycenter.v1beta1.ListSourcesRespo"
+ "nse\":\202\323\344\223\002+\022)/v1beta1/{parent=organizati"
+ "ons/*}/sources\332A\006parent\022\355\001\n\021RunAssetDisc"
+ "overy\022=.google.cloud.securitycenter.v1be"
+ "ta1.RunAssetDiscoveryRequest\032\035.google.lo"
+ "ngrunning.Operation\"z\202\323\344\223\002:\"5/v1beta1/{p"
+ "arent=organizations/*}/assets:runDiscove"
+ "ry:\001*\332A\006parent\312A.\n\025google.protobuf.Empty"
+ "\022\025google.protobuf.Empty\022\336\001\n\017SetFindingSt"
+ "ate\022;.google.cloud.securitycenter.v1beta"
+ "1.SetFindingStateRequest\032,.google.cloud."
+ "securitycenter.v1beta1.Finding\"`\202\323\344\223\002B\"="
+ "/v1beta1/{name=organizations/*/sources/*"
+ "/findings/*}:setState:\001*\332A\025name,state,st"
+ "art_time\022\242\001\n\014SetIamPolicy\022\".google.iam.v"
+ "1.SetIamPolicyRequest\032\025.google.iam.v1.Po"
+ "licy\"W\202\323\344\223\002?\":/v1beta1/{resource=organiz"
+ "ations/*/sources/*}:setIamPolicy:\001*\332A\017re"
+ "source,policy\022\315\001\n\022TestIamPermissions\022(.g"
+ "oogle.iam.v1.TestIamPermissionsRequest\032)"
+ ".google.iam.v1.TestIamPermissionsRespons"
+ "e\"b\202\323\344\223\002E\"@/v1beta1/{resource=organizati"
+ "ons/*/sources/*}:testIamPermissions:\001*\332A"
+ "\024resource,permissions\022\321\001\n\rUpdateFinding\022"
+ "9.google.cloud.securitycenter.v1beta1.Up"
+ "dateFindingRequest\032,.google.cloud.securi"
+ "tycenter.v1beta1.Finding\"W\202\323\344\223\002G2</v1bet"
+ "a1/{finding.name=organizations/*/sources"
+ "/*/findings/*}:\007finding\332A\007finding\022\243\002\n\032Up"
+ "dateOrganizationSettings\022F.google.cloud."
+ "securitycenter.v1beta1.UpdateOrganizatio"
+ "nSettingsRequest\0329.google.cloud.security"
+ "center.v1beta1.OrganizationSettings\"\201\001\202\323"
+ "\344\223\002c2J/v1beta1/{organization_settings.na"
+ "me=organizations/*/organizationSettings}"
+ ":\025organization_settings\332A\025organization_s"
+ "ettings\022\300\001\n\014UpdateSource\0228.google.cloud."
+ "securitycenter.v1beta1.UpdateSourceReque"
+ "st\032+.google.cloud.securitycenter.v1beta1"
+ ".Source\"I\202\323\344\223\002:20/v1beta1/{source.name=o"
+ "rganizations/*/sources/*}:\006source\332A\006sour"
+ "ce\022\341\002\n\023UpdateSecurityMarks\022?.google.clou"
+ "d.securitycenter.v1beta1.UpdateSecurityM"
+ "arksRequest\0322.google.cloud.securitycente"
+ "r.v1beta1.SecurityMarks\"\324\001\202\323\344\223\002\274\0012E/v1be"
+ "ta1/{security_marks.name=organizations/*"
+ "/assets/*/securityMarks}:\016security_marks"
+ "Zc2Q/v1beta1/{security_marks.name=organi"
+ "zations/*/sources/*/findings/*/securityM"
+ "arks}:\016security_marks\332A\016security_marks\032Q"
+ "\312A\035securitycenter.googleapis.com\322A.https"
+ "://www.googleapis.com/auth/cloud-platfor"
+ "mB~\n\'com.google.cloud.securitycenter.v1b"
+ "eta1P\001ZQgoogle.golang.org/genproto/googl"
+ "eapis/cloud/securitycenter/v1beta1;secur"
+ "itycenterb\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.cloud.securitycenter.v1beta1.AssetOuterClass.getDescriptor(),
com.google.cloud.securitycenter.v1beta1.FindingOuterClass.getDescriptor(),
com.google.cloud.securitycenter.v1beta1.OrganizationSettingsOuterClass
.getDescriptor(),
com.google.cloud.securitycenter.v1beta1.SecurityMarksOuterClass.getDescriptor(),
com.google.cloud.securitycenter.v1beta1.SourceOuterClass.getDescriptor(),
com.google.iam.v1.IamPolicyProto.getDescriptor(),
com.google.iam.v1.PolicyProto.getDescriptor(),
com.google.longrunning.OperationsProto.getDescriptor(),
com.google.protobuf.DurationProto.getDescriptor(),
com.google.protobuf.EmptyProto.getDescriptor(),
com.google.protobuf.FieldMaskProto.getDescriptor(),
com.google.protobuf.StructProto.getDescriptor(),
com.google.protobuf.TimestampProto.getDescriptor(),
});
internal_static_google_cloud_securitycenter_v1beta1_CreateFindingRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_securitycenter_v1beta1_CreateFindingRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_CreateFindingRequest_descriptor,
new java.lang.String[] {
"Parent", "FindingId", "Finding",
});
internal_static_google_cloud_securitycenter_v1beta1_CreateSourceRequest_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_securitycenter_v1beta1_CreateSourceRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_CreateSourceRequest_descriptor,
new java.lang.String[] {
"Parent", "Source",
});
internal_static_google_cloud_securitycenter_v1beta1_GetOrganizationSettingsRequest_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_securitycenter_v1beta1_GetOrganizationSettingsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_GetOrganizationSettingsRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_securitycenter_v1beta1_GetSourceRequest_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_securitycenter_v1beta1_GetSourceRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_GetSourceRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsRequest_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsRequest_descriptor,
new java.lang.String[] {
"Parent", "Filter", "GroupBy", "CompareDuration", "ReadTime", "PageToken", "PageSize",
});
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsResponse_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_GroupAssetsResponse_descriptor,
new java.lang.String[] {
"GroupByResults", "ReadTime", "NextPageToken",
});
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsRequest_descriptor =
getDescriptor().getMessageTypes().get(6);
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsRequest_descriptor,
new java.lang.String[] {
"Parent", "Filter", "GroupBy", "ReadTime", "PageToken", "PageSize",
});
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsResponse_descriptor =
getDescriptor().getMessageTypes().get(7);
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_GroupFindingsResponse_descriptor,
new java.lang.String[] {
"GroupByResults", "ReadTime", "NextPageToken",
});
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_descriptor =
getDescriptor().getMessageTypes().get(8);
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_descriptor,
new java.lang.String[] {
"Properties", "Count",
});
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_PropertiesEntry_descriptor =
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_PropertiesEntry_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_GroupResult_PropertiesEntry_descriptor,
new java.lang.String[] {
"Key", "Value",
});
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesRequest_descriptor =
getDescriptor().getMessageTypes().get(9);
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesRequest_descriptor,
new java.lang.String[] {
"Parent", "PageToken", "PageSize",
});
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_descriptor =
getDescriptor().getMessageTypes().get(10);
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_descriptor,
new java.lang.String[] {
"Sources", "NextPageToken",
});
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsRequest_descriptor =
getDescriptor().getMessageTypes().get(11);
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsRequest_descriptor,
new java.lang.String[] {
"Parent",
"Filter",
"OrderBy",
"ReadTime",
"CompareDuration",
"FieldMask",
"PageToken",
"PageSize",
});
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_descriptor =
getDescriptor().getMessageTypes().get(12);
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_descriptor,
new java.lang.String[] {
"ListAssetsResults", "ReadTime", "NextPageToken", "TotalSize",
});
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_ListAssetsResult_descriptor =
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_ListAssetsResult_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_ListAssetsResponse_ListAssetsResult_descriptor,
new java.lang.String[] {
"Asset", "State",
});
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsRequest_descriptor =
getDescriptor().getMessageTypes().get(13);
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsRequest_descriptor,
new java.lang.String[] {
"Parent", "Filter", "OrderBy", "ReadTime", "FieldMask", "PageToken", "PageSize",
});
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsResponse_descriptor =
getDescriptor().getMessageTypes().get(14);
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_ListFindingsResponse_descriptor,
new java.lang.String[] {
"Findings", "ReadTime", "NextPageToken", "TotalSize",
});
internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_descriptor =
getDescriptor().getMessageTypes().get(15);
internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_SetFindingStateRequest_descriptor,
new java.lang.String[] {
"Name", "State", "StartTime",
});
internal_static_google_cloud_securitycenter_v1beta1_RunAssetDiscoveryRequest_descriptor =
getDescriptor().getMessageTypes().get(16);
internal_static_google_cloud_securitycenter_v1beta1_RunAssetDiscoveryRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_RunAssetDiscoveryRequest_descriptor,
new java.lang.String[] {
"Parent",
});
internal_static_google_cloud_securitycenter_v1beta1_UpdateFindingRequest_descriptor =
getDescriptor().getMessageTypes().get(17);
internal_static_google_cloud_securitycenter_v1beta1_UpdateFindingRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_UpdateFindingRequest_descriptor,
new java.lang.String[] {
"Finding", "UpdateMask",
});
internal_static_google_cloud_securitycenter_v1beta1_UpdateOrganizationSettingsRequest_descriptor =
getDescriptor().getMessageTypes().get(18);
internal_static_google_cloud_securitycenter_v1beta1_UpdateOrganizationSettingsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_UpdateOrganizationSettingsRequest_descriptor,
new java.lang.String[] {
"OrganizationSettings", "UpdateMask",
});
internal_static_google_cloud_securitycenter_v1beta1_UpdateSourceRequest_descriptor =
getDescriptor().getMessageTypes().get(19);
internal_static_google_cloud_securitycenter_v1beta1_UpdateSourceRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_UpdateSourceRequest_descriptor,
new java.lang.String[] {
"Source", "UpdateMask",
});
internal_static_google_cloud_securitycenter_v1beta1_UpdateSecurityMarksRequest_descriptor =
getDescriptor().getMessageTypes().get(20);
internal_static_google_cloud_securitycenter_v1beta1_UpdateSecurityMarksRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_securitycenter_v1beta1_UpdateSecurityMarksRequest_descriptor,
new java.lang.String[] {
"SecurityMarks", "UpdateMask", "StartTime",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.methodSignature);
registry.add(com.google.api.ClientProto.oauthScopes);
registry.add(com.google.api.ResourceProto.resourceReference);
registry.add(com.google.longrunning.OperationsProto.operationInfo);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.AnnotationsProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.cloud.securitycenter.v1beta1.AssetOuterClass.getDescriptor();
com.google.cloud.securitycenter.v1beta1.FindingOuterClass.getDescriptor();
com.google.cloud.securitycenter.v1beta1.OrganizationSettingsOuterClass.getDescriptor();
com.google.cloud.securitycenter.v1beta1.SecurityMarksOuterClass.getDescriptor();
com.google.cloud.securitycenter.v1beta1.SourceOuterClass.getDescriptor();
com.google.iam.v1.IamPolicyProto.getDescriptor();
com.google.iam.v1.PolicyProto.getDescriptor();
com.google.longrunning.OperationsProto.getDescriptor();
com.google.protobuf.DurationProto.getDescriptor();
com.google.protobuf.EmptyProto.getDescriptor();
com.google.protobuf.FieldMaskProto.getDescriptor();
com.google.protobuf.StructProto.getDescriptor();
com.google.protobuf.TimestampProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
package cc.bugcat.catserver.scanner;
import cc.bugcat.catface.utils.CatToosUtil;
import cc.bugcat.catserver.annotation.CatServer;
import cc.bugcat.catserver.annotation.EnableCatServer;
import cc.bugcat.catserver.spi.CatInterceptor;
import cc.bugcat.catserver.utils.CatServerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import java.util.HashSet;
import java.util.Set;
/**
* 扫描自定义注解
*
* 注意,在装载此类时,其生命周期早于Spring容器,任何自动注入注解都是无效的!包括@Autowired @Resource @Value
*
* @author: bugcat
* */
public class CatServerScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware{
private static Logger log = LoggerFactory.getLogger(CatServerScannerRegistrar.class);
//资源加载器
private ResourceLoader resourceLoader;
//所有被@CatServer标记的类
private Set<Object> servers = new HashSet<>();
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* 注册扫描事件
* */
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
log.info("catServer 服务端启用...");
AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(EnableCatServer.class.getName()));
String[] pkgs = CatToosUtil.scanPackages(metadata, annoAttrs, "value");
BeanDefinitionBuilder catServerUtil = BeanDefinitionBuilder.genericBeanDefinition(CatServerUtil.class);
String catServerUtilBeanName = CatToosUtil.uncapitalize(CatServerUtil.class.getSimpleName());
registry.registerBeanDefinition(catServerUtilBeanName, catServerUtil.getBeanDefinition());
//扫描所有的 CatInterceptor 子类
ClassPathBeanDefinitionScanner interceptorScanner = new ClassPathBeanDefinitionScanner(registry);
interceptorScanner.setResourceLoader(resourceLoader);
interceptorScanner.addIncludeFilter(CatToosUtil.typeChildrenFilter(CatInterceptor.class));
interceptorScanner.scan(pkgs);
Class<?>[] classes = annoAttrs.getClassArray("classes");
if( classes.length > 0 ){
for ( Class<?> clazz : classes ){
CatServer server = clazz.getAnnotation(CatServer.class);
String beanName = CatToosUtil.defaultIfBlank(server.value(), CatToosUtil.uncapitalize(clazz.getSimpleName()));
servers.add(beanName);
}
}
// 定义扫描对象
CatServerScanner scanner = new CatServerScanner(servers, registry);
scanner.setResourceLoader(resourceLoader);
scanner.addIncludeFilter(new AnnotationTypeFilter(CatServer.class)); //筛选带有@CatServer注解的类
scanner.scan(pkgs);
log.info("catServer 服务端数量:" + servers.size() );
BeanDefinitionBuilder catServerInitBean = BeanDefinitionBuilder.genericBeanDefinition(CatServerInitBean.class);
catServerInitBean.addConstructorArgValue(servers);
registry.registerBeanDefinition(CatToosUtil.uncapitalize(CatServerInitBean.class.getSimpleName()), catServerInitBean.getBeanDefinition());
try {
// swagger扫描
Class swagger = Class.forName("cc.bugcat.catserver.utils.CatSwaggerScanner");
BeanDefinitionBuilder catProvider = BeanDefinitionBuilder.genericBeanDefinition(swagger);
catProvider.getBeanDefinition().setPrimary(true);
registry.registerBeanDefinition(CatToosUtil.uncapitalize(swagger.getSimpleName()), catProvider.getBeanDefinition());
} catch ( Exception e ) {
}
}
/**
* 自定义扫描
* */
private static class CatServerScanner extends ClassPathBeanDefinitionScanner{
private Set<Object> servers;
public CatServerScanner(Set<Object> servers, BeanDefinitionRegistry registry) {
super(registry);
this.servers = servers;
}
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
boolean isCandidate = false;
AnnotationMetadata metadata = beanDefinition.getMetadata();
if (metadata.isIndependent()) {
if ( !metadata.isAnnotation() && metadata.hasAnnotation(CatServer.class.getName())) {
isCandidate = true;
}
}
return isCandidate;
}
@Override
protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
super.postProcessBeanDefinition(beanDefinition, beanName);
servers.add(beanDefinition.getBeanClassName());
}
}
}
|
/*
* aca-py client
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v0.7.0-pre2
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.hyperledger.acy_py.generated.model;
import com.google.gson.annotations.SerializedName;
/**
* RawEncoded
*/
@lombok.Data
@lombok.AllArgsConstructor
@lombok.NoArgsConstructor
@lombok.Builder
public class RawEncoded {
public static final String SERIALIZED_NAME_ENCODED = "encoded";
@SerializedName(SERIALIZED_NAME_ENCODED)
private String encoded;
public static final String SERIALIZED_NAME_RAW = "raw";
@SerializedName(SERIALIZED_NAME_RAW)
private String raw;
}
|
package com.github.adityagarde.microservices.currencyexchangeservice;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
@Entity
public class CurrencyExchange {
@Id
private Long id;
@Column(name = "currency_from")
private String from;
@Column(name = "currency_to")
private String to;
private BigDecimal conversionMultiple;
private String environment;
public CurrencyExchange() {
}
public CurrencyExchange(Long id, String from, String to, BigDecimal conversionMultiple) {
this.id = id;
this.from = from;
this.to = to;
this.conversionMultiple = conversionMultiple;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public BigDecimal getConversionMultiple() {
return conversionMultiple;
}
public void setConversionMultiple(BigDecimal conversionMultiple) {
this.conversionMultiple = conversionMultiple;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
}
|
package org.springblade.anbiao.muban.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @program: SafetyStandards
* @description: 模板配置表
* @author: 呵呵哒
**/
@Data
@TableName("anbiao_muban_map")
@ApiModel(value = "anbiao_muban_map对象", description = "anbiao_muban_map对象")
public class MubanMap implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@ApiModelProperty(value = "id")
@TableId(value = "id",type = IdType.UUID)
private String id;
/**
* 数据表字段
*/
@ApiModelProperty(value = "数据表字段")
private String shujubiaoziduan;
/**
* 实际字段
*/
@ApiModelProperty(value = "实际字段")
private String shijiziduan;
/**
* 字段含义
*/
@ApiModelProperty(value = "字段含义")
private String label;
/**
* 表单参数
*/
@ApiModelProperty(value = "表单参数")
private String biaodancanshu;
/**
* 是否删除
*/
@ApiModelProperty(value = "是否删除")
private Integer isdeleted;
/**
* 表名
*/
@ApiModelProperty(value = "表名")
private String tableName;
}
|
package com.mariadb.todo.repositories;
import com.mariadb.todo.models.Task;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
// Registered as a Spring Repository (Component)
// Repository = a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects
public interface TasksRepository extends ReactiveCrudRepository<Task, Integer> {
}
|
package seedu.address.ui;
import java.util.Comparator;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.address.model.person.Person;
/**
* An UI component that displays information of a {@code Person}.
*/
public class PersonCard extends UiPart<Region> {
private static final String FXML = "PersonListCard.fxml";
/**
* Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX.
* As a consequence, UI elements' variable names cannot be set to such keywords
* or an exception will be thrown by JavaFX during runtime.
*
* @see <a href="https://github.com/se-edu/addressbook-level4/issues/336">The issue on AddressBook level 4</a>
*/
public final Person person;
@FXML
private HBox cardPane;
@FXML
private Label name;
@FXML
private Label id;
@FXML
private Label phone;
@FXML
private Label email;
@FXML
private Label teleHandle;
@FXML
private FlowPane tags;
@FXML
private Label remark;
@FXML
private FlowPane moduleCodes;
/**
* Creates a {@code PersonCode} with the given {@code Person} and index to display.
*/
public PersonCard(Person person, int displayedIndex) {
super(FXML);
this.person = person;
id.setText(displayedIndex + ". ");
name.setText(person.getName().fullName);
email.setText(person.getEmail().value);
remark.setText(person.getRemark().value);
person.getModuleCodes().stream()
.sorted(Comparator.comparing(moduleCode -> moduleCode.value))
.forEach(moduleCode -> moduleCodes.getChildren().add(new Label(moduleCode.value)));
phone.setText(person.getPhone().value);
teleHandle.setText(person.getTeleHandle().value);
person.getModuleCodes().stream()
.sorted(Comparator.comparing(moduleCode -> moduleCode.value))
.map(moduleCode -> moduleCode.tags)
.forEach(t -> t.forEach(tag -> tags.getChildren().add(new Label(tag.tagName))));
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (other == this) {
return true;
}
// instanceof handles nulls
if (!(other instanceof PersonCard)) {
return false;
}
// state check
PersonCard card = (PersonCard) other;
return id.getText().equals(card.id.getText())
&& person.equals(card.person);
}
}
|
package it.mgt.util.json2jpa.test.property;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import it.mgt.util.json2jpa.Json2Jpa;
import it.mgt.util.json2jpa.Json2JpaFactory;
import it.mgt.util.json2jpa.test.config.SpringContext;
import it.mgt.util.json2jpa.test.config.StandaloneDataConfig;
import it.mgt.util.json2jpa.test.property.component.PropertyHelper;
import it.mgt.util.json2jpa.test.property.entity.PropertyBook;
import it.mgt.util.json2jpa.test.property.entity.PropertyBookseller;
import it.mgt.util.json2jpa.test.property.entity.PropertyBookstore;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( classes = {StandaloneDataConfig.class, SpringContext.class })
public class RemoveOnOrphanOneToMany {
private static final Logger logger = LoggerFactory.getLogger(RemoveOnOrphanOneToMany.class);
@PersistenceContext
private EntityManager em;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private Json2JpaFactory json2JpaFactory;
@Autowired
private PropertyHelper helper;
@Before
@Transactional
public void before() {
helper.initialize();
}
@Test
@Transactional
public void test() {
logger.info("Testing remove on orphan one-to-many");
List<PropertyBookstore> stores = em.createNamedQuery("PropertyBookstore.findAll", PropertyBookstore.class)
.getResultList();
List<PropertyBookseller> sellers = em.createNamedQuery("PropertyBookseller.findAll", PropertyBookseller.class)
.getResultList();
List<PropertyBook> books = em.createNamedQuery("PropertyBook.findAll", PropertyBook.class)
.getResultList();
PropertyBookstore mousetonStore = em.createNamedQuery("PropertyBookstore.findByName", PropertyBookstore.class)
.setParameter("name", "Mouseton Store")
.getSingleResult();
int initialEmployeesCount = mousetonStore.getEmployees().size();
int initialStoresCount = stores.size();
int initialSellersCount = sellers.size();
int initialBooksCount = books.size();
ObjectNode json = objectMapper.createObjectNode();
ArrayNode employeesJson = json.putArray("employees");
for (PropertyBookseller s : mousetonStore.getEmployees())
if (mousetonStore.getDirector().equals(s))
continue;
else
employeesJson.add(s.getId());
json.putNull("director");
Json2Jpa json2Jpa = json2JpaFactory.build();
json2Jpa.merge(mousetonStore, json);
em.flush();
em.clear();
mousetonStore = em.createNamedQuery("PropertyBookstore.findByName", PropertyBookstore.class)
.setParameter("name", "Mouseton Store")
.getSingleResult();
PropertyBookseller mickeyMouse = em.createNamedQuery("PropertyBookseller.findByName", PropertyBookseller.class)
.setParameter("firstName", "Mickey")
.setParameter("lastName", "Mouse")
.getResultList()
.stream()
.findFirst()
.orElse(null);
stores = em.createNamedQuery("PropertyBookstore.findAll", PropertyBookstore.class)
.getResultList();
sellers = em.createNamedQuery("PropertyBookseller.findAll", PropertyBookseller.class)
.getResultList();
books = em.createNamedQuery("PropertyBook.findAll", PropertyBook.class)
.getResultList();
Assert.assertNull(mousetonStore.getDirector());
Assert.assertNull(mickeyMouse);
Assert.assertEquals(initialEmployeesCount - 1, mousetonStore.getEmployees().size());
Assert.assertEquals(initialStoresCount, stores.size());
Assert.assertEquals(initialSellersCount - 1, sellers.size());
Assert.assertEquals(initialBooksCount, books.size());
}
}
|
package com.nightingale.model.constraints.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.nightingale.model.constraints.UniqueUserEmail;
import com.nightingale.repository.UserRepository;
@Component
public class UniqueUserEmailValidator implements ConstraintValidator<UniqueUserEmail, String> {
@Autowired
private UserRepository userRepository;
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return userRepository.findByEmail(value) == null;
}
@Override
public void initialize(UniqueUserEmail constraintAnnotation) {
}
}
|
/*
* 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.shardingsphere.proxy.backend.communication;
import lombok.SneakyThrows;
import org.apache.shardingsphere.infra.binder.statement.SQLStatementContext;
import org.apache.shardingsphere.infra.config.persist.DistMetaDataPersistService;
import org.apache.shardingsphere.infra.config.properties.ConfigurationProperties;
import org.apache.shardingsphere.infra.context.metadata.MetaDataContexts;
import org.apache.shardingsphere.infra.context.metadata.impl.StandardMetaDataContexts;
import org.apache.shardingsphere.infra.database.type.dialect.H2DatabaseType;
import org.apache.shardingsphere.infra.executor.kernel.ExecutorEngine;
import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResult;
import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResultMetaData;
import org.apache.shardingsphere.infra.merge.result.impl.memory.MemoryMergedResult;
import org.apache.shardingsphere.infra.merge.result.impl.memory.MemoryQueryResultRow;
import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
import org.apache.shardingsphere.infra.metadata.rule.ShardingSphereRuleMetaData;
import org.apache.shardingsphere.infra.metadata.schema.ShardingSphereSchema;
import org.apache.shardingsphere.infra.metadata.schema.model.ColumnMetaData;
import org.apache.shardingsphere.infra.metadata.schema.model.IndexMetaData;
import org.apache.shardingsphere.infra.metadata.schema.model.TableMetaData;
import org.apache.shardingsphere.infra.optimize.context.OptimizeContextFactory;
import org.apache.shardingsphere.infra.optimize.core.metadata.FederateSchemaMetadatas;
import org.apache.shardingsphere.infra.rule.ShardingSphereRule;
import org.apache.shardingsphere.proxy.backend.communication.jdbc.connection.BackendConnection;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.response.header.query.impl.QueryHeaderBuilder;
import org.apache.shardingsphere.sharding.rule.ShardingRule;
import org.apache.shardingsphere.transaction.context.impl.StandardTransactionContexts;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.FieldSetter;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public final class DatabaseCommunicationEngineTest {
@Mock
private BackendConnection backendConnection;
@Mock
private Statement statement;
@Mock
private ResultSet resultSet;
@Before
public void setUp() {
when(backendConnection.getSchemaName()).thenReturn("schema");
MetaDataContexts metaDataContexts = new StandardMetaDataContexts(mock(DistMetaDataPersistService.class), mockMetaDataMap(), mock(ShardingSphereRuleMetaData.class), mock(ExecutorEngine.class),
new ConfigurationProperties(new Properties()), mockOptimizeContextFactory());
ProxyContext.getInstance().init(metaDataContexts, new StandardTransactionContexts());
}
private Map<String, ShardingSphereMetaData> mockMetaDataMap() {
ShardingSphereMetaData result = mock(ShardingSphereMetaData.class, RETURNS_DEEP_STUBS);
when(result.getResource().getDatabaseType()).thenReturn(new H2DatabaseType());
when(result.getRuleMetaData().getRules()).thenReturn(Collections.emptyList());
return Collections.singletonMap("schema", result);
}
private OptimizeContextFactory mockOptimizeContextFactory() {
OptimizeContextFactory result = mock(OptimizeContextFactory.class, RETURNS_DEEP_STUBS);
when(result.getSchemaMetadatas()).thenReturn(new FederateSchemaMetadatas(Collections.emptyMap()));
return result;
}
@Test
public void assertBinaryProtocolQueryHeader() throws SQLException, NoSuchFieldException {
DatabaseCommunicationEngine engine =
DatabaseCommunicationEngineFactory.getInstance().newBinaryProtocolInstance(mock(SQLStatementContext.class), "schemaName", Collections.emptyList(), backendConnection);
assertNotNull(engine);
assertThat(engine, instanceOf(DatabaseCommunicationEngine.class));
Field queryHeadersField = engine.getClass().getDeclaredField("queryHeaders");
FieldSetter.setField(engine, queryHeadersField, Collections.singletonList(QueryHeaderBuilder.build(createQueryResultMetaData(), createMetaData(), 1)));
Field mergedResultField = engine.getClass().getDeclaredField("mergedResult");
FieldSetter.setField(engine, mergedResultField, new MemoryMergedResult<ShardingSphereRule>(null, null, null, Collections.emptyList()) {
private MemoryQueryResultRow memoryQueryResultRow;
@Override
protected List<MemoryQueryResultRow> init(final ShardingSphereRule rule, final ShardingSphereSchema schema,
final SQLStatementContext sqlStatementContext, final List<QueryResult> queryResults) {
memoryQueryResultRow = mock(MemoryQueryResultRow.class);
return Collections.singletonList(memoryQueryResultRow);
}
});
Exception ex = null;
try {
engine.getQueryResponseRow();
} catch (final SQLException | IndexOutOfBoundsException e) {
ex = e;
} finally {
assertFalse(ex instanceof IndexOutOfBoundsException);
}
}
private ShardingSphereMetaData createMetaData() {
ShardingSphereMetaData result = mock(ShardingSphereMetaData.class, RETURNS_DEEP_STUBS);
ColumnMetaData columnMetaData = new ColumnMetaData("order_id", Types.INTEGER, true, false, false);
when(result.getSchema().get("t_logic_order")).thenReturn(
new TableMetaData("t_logic_order", Collections.singletonList(columnMetaData), Collections.singletonList(new IndexMetaData("order_id"))));
ShardingRule shardingRule = mock(ShardingRule.class);
when(shardingRule.findLogicTableByActualTable("t_order")).thenReturn(Optional.of("t_logic_order"));
when(result.getRuleMetaData().getRules()).thenReturn(Collections.singletonList(shardingRule));
when(result.getName()).thenReturn("sharding_schema");
return result;
}
private QueryResultMetaData createQueryResultMetaData() throws SQLException {
QueryResultMetaData result = mock(QueryResultMetaData.class);
when(result.getTableName(1)).thenReturn("t_order");
when(result.getColumnLabel(1)).thenReturn("order_id");
when(result.getColumnName(1)).thenReturn("order_id");
when(result.getColumnType(1)).thenReturn(Types.INTEGER);
when(result.isSigned(1)).thenReturn(true);
when(result.isAutoIncrement(1)).thenReturn(true);
when(result.getColumnLength(1)).thenReturn(1);
when(result.getDecimals(1)).thenReturn(1);
when(result.isNotNull(1)).thenReturn(true);
return result;
}
@Test
public void assertAddStatementCorrectly() {
DatabaseCommunicationEngine engine =
DatabaseCommunicationEngineFactory.getInstance().newBinaryProtocolInstance(mock(SQLStatementContext.class), "schemaName", Collections.emptyList(), backendConnection);
engine.add(statement);
Collection<?> actual = getField(engine, "cachedStatements");
assertThat(actual.size(), is(1));
assertThat(actual.iterator().next(), is(statement));
}
@Test
public void assertAddResultSetCorrectly() {
DatabaseCommunicationEngine engine =
DatabaseCommunicationEngineFactory.getInstance().newBinaryProtocolInstance(mock(SQLStatementContext.class), "schemaName", Collections.emptyList(), backendConnection);
engine.add(resultSet);
Collection<?> actual = getField(engine, "cachedResultSets");
assertThat(actual.size(), is(1));
assertThat(actual.iterator().next(), is(resultSet));
}
@Test
public void assertCloseCorrectly() throws SQLException {
DatabaseCommunicationEngine engine =
DatabaseCommunicationEngineFactory.getInstance().newBinaryProtocolInstance(mock(SQLStatementContext.class), "schemaName", Collections.emptyList(), backendConnection);
Collection<ResultSet> cachedResultSets = getField(engine, "cachedResultSets");
cachedResultSets.add(resultSet);
Collection<Statement> cachedStatements = getField(engine, "cachedStatements");
cachedStatements.add(statement);
engine.close();
verify(resultSet).close();
verify(statement).close();
assertTrue(cachedResultSets.isEmpty());
assertTrue(cachedStatements.isEmpty());
}
@Test
public void assertCloseResultSetsWithExceptionThrown() throws SQLException {
DatabaseCommunicationEngine engine =
DatabaseCommunicationEngineFactory.getInstance().newBinaryProtocolInstance(mock(SQLStatementContext.class), "schemaName", Collections.emptyList(), backendConnection);
Collection<ResultSet> cachedResultSets = getField(engine, "cachedResultSets");
SQLException sqlExceptionByResultSet = new SQLException("ResultSet");
doThrow(sqlExceptionByResultSet).when(resultSet).close();
cachedResultSets.add(resultSet);
Collection<Statement> cachedStatements = getField(engine, "cachedStatements");
SQLException sqlExceptionByStatement = new SQLException("Statement");
doThrow(sqlExceptionByStatement).when(statement).close();
cachedStatements.add(statement);
SQLException actual = null;
try {
engine.close();
} catch (final SQLException ex) {
actual = ex;
}
verify(resultSet).close();
verify(statement).close();
assertTrue(cachedResultSets.isEmpty());
assertTrue(cachedStatements.isEmpty());
assertThat(actual.getNextException(), is(sqlExceptionByResultSet));
assertThat(actual.getNextException().getNextException(), is(sqlExceptionByStatement));
}
@SneakyThrows
private <T> T getField(final DatabaseCommunicationEngine target, final String fieldName) {
Field field = DatabaseCommunicationEngine.class.getDeclaredField(fieldName);
field.setAccessible(true);
return (T) field.get(target);
}
}
|
package ru.stqa.new_project.addressbook.tests;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import ru.stqa.new_project.addressbook.model.ContactData;
import ru.stqa.new_project.addressbook.model.Contacts;
import ru.stqa.new_project.addressbook.model.GroupData;
import ru.stqa.new_project.addressbook.model.Groups;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class ContactCreationTest extends TestBase{
@BeforeMethod
public void ensurePreconditions() {
if (app.db().groups().size() ==0) {
app.goTo().groupPage();
app.group().create(new GroupData().withName("test 1"));
}
}
@DataProvider
public Iterator<Object[]> validContactsFromJson() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/contacts.json")));
String json = "";
String line = reader.readLine();
while (line != null) {
json += line;
line = reader.readLine();
}
Gson gson = new Gson();
List<ContactData> contacts = gson.fromJson(json, new TypeToken<List<ContactData>>(){}.getType()); //List<ContactData>.class
return contacts.stream().map((c) -> new Object[]{c}).collect(Collectors.toList()).iterator();
}
@Test(dataProvider = "validContactsFromJson")
public void testContactCreationTests(ContactData contact) throws Exception {
//Groups groups = app.db().groups();
app.contact().ContactHomePage();
Contacts before = app.db().contacts();
File photo = new File("src/test/resources/kitten_child.png");
app.contact().create(contact, true);
Contacts after = app.db().contacts();
assertThat(after.size(), equalTo(before.size() + 1));
assertThat(after, equalTo(
before.withAdded(contact.withId(after.stream().mapToInt((c) -> c.getId()).max().getAsInt()))));
verifyContactListInUi();
}
}
|
/**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.vesoft.nebula.meta;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.BitSet;
import java.util.Arrays;
import com.facebook.thrift.*;
import com.facebook.thrift.annotations.*;
import com.facebook.thrift.async.*;
import com.facebook.thrift.meta_data.*;
import com.facebook.thrift.server.*;
import com.facebook.thrift.transport.*;
import com.facebook.thrift.protocol.*;
@SuppressWarnings({ "unused", "serial" })
public class HostItem implements TBase, java.io.Serializable, Cloneable, Comparable<HostItem> {
private static final TStruct STRUCT_DESC = new TStruct("HostItem");
private static final TField HOST_ADDR_FIELD_DESC = new TField("hostAddr", TType.STRUCT, (short)1);
private static final TField STATUS_FIELD_DESC = new TField("status", TType.I32, (short)2);
private static final TField LEADER_PARTS_FIELD_DESC = new TField("leader_parts", TType.MAP, (short)3);
private static final TField ALL_PARTS_FIELD_DESC = new TField("all_parts", TType.MAP, (short)4);
private static final TField ROLE_FIELD_DESC = new TField("role", TType.I32, (short)5);
private static final TField GIT_INFO_SHA_FIELD_DESC = new TField("git_info_sha", TType.STRING, (short)6);
private static final TField ZONE_NAME_FIELD_DESC = new TField("zone_name", TType.STRING, (short)7);
private static final TField VERSION_FIELD_DESC = new TField("version", TType.STRING, (short)8);
public com.vesoft.nebula.HostAddr hostAddr;
/**
*
* @see HostStatus
*/
public HostStatus status;
public Map<byte[],List<Integer>> leader_parts;
public Map<byte[],List<Integer>> all_parts;
public HostRole role;
public byte[] git_info_sha;
public byte[] zone_name;
public byte[] version;
public static final int HOSTADDR = 1;
public static final int STATUS = 2;
public static final int LEADER_PARTS = 3;
public static final int ALL_PARTS = 4;
public static final int ROLE = 5;
public static final int GIT_INFO_SHA = 6;
public static final int ZONE_NAME = 7;
public static final int VERSION = 8;
// isset id assignments
public static final Map<Integer, FieldMetaData> metaDataMap;
static {
Map<Integer, FieldMetaData> tmpMetaDataMap = new HashMap<Integer, FieldMetaData>();
tmpMetaDataMap.put(HOSTADDR, new FieldMetaData("hostAddr", TFieldRequirementType.DEFAULT,
new StructMetaData(TType.STRUCT, com.vesoft.nebula.HostAddr.class)));
tmpMetaDataMap.put(STATUS, new FieldMetaData("status", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.I32)));
tmpMetaDataMap.put(LEADER_PARTS, new FieldMetaData("leader_parts", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.I32)))));
tmpMetaDataMap.put(ALL_PARTS, new FieldMetaData("all_parts", TFieldRequirementType.DEFAULT,
new MapMetaData(TType.MAP,
new FieldValueMetaData(TType.STRING),
new ListMetaData(TType.LIST,
new FieldValueMetaData(TType.I32)))));
tmpMetaDataMap.put(ROLE, new FieldMetaData("role", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.I32)));
tmpMetaDataMap.put(GIT_INFO_SHA, new FieldMetaData("git_info_sha", TFieldRequirementType.DEFAULT,
new FieldValueMetaData(TType.STRING)));
tmpMetaDataMap.put(ZONE_NAME, new FieldMetaData("zone_name", TFieldRequirementType.OPTIONAL,
new FieldValueMetaData(TType.STRING)));
tmpMetaDataMap.put(VERSION, new FieldMetaData("version", TFieldRequirementType.OPTIONAL,
new FieldValueMetaData(TType.STRING)));
metaDataMap = Collections.unmodifiableMap(tmpMetaDataMap);
}
static {
FieldMetaData.addStructMetaDataMap(HostItem.class, metaDataMap);
}
public HostItem() {
}
public HostItem(
com.vesoft.nebula.HostAddr hostAddr,
HostStatus status,
Map<byte[],List<Integer>> leader_parts,
Map<byte[],List<Integer>> all_parts,
HostRole role,
byte[] git_info_sha) {
this();
this.hostAddr = hostAddr;
this.status = status;
this.leader_parts = leader_parts;
this.all_parts = all_parts;
this.role = role;
this.git_info_sha = git_info_sha;
}
public HostItem(
com.vesoft.nebula.HostAddr hostAddr,
HostStatus status,
Map<byte[],List<Integer>> leader_parts,
Map<byte[],List<Integer>> all_parts,
HostRole role,
byte[] git_info_sha,
byte[] zone_name,
byte[] version) {
this();
this.hostAddr = hostAddr;
this.status = status;
this.leader_parts = leader_parts;
this.all_parts = all_parts;
this.role = role;
this.git_info_sha = git_info_sha;
this.zone_name = zone_name;
this.version = version;
}
public static class Builder {
private com.vesoft.nebula.HostAddr hostAddr;
private HostStatus status;
private Map<byte[],List<Integer>> leader_parts;
private Map<byte[],List<Integer>> all_parts;
private HostRole role;
private byte[] git_info_sha;
private byte[] zone_name;
private byte[] version;
public Builder() {
}
public Builder setHostAddr(final com.vesoft.nebula.HostAddr hostAddr) {
this.hostAddr = hostAddr;
return this;
}
public Builder setStatus(final HostStatus status) {
this.status = status;
return this;
}
public Builder setLeader_parts(final Map<byte[],List<Integer>> leader_parts) {
this.leader_parts = leader_parts;
return this;
}
public Builder setAll_parts(final Map<byte[],List<Integer>> all_parts) {
this.all_parts = all_parts;
return this;
}
public Builder setRole(final HostRole role) {
this.role = role;
return this;
}
public Builder setGit_info_sha(final byte[] git_info_sha) {
this.git_info_sha = git_info_sha;
return this;
}
public Builder setZone_name(final byte[] zone_name) {
this.zone_name = zone_name;
return this;
}
public Builder setVersion(final byte[] version) {
this.version = version;
return this;
}
public HostItem build() {
HostItem result = new HostItem();
result.setHostAddr(this.hostAddr);
result.setStatus(this.status);
result.setLeader_parts(this.leader_parts);
result.setAll_parts(this.all_parts);
result.setRole(this.role);
result.setGit_info_sha(this.git_info_sha);
result.setZone_name(this.zone_name);
result.setVersion(this.version);
return result;
}
}
public static Builder builder() {
return new Builder();
}
/**
* Performs a deep copy on <i>other</i>.
*/
public HostItem(HostItem other) {
if (other.isSetHostAddr()) {
this.hostAddr = TBaseHelper.deepCopy(other.hostAddr);
}
if (other.isSetStatus()) {
this.status = TBaseHelper.deepCopy(other.status);
}
if (other.isSetLeader_parts()) {
this.leader_parts = TBaseHelper.deepCopy(other.leader_parts);
}
if (other.isSetAll_parts()) {
this.all_parts = TBaseHelper.deepCopy(other.all_parts);
}
if (other.isSetRole()) {
this.role = TBaseHelper.deepCopy(other.role);
}
if (other.isSetGit_info_sha()) {
this.git_info_sha = TBaseHelper.deepCopy(other.git_info_sha);
}
if (other.isSetZone_name()) {
this.zone_name = TBaseHelper.deepCopy(other.zone_name);
}
if (other.isSetVersion()) {
this.version = TBaseHelper.deepCopy(other.version);
}
}
public HostItem deepCopy() {
return new HostItem(this);
}
public com.vesoft.nebula.HostAddr getHostAddr() {
return this.hostAddr;
}
public HostItem setHostAddr(com.vesoft.nebula.HostAddr hostAddr) {
this.hostAddr = hostAddr;
return this;
}
public void unsetHostAddr() {
this.hostAddr = null;
}
// Returns true if field hostAddr is set (has been assigned a value) and false otherwise
public boolean isSetHostAddr() {
return this.hostAddr != null;
}
public void setHostAddrIsSet(boolean __value) {
if (!__value) {
this.hostAddr = null;
}
}
/**
*
* @see HostStatus
*/
public HostStatus getStatus() {
return this.status;
}
/**
*
* @see HostStatus
*/
public HostItem setStatus(HostStatus status) {
this.status = status;
return this;
}
public void unsetStatus() {
this.status = null;
}
// Returns true if field status is set (has been assigned a value) and false otherwise
public boolean isSetStatus() {
return this.status != null;
}
public void setStatusIsSet(boolean __value) {
if (!__value) {
this.status = null;
}
}
public Map<byte[],List<Integer>> getLeader_parts() {
return this.leader_parts;
}
public HostItem setLeader_parts(Map<byte[],List<Integer>> leader_parts) {
this.leader_parts = leader_parts;
return this;
}
public void unsetLeader_parts() {
this.leader_parts = null;
}
// Returns true if field leader_parts is set (has been assigned a value) and false otherwise
public boolean isSetLeader_parts() {
return this.leader_parts != null;
}
public void setLeader_partsIsSet(boolean __value) {
if (!__value) {
this.leader_parts = null;
}
}
public Map<byte[],List<Integer>> getAll_parts() {
return this.all_parts;
}
public HostItem setAll_parts(Map<byte[],List<Integer>> all_parts) {
this.all_parts = all_parts;
return this;
}
public void unsetAll_parts() {
this.all_parts = null;
}
// Returns true if field all_parts is set (has been assigned a value) and false otherwise
public boolean isSetAll_parts() {
return this.all_parts != null;
}
public void setAll_partsIsSet(boolean __value) {
if (!__value) {
this.all_parts = null;
}
}
public HostRole getRole() {
return this.role;
}
public HostItem setRole(HostRole role) {
this.role = role;
return this;
}
public void unsetRole() {
this.role = null;
}
// Returns true if field role is set (has been assigned a value) and false otherwise
public boolean isSetRole() {
return this.role != null;
}
public void setRoleIsSet(boolean __value) {
if (!__value) {
this.role = null;
}
}
public byte[] getGit_info_sha() {
return this.git_info_sha;
}
public HostItem setGit_info_sha(byte[] git_info_sha) {
this.git_info_sha = git_info_sha;
return this;
}
public void unsetGit_info_sha() {
this.git_info_sha = null;
}
// Returns true if field git_info_sha is set (has been assigned a value) and false otherwise
public boolean isSetGit_info_sha() {
return this.git_info_sha != null;
}
public void setGit_info_shaIsSet(boolean __value) {
if (!__value) {
this.git_info_sha = null;
}
}
public byte[] getZone_name() {
return this.zone_name;
}
public HostItem setZone_name(byte[] zone_name) {
this.zone_name = zone_name;
return this;
}
public void unsetZone_name() {
this.zone_name = null;
}
// Returns true if field zone_name is set (has been assigned a value) and false otherwise
public boolean isSetZone_name() {
return this.zone_name != null;
}
public void setZone_nameIsSet(boolean __value) {
if (!__value) {
this.zone_name = null;
}
}
public byte[] getVersion() {
return this.version;
}
public HostItem setVersion(byte[] version) {
this.version = version;
return this;
}
public void unsetVersion() {
this.version = null;
}
// Returns true if field version is set (has been assigned a value) and false otherwise
public boolean isSetVersion() {
return this.version != null;
}
public void setVersionIsSet(boolean __value) {
if (!__value) {
this.version = null;
}
}
@SuppressWarnings("unchecked")
public void setFieldValue(int fieldID, Object __value) {
switch (fieldID) {
case HOSTADDR:
if (__value == null) {
unsetHostAddr();
} else {
setHostAddr((com.vesoft.nebula.HostAddr)__value);
}
break;
case STATUS:
if (__value == null) {
unsetStatus();
} else {
setStatus((HostStatus)__value);
}
break;
case LEADER_PARTS:
if (__value == null) {
unsetLeader_parts();
} else {
setLeader_parts((Map<byte[],List<Integer>>)__value);
}
break;
case ALL_PARTS:
if (__value == null) {
unsetAll_parts();
} else {
setAll_parts((Map<byte[],List<Integer>>)__value);
}
break;
case ROLE:
if (__value == null) {
unsetRole();
} else {
setRole((HostRole)__value);
}
break;
case GIT_INFO_SHA:
if (__value == null) {
unsetGit_info_sha();
} else {
setGit_info_sha((byte[])__value);
}
break;
case ZONE_NAME:
if (__value == null) {
unsetZone_name();
} else {
setZone_name((byte[])__value);
}
break;
case VERSION:
if (__value == null) {
unsetVersion();
} else {
setVersion((byte[])__value);
}
break;
default:
throw new IllegalArgumentException("Field " + fieldID + " doesn't exist!");
}
}
public Object getFieldValue(int fieldID) {
switch (fieldID) {
case HOSTADDR:
return getHostAddr();
case STATUS:
return getStatus();
case LEADER_PARTS:
return getLeader_parts();
case ALL_PARTS:
return getAll_parts();
case ROLE:
return getRole();
case GIT_INFO_SHA:
return getGit_info_sha();
case ZONE_NAME:
return getZone_name();
case VERSION:
return getVersion();
default:
throw new IllegalArgumentException("Field " + fieldID + " doesn't exist!");
}
}
@Override
public boolean equals(Object _that) {
if (_that == null)
return false;
if (this == _that)
return true;
if (!(_that instanceof HostItem))
return false;
HostItem that = (HostItem)_that;
if (!TBaseHelper.equalsNobinary(this.isSetHostAddr(), that.isSetHostAddr(), this.hostAddr, that.hostAddr)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetStatus(), that.isSetStatus(), this.status, that.status)) { return false; }
if (!TBaseHelper.equalsSlow(this.isSetLeader_parts(), that.isSetLeader_parts(), this.leader_parts, that.leader_parts)) { return false; }
if (!TBaseHelper.equalsSlow(this.isSetAll_parts(), that.isSetAll_parts(), this.all_parts, that.all_parts)) { return false; }
if (!TBaseHelper.equalsNobinary(this.isSetRole(), that.isSetRole(), this.role, that.role)) { return false; }
if (!TBaseHelper.equalsSlow(this.isSetGit_info_sha(), that.isSetGit_info_sha(), this.git_info_sha, that.git_info_sha)) { return false; }
if (!TBaseHelper.equalsSlow(this.isSetZone_name(), that.isSetZone_name(), this.zone_name, that.zone_name)) { return false; }
if (!TBaseHelper.equalsSlow(this.isSetVersion(), that.isSetVersion(), this.version, that.version)) { return false; }
return true;
}
@Override
public int hashCode() {
return Arrays.deepHashCode(new Object[] {hostAddr, status, leader_parts, all_parts, role, git_info_sha, zone_name, version});
}
@Override
public int compareTo(HostItem other) {
if (other == null) {
// See java.lang.Comparable docs
throw new NullPointerException();
}
if (other == this) {
return 0;
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetHostAddr()).compareTo(other.isSetHostAddr());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = TBaseHelper.compareTo(hostAddr, other.hostAddr);
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = Boolean.valueOf(isSetStatus()).compareTo(other.isSetStatus());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = TBaseHelper.compareTo(status, other.status);
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = Boolean.valueOf(isSetLeader_parts()).compareTo(other.isSetLeader_parts());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = TBaseHelper.compareTo(leader_parts, other.leader_parts);
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = Boolean.valueOf(isSetAll_parts()).compareTo(other.isSetAll_parts());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = TBaseHelper.compareTo(all_parts, other.all_parts);
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = Boolean.valueOf(isSetRole()).compareTo(other.isSetRole());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = TBaseHelper.compareTo(role, other.role);
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = Boolean.valueOf(isSetGit_info_sha()).compareTo(other.isSetGit_info_sha());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = TBaseHelper.compareTo(git_info_sha, other.git_info_sha);
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = Boolean.valueOf(isSetZone_name()).compareTo(other.isSetZone_name());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = TBaseHelper.compareTo(zone_name, other.zone_name);
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = Boolean.valueOf(isSetVersion()).compareTo(other.isSetVersion());
if (lastComparison != 0) {
return lastComparison;
}
lastComparison = TBaseHelper.compareTo(version, other.version);
if (lastComparison != 0) {
return lastComparison;
}
return 0;
}
public void read(TProtocol iprot) throws TException {
TField __field;
iprot.readStructBegin(metaDataMap);
while (true)
{
__field = iprot.readFieldBegin();
if (__field.type == TType.STOP) {
break;
}
switch (__field.id)
{
case HOSTADDR:
if (__field.type == TType.STRUCT) {
this.hostAddr = new com.vesoft.nebula.HostAddr();
this.hostAddr.read(iprot);
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case STATUS:
if (__field.type == TType.I32) {
this.status = HostStatus.findByValue(iprot.readI32());
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case LEADER_PARTS:
if (__field.type == TType.MAP) {
{
TMap _map8 = iprot.readMapBegin();
this.leader_parts = new HashMap<byte[],List<Integer>>(Math.max(0, 2*_map8.size));
for (int _i9 = 0;
(_map8.size < 0) ? iprot.peekMap() : (_i9 < _map8.size);
++_i9)
{
byte[] _key10;
List<Integer> _val11;
_key10 = iprot.readBinary();
{
TList _list12 = iprot.readListBegin();
_val11 = new ArrayList<Integer>(Math.max(0, _list12.size));
for (int _i13 = 0;
(_list12.size < 0) ? iprot.peekList() : (_i13 < _list12.size);
++_i13)
{
int _elem14;
_elem14 = iprot.readI32();
_val11.add(_elem14);
}
iprot.readListEnd();
}
this.leader_parts.put(_key10, _val11);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case ALL_PARTS:
if (__field.type == TType.MAP) {
{
TMap _map15 = iprot.readMapBegin();
this.all_parts = new HashMap<byte[],List<Integer>>(Math.max(0, 2*_map15.size));
for (int _i16 = 0;
(_map15.size < 0) ? iprot.peekMap() : (_i16 < _map15.size);
++_i16)
{
byte[] _key17;
List<Integer> _val18;
_key17 = iprot.readBinary();
{
TList _list19 = iprot.readListBegin();
_val18 = new ArrayList<Integer>(Math.max(0, _list19.size));
for (int _i20 = 0;
(_list19.size < 0) ? iprot.peekList() : (_i20 < _list19.size);
++_i20)
{
int _elem21;
_elem21 = iprot.readI32();
_val18.add(_elem21);
}
iprot.readListEnd();
}
this.all_parts.put(_key17, _val18);
}
iprot.readMapEnd();
}
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case ROLE:
if (__field.type == TType.I32) {
this.role = HostRole.findByValue(iprot.readI32());
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case GIT_INFO_SHA:
if (__field.type == TType.STRING) {
this.git_info_sha = iprot.readBinary();
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case ZONE_NAME:
if (__field.type == TType.STRING) {
this.zone_name = iprot.readBinary();
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
case VERSION:
if (__field.type == TType.STRING) {
this.version = iprot.readBinary();
} else {
TProtocolUtil.skip(iprot, __field.type);
}
break;
default:
TProtocolUtil.skip(iprot, __field.type);
break;
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
validate();
}
public void write(TProtocol oprot) throws TException {
validate();
oprot.writeStructBegin(STRUCT_DESC);
if (this.hostAddr != null) {
oprot.writeFieldBegin(HOST_ADDR_FIELD_DESC);
this.hostAddr.write(oprot);
oprot.writeFieldEnd();
}
if (this.status != null) {
oprot.writeFieldBegin(STATUS_FIELD_DESC);
oprot.writeI32(this.status == null ? 0 : this.status.getValue());
oprot.writeFieldEnd();
}
if (this.leader_parts != null) {
oprot.writeFieldBegin(LEADER_PARTS_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.LIST, this.leader_parts.size()));
for (Map.Entry<byte[], List<Integer>> _iter22 : this.leader_parts.entrySet()) {
oprot.writeBinary(_iter22.getKey());
{
oprot.writeListBegin(new TList(TType.I32, _iter22.getValue().size()));
for (int _iter23 : _iter22.getValue()) {
oprot.writeI32(_iter23);
}
oprot.writeListEnd();
}
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.all_parts != null) {
oprot.writeFieldBegin(ALL_PARTS_FIELD_DESC);
{
oprot.writeMapBegin(new TMap(TType.STRING, TType.LIST, this.all_parts.size()));
for (Map.Entry<byte[], List<Integer>> _iter24 : this.all_parts.entrySet()) {
oprot.writeBinary(_iter24.getKey());
{
oprot.writeListBegin(new TList(TType.I32, _iter24.getValue().size()));
for (int _iter25 : _iter24.getValue()) {
oprot.writeI32(_iter25);
}
oprot.writeListEnd();
}
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
if (this.role != null) {
oprot.writeFieldBegin(ROLE_FIELD_DESC);
oprot.writeI32(this.role == null ? 0 : this.role.getValue());
oprot.writeFieldEnd();
}
if (this.git_info_sha != null) {
oprot.writeFieldBegin(GIT_INFO_SHA_FIELD_DESC);
oprot.writeBinary(this.git_info_sha);
oprot.writeFieldEnd();
}
if (this.zone_name != null) {
if (isSetZone_name()) {
oprot.writeFieldBegin(ZONE_NAME_FIELD_DESC);
oprot.writeBinary(this.zone_name);
oprot.writeFieldEnd();
}
}
if (this.version != null) {
if (isSetVersion()) {
oprot.writeFieldBegin(VERSION_FIELD_DESC);
oprot.writeBinary(this.version);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
@Override
public String toString() {
return toString(1, true);
}
@Override
public String toString(int indent, boolean prettyPrint) {
String indentStr = prettyPrint ? TBaseHelper.getIndentedString(indent) : "";
String newLine = prettyPrint ? "\n" : "";
String space = prettyPrint ? " " : "";
StringBuilder sb = new StringBuilder("HostItem");
sb.append(space);
sb.append("(");
sb.append(newLine);
boolean first = true;
sb.append(indentStr);
sb.append("hostAddr");
sb.append(space);
sb.append(":").append(space);
if (this.getHostAddr() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getHostAddr(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("status");
sb.append(space);
sb.append(":").append(space);
if (this.getStatus() == null) {
sb.append("null");
} else {
String status_name = this.getStatus() == null ? "null" : this.getStatus().name();
if (status_name != null) {
sb.append(status_name);
sb.append(" (");
}
sb.append(this.getStatus());
if (status_name != null) {
sb.append(")");
}
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("leader_parts");
sb.append(space);
sb.append(":").append(space);
if (this.getLeader_parts() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getLeader_parts(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("all_parts");
sb.append(space);
sb.append(":").append(space);
if (this.getAll_parts() == null) {
sb.append("null");
} else {
sb.append(TBaseHelper.toString(this.getAll_parts(), indent + 1, prettyPrint));
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("role");
sb.append(space);
sb.append(":").append(space);
if (this.getRole() == null) {
sb.append("null");
} else {
String role_name = this.getRole() == null ? "null" : this.getRole().name();
if (role_name != null) {
sb.append(role_name);
sb.append(" (");
}
sb.append(this.getRole());
if (role_name != null) {
sb.append(")");
}
}
first = false;
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("git_info_sha");
sb.append(space);
sb.append(":").append(space);
if (this.getGit_info_sha() == null) {
sb.append("null");
} else {
int __git_info_sha_size = Math.min(this.getGit_info_sha().length, 128);
for (int i = 0; i < __git_info_sha_size; i++) {
if (i != 0) sb.append(" ");
sb.append(Integer.toHexString(this.getGit_info_sha()[i]).length() > 1 ? Integer.toHexString(this.getGit_info_sha()[i]).substring(Integer.toHexString(this.getGit_info_sha()[i]).length() - 2).toUpperCase() : "0" + Integer.toHexString(this.getGit_info_sha()[i]).toUpperCase());
}
if (this.getGit_info_sha().length > 128) sb.append(" ...");
}
first = false;
if (isSetZone_name())
{
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("zone_name");
sb.append(space);
sb.append(":").append(space);
if (this.getZone_name() == null) {
sb.append("null");
} else {
int __zone_name_size = Math.min(this.getZone_name().length, 128);
for (int i = 0; i < __zone_name_size; i++) {
if (i != 0) sb.append(" ");
sb.append(Integer.toHexString(this.getZone_name()[i]).length() > 1 ? Integer.toHexString(this.getZone_name()[i]).substring(Integer.toHexString(this.getZone_name()[i]).length() - 2).toUpperCase() : "0" + Integer.toHexString(this.getZone_name()[i]).toUpperCase());
}
if (this.getZone_name().length > 128) sb.append(" ...");
}
first = false;
}
if (isSetVersion())
{
if (!first) sb.append("," + newLine);
sb.append(indentStr);
sb.append("version");
sb.append(space);
sb.append(":").append(space);
if (this.getVersion() == null) {
sb.append("null");
} else {
int __version_size = Math.min(this.getVersion().length, 128);
for (int i = 0; i < __version_size; i++) {
if (i != 0) sb.append(" ");
sb.append(Integer.toHexString(this.getVersion()[i]).length() > 1 ? Integer.toHexString(this.getVersion()[i]).substring(Integer.toHexString(this.getVersion()[i]).length() - 2).toUpperCase() : "0" + Integer.toHexString(this.getVersion()[i]).toUpperCase());
}
if (this.getVersion().length > 128) sb.append(" ...");
}
first = false;
}
sb.append(newLine + TBaseHelper.reduceIndent(indentStr));
sb.append(")");
return sb.toString();
}
public void validate() throws TException {
// check for required fields
}
}
|
package org.ovirt.engine.core.bll;
import javax.inject.Inject;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
public class GetTagByTagIdQuery<P extends IdQueryParameters> extends QueriesCommandBase<P> {
@Inject
private TagsDirector tagsDirector;
public GetTagByTagIdQuery(P parameters) {
super(parameters);
}
@Override
protected void executeQueryCommand() {
getQueryReturnValue().setReturnValue(tagsDirector.getTagById(getParameters().getId()));
}
}
|
package com.binance.api.client.domain.account;
import com.binance.api.client.constant.BinanceApiConstants;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.List;
/**
* History of account deposits.
*
* @see Deposit
*/
public class DepositHistory {
@JsonProperty("depositList")
private List<Deposit> depositList;
private boolean success;
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<Deposit> getDepositList() {
return depositList;
}
public void setDepositList(List<Deposit> depositList) {
this.depositList = depositList;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@Override
public String toString() {
return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE)
.append("depositList", depositList)
.append("success", success)
.append("msg", msg)
.toString();
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.elasticsearch.Version;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.collect.Tuple;
/** Utilities for selecting versions in tests */
public class VersionUtils {
/**
* Sort versions that have backwards compatibility guarantees from
* those that don't. Doesn't actually check whether or not the versions
* are released, instead it relies on gradle to have already checked
* this which it does in {@code :core:verifyVersions}. So long as the
* rules here match up with the rules in gradle then this should
* produce sensible results.
* @return a tuple containing versions with backwards compatibility
* guarantees in v1 and versions without the guranteees in v2
*/
static Tuple<List<Version>, List<Version>> resolveReleasedVersions(Version current, Class<?> versionClass) {
// group versions into major version
Map<Integer, List<Version>> majorVersions = Version.getDeclaredVersions(versionClass).stream()
.collect(Collectors.groupingBy(v -> (int)v.major));
// this breaks b/c 5.x is still in version list but master doesn't care about it!
//assert majorVersions.size() == 2;
// TODO: remove oldVersions, we should only ever have 2 majors in Version
List<Version> oldVersions = majorVersions.getOrDefault((int)current.major - 2, Collections.emptyList());
List<List<Version>> previousMajor = splitByMinor(majorVersions.get((int)current.major - 1));
List<List<Version>> currentMajor = splitByMinor(majorVersions.get((int)current.major));
List<Version> unreleasedVersions = new ArrayList<>();
final List<List<Version>> stableVersions;
if (currentMajor.size() == 1) {
// on master branch
stableVersions = previousMajor;
// remove current
moveLastToUnreleased(currentMajor, unreleasedVersions);
} else {
// on a stable or release branch, ie N.x
stableVersions = currentMajor;
// remove the next maintenance bugfix
moveLastToUnreleased(previousMajor, unreleasedVersions);
}
// remove next minor
Version lastMinor = moveLastToUnreleased(stableVersions, unreleasedVersions);
if (lastMinor.revision == 0) {
if (stableVersions.get(stableVersions.size() - 1).size() == 1) {
// a minor is being staged, which is also unreleased
moveLastToUnreleased(stableVersions, unreleasedVersions);
}
// remove the next bugfix
moveLastToUnreleased(stableVersions, unreleasedVersions);
}
List<Version> releasedVersions = Stream.concat(oldVersions.stream(),
Stream.concat(previousMajor.stream(), currentMajor.stream()).flatMap(List::stream))
.collect(Collectors.toList());
Collections.sort(unreleasedVersions); // we add unreleased out of order, so need to sort here
return new Tuple<>(Collections.unmodifiableList(releasedVersions), Collections.unmodifiableList(unreleasedVersions));
}
// split the given versions into sub lists grouped by minor version
private static List<List<Version>> splitByMinor(List<Version> versions) {
Map<Integer, List<Version>> byMinor = versions.stream().collect(Collectors.groupingBy(v -> (int)v.minor));
return byMinor.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(Map.Entry::getValue).collect(Collectors.toList());
}
// move the last version of the last minor in versions to the unreleased versions
private static Version moveLastToUnreleased(List<List<Version>> versions, List<Version> unreleasedVersions) {
List<Version> lastMinor = new ArrayList<>(versions.get(versions.size() - 1));
Version lastVersion = lastMinor.remove(lastMinor.size() - 1);
if (lastMinor.isEmpty()) {
versions.remove(versions.size() - 1);
} else {
versions.set(versions.size() - 1, lastMinor);
}
unreleasedVersions.add(lastVersion);
return lastVersion;
}
private static final List<Version> RELEASED_VERSIONS;
private static final List<Version> UNRELEASED_VERSIONS;
private static final List<Version> ALL_VERSIONS;
static {
Tuple<List<Version>, List<Version>> versions = resolveReleasedVersions(Version.CURRENT, Version.class);
RELEASED_VERSIONS = versions.v1();
UNRELEASED_VERSIONS = versions.v2();
List<Version> allVersions = new ArrayList<>(RELEASED_VERSIONS.size() + UNRELEASED_VERSIONS.size());
allVersions.addAll(RELEASED_VERSIONS);
allVersions.addAll(UNRELEASED_VERSIONS);
Collections.sort(allVersions);
ALL_VERSIONS = Collections.unmodifiableList(allVersions);
}
/**
* Returns an immutable, sorted list containing all released versions.
*/
public static List<Version> allReleasedVersions() {
return RELEASED_VERSIONS;
}
/**
* Returns an immutable, sorted list containing all unreleased versions.
*/
public static List<Version> allUnreleasedVersions() {
return UNRELEASED_VERSIONS;
}
/**
* Returns an immutable, sorted list containing all versions, both released and unreleased.
*/
public static List<Version> allVersions() {
return ALL_VERSIONS;
}
/**
* Get the released version before {@code version}.
*/
public static Version getPreviousVersion(Version version) {
for (int i = RELEASED_VERSIONS.size() - 1; i >= 0; i--) {
Version v = RELEASED_VERSIONS.get(i);
if (v.before(version)) {
return v;
}
}
throw new IllegalArgumentException("couldn't find any released versions before [" + version + "]");
}
/**
* Get the released version before {@link Version#CURRENT}.
*/
public static Version getPreviousVersion() {
Version version = getPreviousVersion(Version.CURRENT);
assert version.before(Version.CURRENT);
return version;
}
/**
* Returns the released {@link Version} before the {@link Version#CURRENT}
* where the minor version is less than the currents minor version.
*/
public static Version getPreviousMinorVersion() {
for (int i = RELEASED_VERSIONS.size() - 1; i >= 0; i--) {
Version v = RELEASED_VERSIONS.get(i);
if (v.minor < Version.CURRENT.minor || v.major < Version.CURRENT.major) {
return v;
}
}
throw new IllegalArgumentException("couldn't find any released versions of the minor before [" + Version.CURRENT + "]");
}
/** Returns the oldest released {@link Version} */
public static Version getFirstVersion() {
return RELEASED_VERSIONS.get(0);
}
/** Returns a random {@link Version} from all available versions. */
public static Version randomVersion(Random random) {
return ALL_VERSIONS.get(random.nextInt(ALL_VERSIONS.size()));
}
/** Returns a random {@link Version} from all available versions, that is compatible with the given version. */
public static Version randomCompatibleVersion(Random random, Version version) {
final List<Version> compatible = ALL_VERSIONS.stream().filter(version::isCompatible).collect(Collectors.toList());
return compatible.get(random.nextInt(compatible.size()));
}
/** Returns a random {@link Version} between <code>minVersion</code> and <code>maxVersion</code> (inclusive). */
public static Version randomVersionBetween(Random random, @Nullable Version minVersion, @Nullable Version maxVersion) {
int minVersionIndex = 0;
if (minVersion != null) {
minVersionIndex = ALL_VERSIONS.indexOf(minVersion);
}
int maxVersionIndex = ALL_VERSIONS.size() - 1;
if (maxVersion != null) {
maxVersionIndex = ALL_VERSIONS.indexOf(maxVersion);
}
if (minVersionIndex == -1) {
throw new IllegalArgumentException("minVersion [" + minVersion + "] does not exist.");
} else if (maxVersionIndex == -1) {
throw new IllegalArgumentException("maxVersion [" + maxVersion + "] does not exist.");
} else if (minVersionIndex > maxVersionIndex) {
throw new IllegalArgumentException("maxVersion [" + maxVersion + "] cannot be less than minVersion [" + minVersion + "]");
} else {
// minVersionIndex is inclusive so need to add 1 to this index
int range = maxVersionIndex + 1 - minVersionIndex;
return ALL_VERSIONS.get(minVersionIndex + random.nextInt(range));
}
}
/** returns the first future incompatible version */
public static Version incompatibleFutureVersion(Version version) {
final Optional<Version> opt = ALL_VERSIONS.stream().filter(version::before).filter(v -> v.isCompatible(version) == false).findAny();
assert opt.isPresent() : "no future incompatible version for " + version;
return opt.get();
}
/** Returns the maximum {@link Version} that is compatible with the given version. */
public static Version maxCompatibleVersion(Version version) {
final List<Version> compatible = ALL_VERSIONS.stream().filter(version::isCompatible).filter(version::onOrBefore)
.collect(Collectors.toList());
assert compatible.size() > 0;
return compatible.get(compatible.size() - 1);
}
}
|
package com.kupferwerk.planningpoker.retrofit;
import retrofit.Call;
import retrofit.http.Field;
import retrofit.http.POST;
///session?name=sessionname&presetid=0
public interface RetroService {
// @POST ("session/")
// Call<Session> getData(@Field ("sessionid"), @Field ("presetid"));
}
|
package com.joywire.kidsgame.events;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.os.Handler;
/**
* The gateway of all events running in the game from ui to engine components
* and back.
*
* @author sromku
*/
public class EventBus {
private Handler mHandler;
private static EventBus mInstance = null;
private final Map<String, List<EventObserver>> events = Collections.synchronizedMap(new HashMap<String, List<EventObserver>>());
private Object obj = new Object();
private EventBus() {
mHandler = new Handler();
}
public static EventBus getInstance() {
if (mInstance == null) {
mInstance = new EventBus();
}
return mInstance;
}
synchronized public void listen(String eventType, EventObserver eventObserver) {
List<EventObserver> observers = events.get(eventType);
if (observers == null) {
observers = Collections.synchronizedList(new ArrayList<EventObserver>());
}
observers.add(eventObserver);
events.put(eventType, observers);
}
synchronized public void unlisten(String eventType, EventObserver eventObserver) {
List<EventObserver> observers = events.get(eventType);
if (observers != null) {
observers.remove(eventObserver);
}
}
public void notify(Event event) {
synchronized (obj) {
List<EventObserver> observers = events.get(event.getType());
if (observers != null) {
for (EventObserver observer : observers) {
AbstractEvent abstractEvent = (AbstractEvent) event;
abstractEvent.fire(observer);
}
}
}
}
public void notify(final Event event, long delay) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
EventBus.this.notify(event);
}
}, delay);
}
}
|
package ssl;
/**
* @author Enio Kaljic, mr.el.-dipl.ing.el.
*
*/
public class Parameter {
public static final int MAC0_BASE_ADDR = 0x00000000;
public static final int MAC1_BASE_ADDR = 0x00008000;
public static final int MAC2_BASE_ADDR = 0x00010000;
public static final int MAC3_BASE_ADDR = 0x00018000;
public static final int SCHEDULER_BASE_ADDR = 0x00020000;
public static final int HEADER_PARSER_BASE_ADDR = 0x00030000;
public static final int MATCH_ACTION_TABLE_BASE_ADDR = 0x00040000;
public static final int DEMUX_BASE_ADDR = 0x00050000;
public static final int RX_BACKPRESSURE_BASE_ADDR = 0x00000000;
public static final int CRC_PAD_REMOVER_BASE_ADDR = 0x00000100;
public static final int CRC_CHECKER_BASE_ADDR = 0x00000200;
public static final int RX_FRAME_DECODER_BASE_ADDR = 0x00002000;
public static final int OVERFLOW_CTRL_BASE_ADDR = 0x00000300;
public static final int RX_STATISTICS_BASE_ADDR = 0x00003000;
public static final int TX_BACKPRESSURE_BASE_ADDR = 0x00004000;
public static final int CRC_INSERTER_BASE_ADDR = 0x00004200;
public static final int PAD_INSERTER_BASE_ADDR = 0x00004100;
public static final int PAUSE_GEN_CTRL_BASE_ADDR = 0x00004500;
public static final int ADDRESS_INSERTER_BASE_ADDR = 0x00004800;
public static final int TX_FRAME_DECODER_BASE_ADDR = 0x00006000;
public static final int UNDERFLOW_CTRL_BASE_ADDR = 0x00006300;
public static final int TX_STATISTICS_BASE_ADDR = 0x00007000;
public static final int STAT_CLR = 0x00;
public static final int STAT_FRAMESOK = 0x08;
public static final int STAT_FRAMESERR = 0x10;
public static final int STAT_FRAMESCRCERR = 0x18;
public static final int STAT_OCTETSOK = 0x20;
public static final int STAT_PAUSEMACCTRLFRAMES = 0x28;
public static final int STAT_IFERRORS = 0x30;
public static final int STAT_UNICASTFRAMESOK = 0x38;
public static final int STAT_UNICASTFRAMESERR = 0x40;
public static final int STAT_MULTICASTFRAMESOK = 0x48;
public static final int STAT_MULTICASTFRAMESERR = 0x50;
public static final int STAT_BROADCASTFRAMESOK = 0x58;
public static final int STAT_BROADCASTFRAMESERR = 0x60;
public static final int STAT_ETHERSTATSOCTETS = 0x68;
public static final int STAT_ETHERSTATSPKTS = 0x70;
public static final int STAT_ETHERSTATSUNDERSIZEPKTS = 0x78;
public static final int STAT_ETHERSTATSOVERSIZEPKTS = 0x80;
public static final int STAT_ETHERSTATSPKTS64OCTETS = 0x88;
public static final int STAT_ETHERSTATSPKTS65TO127OCTETS = 0x90;
public static final int STAT_ETHERSTATSPKTS128TO255OCTETS = 0x98;
public static final int STAT_ETHERSTATSPKTS256TO511OCTET = 0xA0;
public static final int STAT_ETHERSTATSPKTS512TO1023OCTETS = 0xA8;
public static final int STAT_ETHERSTATSPKTS1024TO1518OCTETS = 0xB0;
public static final int STAT_ETHERSTATSPKTS1518TOXOCTETS = 0xB8;
public static final int STAT_ETHERSTATSFRAGMENTS = 0xC0;
public static final int STAT_ETHERSTATSJABBERS = 0xC8;
public static final int STAT_ETHERSTATSCRCERR = 0xD0;
public static final int STAT_UNICASTMACCTRLFRAMES = 0xD8;
public static final int STAT_MULTICASTMACCTRLFRAMES = 0xE0;
public static final int STAT_BROADCASTMACCTRLFRAMES = 0xE8;
private String parameterName;
private int jtagBaseAddress;
private int jtagSubBaseAddress;
private int jtagOffset;
private boolean jtagIsData64;
private boolean poll;
public Parameter() {
}
public Parameter(String parameterName, int jtagBaseAddress, int jtagSubBaseAddress, int jtagOffset, boolean jtagIsData64, boolean poll) {
this.parameterName = parameterName;
this.jtagBaseAddress = jtagBaseAddress;
this.jtagSubBaseAddress = jtagSubBaseAddress;
this.jtagOffset = jtagOffset;
this.jtagIsData64 = jtagIsData64;
this.poll = poll;
}
public String getParameterName() {
return parameterName;
}
public void setParameterName(String parameterName) {
this.parameterName = parameterName;
}
public int getJtagBaseAddress() {
return jtagBaseAddress;
}
public void setJtagBaseAddress(int jtagBaseAddress) {
this.jtagBaseAddress = jtagBaseAddress;
}
public int getJtagSubBaseAddress() {
return jtagSubBaseAddress;
}
public void setJtagSubBaseAddress(int jtagSubBaseAddress) {
this.jtagSubBaseAddress = jtagSubBaseAddress;
}
public int getJtagOffset() {
return jtagOffset;
}
public void setJtagOffset(int jtagOffset) {
this.jtagOffset = jtagOffset;
}
public boolean getJtagIsData64() {
return jtagIsData64;
}
public void setJtagIsData64(boolean jtagIsData64) {
this.jtagIsData64 = jtagIsData64;
}
public boolean getPoll() {
return poll;
}
public void setPoll(boolean poll) {
this.poll = poll;
}
}
|
package ru.p4b.dev.mantis.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import java.io.File;
public class HelperBase {
protected ApplicationManager app;
protected WebDriver wd;
public HelperBase(ApplicationManager app) {
this.app = app;
this.wd = app.getDriver();
}
protected void click(By locator) {
wd.findElement(locator).click();
}
protected void type(By locator, String text) {
click(locator);
if (text != null) {
String existingText = wd.findElement(locator).getAttribute("value");
if (!text.equals(existingText)) {
wd.findElement(locator).clear();
wd.findElement(locator).sendKeys(text);
}
}
}
protected void attach(By locator, File file) {
if (file != null) {
wd.findElement(locator).sendKeys(file.getAbsolutePath());
}
}
public boolean isAlertPresent() {
try {
wd.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
protected boolean isElementPresent(By locator) {
try {
wd.findElement(locator);
return true;
} catch (NoSuchElementException ex) {
return false;
}
}
}
|
/*******************************************************************************
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Guy Pelletier - initial API and implementation
******************************************************************************/
package org.eclipse.persistence.internal.jpa.config.mappings;
import org.eclipse.persistence.internal.jpa.config.MetadataImpl;
import org.eclipse.persistence.internal.jpa.metadata.mappings.AccessMethodsMetadata;
import org.eclipse.persistence.jpa.config.AccessMethods;
/**
* JPA scripting API implementation.
*
* @author Guy Pelletier
* @since EclipseLink 2.5.1
*/
public class AccessMethodsImpl extends MetadataImpl<AccessMethodsMetadata> implements AccessMethods {
public AccessMethodsImpl() {
super(new AccessMethodsMetadata());
}
public AccessMethods setGetMethod(String getMethod) {
getMetadata().setGetMethodName(getMethod);
return this;
}
public AccessMethods setSetMethod(String setMethod) {
getMetadata().setSetMethodName(setMethod);
return this;
}
}
|
package com.ihc.smartbot.telegraminterface;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
public class Message {
public static SendMessage message(Update update) {
long chat_id = update.getMessage().getChatId();
if (update.getMessage().getText().equals("/start")) {
SendMessage message = new SendMessage().setChatId(chat_id).setText("You send /start");
message.setReplyMarkup(new Start().ligar());
return message;
} else if (update.getMessage().getText().equals("")) {
return null;
} else {
SendMessage message = new SendMessage().setChatId(chat_id).setText("No hablo chino!");
message.setReplyMarkup(new Start().ligar());
return message;
}
}
}
|
/*
* Copyright 2021 ThoughtWorks, 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.thoughtworks.go.config.validation;
import org.junit.jupiter.api.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class NameTypeValidatorTest {
@Test
public void shouldValidateNameBasedOnLength() {
assertThat(new NameTypeValidator().isNameValid("name"), is(true));
assertThat(new NameTypeValidator().isNameValid(nameOfLength(255)), is(true));
assertThat(new NameTypeValidator().isNameValid(nameOfLength(256)), is(false));
}
@Test
public void shouldValidateNameBasedOnCharacterType() {
//[a-zA-Z0-9_\-]{1}[a-zA-Z0-9_\-.]*
assertThat(new NameTypeValidator().isNameValid(""), is(false));
assertThat(new NameTypeValidator().isNameValid("name"), is(true));
assertThat(new NameTypeValidator().isNameValid("!"), is(false));
assertThat(new NameTypeValidator().isNameValid("name!"), is(false));
assertThat(new NameTypeValidator().isNameValid("name_123"), is(true));
assertThat(new NameTypeValidator().isNameValid("1"), is(true));
assertThat(new NameTypeValidator().isNameValid("."), is(false));
assertThat(new NameTypeValidator().isNameValid("1."), is(true));
}
private String nameOfLength(final int length) {
StringBuilder name = new StringBuilder();
for (int i = 0; i < length; i++) {
name.append("a");
}
return name.toString();
}
}
|
/*
* Elastic Cloud API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.client.model.ClusterCurationSettings;
import io.swagger.client.model.ClusterMetadataSettings;
import io.swagger.client.model.ClusterSnapshotSettings;
import io.swagger.client.model.CrossClusterSearchSettings;
import io.swagger.client.model.IpFilteringSettings;
import io.swagger.client.model.ManagedMonitoringSettings;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.IOException;
/**
* The settings for an Elasticsearch cluster.
*/
@Schema(description = "The settings for an Elasticsearch cluster.")
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2020-03-10T16:33:30.970+05:30[Asia/Kolkata]")
public class ElasticsearchClusterSettings {
@SerializedName("snapshot")
private ClusterSnapshotSettings snapshot = null;
@SerializedName("monitoring")
private ManagedMonitoringSettings monitoring = null;
@SerializedName("metadata")
private ClusterMetadataSettings metadata = null;
@SerializedName("curation")
private ClusterCurationSettings curation = null;
@SerializedName("dedicated_masters_threshold")
private Integer dedicatedMastersThreshold = null;
@SerializedName("ip_filtering")
private IpFilteringSettings ipFiltering = null;
@SerializedName("ccs")
private CrossClusterSearchSettings ccs = null;
public ElasticsearchClusterSettings snapshot(ClusterSnapshotSettings snapshot) {
this.snapshot = snapshot;
return this;
}
/**
* Get snapshot
* @return snapshot
**/
@Schema(description = "")
public ClusterSnapshotSettings getSnapshot() {
return snapshot;
}
public void setSnapshot(ClusterSnapshotSettings snapshot) {
this.snapshot = snapshot;
}
public ElasticsearchClusterSettings monitoring(ManagedMonitoringSettings monitoring) {
this.monitoring = monitoring;
return this;
}
/**
* Get monitoring
* @return monitoring
**/
@Schema(description = "")
public ManagedMonitoringSettings getMonitoring() {
return monitoring;
}
public void setMonitoring(ManagedMonitoringSettings monitoring) {
this.monitoring = monitoring;
}
public ElasticsearchClusterSettings metadata(ClusterMetadataSettings metadata) {
this.metadata = metadata;
return this;
}
/**
* Get metadata
* @return metadata
**/
@Schema(description = "")
public ClusterMetadataSettings getMetadata() {
return metadata;
}
public void setMetadata(ClusterMetadataSettings metadata) {
this.metadata = metadata;
}
public ElasticsearchClusterSettings curation(ClusterCurationSettings curation) {
this.curation = curation;
return this;
}
/**
* Get curation
* @return curation
**/
@Schema(description = "")
public ClusterCurationSettings getCuration() {
return curation;
}
public void setCuration(ClusterCurationSettings curation) {
this.curation = curation;
}
public ElasticsearchClusterSettings dedicatedMastersThreshold(Integer dedicatedMastersThreshold) {
this.dedicatedMastersThreshold = dedicatedMastersThreshold;
return this;
}
/**
* Threshold starting from which the number of instances in the cluster results in the introduction of dedicated masters. If the cluster is downscaled to a number of nodes below this one, dedicated masters will be removed. Limit is inclusive.
* @return dedicatedMastersThreshold
**/
@Schema(description = "Threshold starting from which the number of instances in the cluster results in the introduction of dedicated masters. If the cluster is downscaled to a number of nodes below this one, dedicated masters will be removed. Limit is inclusive.")
public Integer getDedicatedMastersThreshold() {
return dedicatedMastersThreshold;
}
public void setDedicatedMastersThreshold(Integer dedicatedMastersThreshold) {
this.dedicatedMastersThreshold = dedicatedMastersThreshold;
}
public ElasticsearchClusterSettings ipFiltering(IpFilteringSettings ipFiltering) {
this.ipFiltering = ipFiltering;
return this;
}
/**
* Get ipFiltering
* @return ipFiltering
**/
@Schema(description = "")
public IpFilteringSettings getIpFiltering() {
return ipFiltering;
}
public void setIpFiltering(IpFilteringSettings ipFiltering) {
this.ipFiltering = ipFiltering;
}
public ElasticsearchClusterSettings ccs(CrossClusterSearchSettings ccs) {
this.ccs = ccs;
return this;
}
/**
* Get ccs
* @return ccs
**/
@Schema(description = "")
public CrossClusterSearchSettings getCcs() {
return ccs;
}
public void setCcs(CrossClusterSearchSettings ccs) {
this.ccs = ccs;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ElasticsearchClusterSettings elasticsearchClusterSettings = (ElasticsearchClusterSettings) o;
return Objects.equals(this.snapshot, elasticsearchClusterSettings.snapshot) &&
Objects.equals(this.monitoring, elasticsearchClusterSettings.monitoring) &&
Objects.equals(this.metadata, elasticsearchClusterSettings.metadata) &&
Objects.equals(this.curation, elasticsearchClusterSettings.curation) &&
Objects.equals(this.dedicatedMastersThreshold, elasticsearchClusterSettings.dedicatedMastersThreshold) &&
Objects.equals(this.ipFiltering, elasticsearchClusterSettings.ipFiltering) &&
Objects.equals(this.ccs, elasticsearchClusterSettings.ccs);
}
@Override
public int hashCode() {
return Objects.hash(snapshot, monitoring, metadata, curation, dedicatedMastersThreshold, ipFiltering, ccs);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ElasticsearchClusterSettings {\n");
sb.append(" snapshot: ").append(toIndentedString(snapshot)).append("\n");
sb.append(" monitoring: ").append(toIndentedString(monitoring)).append("\n");
sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n");
sb.append(" curation: ").append(toIndentedString(curation)).append("\n");
sb.append(" dedicatedMastersThreshold: ").append(toIndentedString(dedicatedMastersThreshold)).append("\n");
sb.append(" ipFiltering: ").append(toIndentedString(ipFiltering)).append("\n");
sb.append(" ccs: ").append(toIndentedString(ccs)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.css.model.api;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
/**
*
* @author marekfukala
*/
public class ModelVisitorTest extends ModelTestBase {
public ModelVisitorTest(String name) {
super(name);
}
@Test
public void testRules() {
final Set<Rule> rules = new HashSet<>();
ModelVisitor visitor = new ModelVisitor.Adapter() {
@Override
public void visitRule(Rule rule) {
rules.add(rule);
}
};
Model model = createModel("dir { color: red; }");
model.getStyleSheet().accept(visitor);
assertEquals(1, rules.size());
rules.clear();
model = createModel("@media screen { dir { color: red; } }");
model.getStyleSheet().accept(visitor);
assertEquals(1, rules.size());
}
}
|
/**
* Copyright © 2013-2021 The OpenNTF Domino API 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.openntf.domino.graph2.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Property annotations are for getter and setters to manipulate the property value of an Element. TypedProperty annotations are used to
* enforce type coercion on the results, provide for derived dynamic properties and allow for properties that must be specifically requested
* to return in services.
*
* @author Nathan T. Freeman
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ComputedProperty {
public String value();
public String computation() default "";
}
|
package com.dantsu.escposprinter.textparser;
import java.util.Hashtable;
import com.dantsu.escposprinter.EscPosPrinter;
import com.dantsu.escposprinter.EscPosPrinterCommands;
import com.dantsu.escposprinter.barcode.Barcode;
import com.dantsu.escposprinter.barcode.Barcode128;
import com.dantsu.escposprinter.barcode.BarcodeEAN13;
import com.dantsu.escposprinter.barcode.BarcodeEAN8;
import com.dantsu.escposprinter.barcode.BarcodeUPCA;
import com.dantsu.escposprinter.barcode.BarcodeUPCE;
import com.dantsu.escposprinter.exceptions.EscPosBarcodeException;
import com.dantsu.escposprinter.exceptions.EscPosEncodingException;
import com.dantsu.escposprinter.exceptions.EscPosParserException;
public class PrinterTextParserBarcode implements IPrinterTextParserElement {
private Barcode barcode;
private int length;
private byte[] align;
public PrinterTextParserBarcode(PrinterTextParserColumn printerTextParserColumn,
String textAlign,
Hashtable<String, String> barcodeAttributes,
String code) throws EscPosParserException, EscPosBarcodeException {
EscPosPrinter printer = printerTextParserColumn.getLine().getTextParser().getPrinter();
code = code.trim();
this.align = EscPosPrinterCommands.TEXT_ALIGN_LEFT;
switch (textAlign) {
case PrinterTextParser.TAGS_ALIGN_CENTER:
this.align = EscPosPrinterCommands.TEXT_ALIGN_CENTER;
break;
case PrinterTextParser.TAGS_ALIGN_RIGHT:
this.align = EscPosPrinterCommands.TEXT_ALIGN_RIGHT;
break;
}
this.length = printer.getPrinterNbrCharactersPerLine();
float height = 10f;
if (barcodeAttributes.containsKey(PrinterTextParser.ATTR_BARCODE_HEIGHT)) {
String barCodeAttribute = barcodeAttributes.get(PrinterTextParser.ATTR_BARCODE_HEIGHT);
if (barCodeAttribute == null) {
throw new EscPosParserException("Invalid barcode attribute: " + PrinterTextParser.ATTR_BARCODE_HEIGHT);
}
try {
height = Float.parseFloat(barCodeAttribute);
} catch (NumberFormatException nfe) {
throw new EscPosParserException("Invalid barcode " + PrinterTextParser.ATTR_BARCODE_HEIGHT + " value");
}
}
float width = 0f;
if (barcodeAttributes.containsKey(PrinterTextParser.ATTR_BARCODE_WIDTH)) {
String barCodeAttribute = barcodeAttributes.get(PrinterTextParser.ATTR_BARCODE_WIDTH);
if (barCodeAttribute == null) {
throw new EscPosParserException("Invalid barcode attribute: " + PrinterTextParser.ATTR_BARCODE_WIDTH);
}
try {
width = Float.parseFloat(barCodeAttribute);
} catch (NumberFormatException nfe) {
throw new EscPosParserException("Invalid barcode " + PrinterTextParser.ATTR_BARCODE_WIDTH + " value");
}
}
int textPosition = EscPosPrinterCommands.BARCODE_TEXT_POSITION_BELOW;
if (barcodeAttributes.containsKey(PrinterTextParser.ATTR_BARCODE_TEXT_POSITION)) {
String barCodeAttribute = barcodeAttributes.get(PrinterTextParser.ATTR_BARCODE_TEXT_POSITION);
if (barCodeAttribute == null) {
throw new EscPosParserException("Invalid barcode attribute: " + PrinterTextParser.ATTR_BARCODE_TEXT_POSITION);
}
switch (barCodeAttribute) {
case PrinterTextParser.ATTR_BARCODE_TEXT_POSITION_NONE:
textPosition = EscPosPrinterCommands.BARCODE_TEXT_POSITION_NONE;
break;
case PrinterTextParser.ATTR_BARCODE_TEXT_POSITION_ABOVE:
textPosition = EscPosPrinterCommands.BARCODE_TEXT_POSITION_ABOVE;
break;
}
}
String barcodeType = PrinterTextParser.ATTR_BARCODE_TYPE_EAN13;
if (barcodeAttributes.containsKey(PrinterTextParser.ATTR_BARCODE_TYPE)) {
barcodeType = barcodeAttributes.get(PrinterTextParser.ATTR_BARCODE_TYPE);
if (barcodeType == null) {
throw new EscPosParserException("Invalid barcode attribute : " + PrinterTextParser.ATTR_BARCODE_TYPE);
}
}
switch (barcodeType) {
case PrinterTextParser.ATTR_BARCODE_TYPE_EAN8:
this.barcode = new BarcodeEAN8(printer, code, width, height, textPosition);
break;
case PrinterTextParser.ATTR_BARCODE_TYPE_EAN13:
this.barcode = new BarcodeEAN13(printer, code, width, height, textPosition);
break;
case PrinterTextParser.ATTR_BARCODE_TYPE_UPCA:
this.barcode = new BarcodeUPCA(printer, code, width, height, textPosition);
break;
case PrinterTextParser.ATTR_BARCODE_TYPE_UPCE:
this.barcode = new BarcodeUPCE(printer, code, width, height, textPosition);
break;
case PrinterTextParser.ATTR_BARCODE_TYPE_128:
this.barcode = new Barcode128(printer, code, width, height, textPosition);
break;
default:
throw new EscPosParserException("Invalid barcode attribute : " + PrinterTextParser.ATTR_BARCODE_TYPE);
}
}
/**
* Get the barcode width in char length.
*
* @return int
*/
@Override
public int length() throws EscPosEncodingException {
return this.length;
}
/**
* Print barcode
*
* @param printerSocket Instance of EscPosPrinterCommands
* @return this Fluent method
*/
@Override
public PrinterTextParserBarcode print(EscPosPrinterCommands printerSocket) {
printerSocket
.setAlign(this.align)
.printBarcode(this.barcode);
return this;
}
}
|
/*******************************************************************************
* Copyright (c)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
/**
*/
package bvr.impl;
import bvr.BvrPackage;
import bvr.ChoiceOccurrence;
import bvr.ChoiceVSpec;
import bvr.NamedElement;
import bvr.Note;
import bvr.Target;
import bvr.VSpec;
import bvr.VType;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Choice Occurrence</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link bvr.impl.ChoiceOccurrenceImpl#getName <em>Name</em>}</li>
* <li>{@link bvr.impl.ChoiceOccurrenceImpl#getNote <em>Note</em>}</li>
* <li>{@link bvr.impl.ChoiceOccurrenceImpl#getResolutionTime <em>Resolution Time</em>}</li>
* <li>{@link bvr.impl.ChoiceOccurrenceImpl#getTarget <em>Target</em>}</li>
* <li>{@link bvr.impl.ChoiceOccurrenceImpl#isDefaultResolution <em>Default Resolution</em>}</li>
* <li>{@link bvr.impl.ChoiceOccurrenceImpl#isIsImpliedByParent <em>Is Implied By Parent</em>}</li>
* <li>{@link bvr.impl.ChoiceOccurrenceImpl#getVType <em>VType</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ChoiceOccurrenceImpl extends VNodeImpl implements ChoiceOccurrence {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getNote() <em>Note</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNote()
* @generated
* @ordered
*/
protected EList<Note> note;
/**
* The default value of the '{@link #getResolutionTime() <em>Resolution Time</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResolutionTime()
* @generated
* @ordered
*/
protected static final String RESOLUTION_TIME_EDEFAULT = null;
/**
* The cached value of the '{@link #getResolutionTime() <em>Resolution Time</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResolutionTime()
* @generated
* @ordered
*/
protected String resolutionTime = RESOLUTION_TIME_EDEFAULT;
/**
* The cached value of the '{@link #getTarget() <em>Target</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTarget()
* @generated
* @ordered
*/
protected Target target;
/**
* The default value of the '{@link #isDefaultResolution() <em>Default Resolution</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isDefaultResolution()
* @generated
* @ordered
*/
protected static final boolean DEFAULT_RESOLUTION_EDEFAULT = false;
/**
* The cached value of the '{@link #isDefaultResolution() <em>Default Resolution</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isDefaultResolution()
* @generated
* @ordered
*/
protected boolean defaultResolution = DEFAULT_RESOLUTION_EDEFAULT;
/**
* The default value of the '{@link #isIsImpliedByParent() <em>Is Implied By Parent</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isIsImpliedByParent()
* @generated
* @ordered
*/
protected static final boolean IS_IMPLIED_BY_PARENT_EDEFAULT = false;
/**
* The cached value of the '{@link #isIsImpliedByParent() <em>Is Implied By Parent</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isIsImpliedByParent()
* @generated
* @ordered
*/
protected boolean isImpliedByParent = IS_IMPLIED_BY_PARENT_EDEFAULT;
/**
* The cached value of the '{@link #getVType() <em>VType</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getVType()
* @generated
* @ordered
*/
protected VType vType;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ChoiceOccurrenceImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return BvrPackage.Literals.CHOICE_OCCURRENCE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BvrPackage.CHOICE_OCCURRENCE__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Note> getNote() {
if (note == null) {
note = new EObjectContainmentEList<Note>(Note.class, this, BvrPackage.CHOICE_OCCURRENCE__NOTE);
}
return note;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getResolutionTime() {
return resolutionTime;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setResolutionTime(String newResolutionTime) {
String oldResolutionTime = resolutionTime;
resolutionTime = newResolutionTime;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BvrPackage.CHOICE_OCCURRENCE__RESOLUTION_TIME, oldResolutionTime, resolutionTime));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Target getTarget() {
if (target != null && target.eIsProxy()) {
InternalEObject oldTarget = (InternalEObject)target;
target = (Target)eResolveProxy(oldTarget);
if (target != oldTarget) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, BvrPackage.CHOICE_OCCURRENCE__TARGET, oldTarget, target));
}
}
return target;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Target basicGetTarget() {
return target;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTarget(Target newTarget) {
Target oldTarget = target;
target = newTarget;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BvrPackage.CHOICE_OCCURRENCE__TARGET, oldTarget, target));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isDefaultResolution() {
return defaultResolution;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDefaultResolution(boolean newDefaultResolution) {
boolean oldDefaultResolution = defaultResolution;
defaultResolution = newDefaultResolution;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BvrPackage.CHOICE_OCCURRENCE__DEFAULT_RESOLUTION, oldDefaultResolution, defaultResolution));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isIsImpliedByParent() {
return isImpliedByParent;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIsImpliedByParent(boolean newIsImpliedByParent) {
boolean oldIsImpliedByParent = isImpliedByParent;
isImpliedByParent = newIsImpliedByParent;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BvrPackage.CHOICE_OCCURRENCE__IS_IMPLIED_BY_PARENT, oldIsImpliedByParent, isImpliedByParent));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VType getVType() {
if (vType != null && vType.eIsProxy()) {
InternalEObject oldVType = (InternalEObject)vType;
vType = (VType)eResolveProxy(oldVType);
if (vType != oldVType) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, BvrPackage.CHOICE_OCCURRENCE__VTYPE, oldVType, vType));
}
}
return vType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VType basicGetVType() {
return vType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setVType(VType newVType) {
VType oldVType = vType;
vType = newVType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BvrPackage.CHOICE_OCCURRENCE__VTYPE, oldVType, vType));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case BvrPackage.CHOICE_OCCURRENCE__NOTE:
return ((InternalEList<?>)getNote()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case BvrPackage.CHOICE_OCCURRENCE__NAME:
return getName();
case BvrPackage.CHOICE_OCCURRENCE__NOTE:
return getNote();
case BvrPackage.CHOICE_OCCURRENCE__RESOLUTION_TIME:
return getResolutionTime();
case BvrPackage.CHOICE_OCCURRENCE__TARGET:
if (resolve) return getTarget();
return basicGetTarget();
case BvrPackage.CHOICE_OCCURRENCE__DEFAULT_RESOLUTION:
return isDefaultResolution();
case BvrPackage.CHOICE_OCCURRENCE__IS_IMPLIED_BY_PARENT:
return isIsImpliedByParent();
case BvrPackage.CHOICE_OCCURRENCE__VTYPE:
if (resolve) return getVType();
return basicGetVType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case BvrPackage.CHOICE_OCCURRENCE__NAME:
setName((String)newValue);
return;
case BvrPackage.CHOICE_OCCURRENCE__NOTE:
getNote().clear();
getNote().addAll((Collection<? extends Note>)newValue);
return;
case BvrPackage.CHOICE_OCCURRENCE__RESOLUTION_TIME:
setResolutionTime((String)newValue);
return;
case BvrPackage.CHOICE_OCCURRENCE__TARGET:
setTarget((Target)newValue);
return;
case BvrPackage.CHOICE_OCCURRENCE__DEFAULT_RESOLUTION:
setDefaultResolution((Boolean)newValue);
return;
case BvrPackage.CHOICE_OCCURRENCE__IS_IMPLIED_BY_PARENT:
setIsImpliedByParent((Boolean)newValue);
return;
case BvrPackage.CHOICE_OCCURRENCE__VTYPE:
setVType((VType)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case BvrPackage.CHOICE_OCCURRENCE__NAME:
setName(NAME_EDEFAULT);
return;
case BvrPackage.CHOICE_OCCURRENCE__NOTE:
getNote().clear();
return;
case BvrPackage.CHOICE_OCCURRENCE__RESOLUTION_TIME:
setResolutionTime(RESOLUTION_TIME_EDEFAULT);
return;
case BvrPackage.CHOICE_OCCURRENCE__TARGET:
setTarget((Target)null);
return;
case BvrPackage.CHOICE_OCCURRENCE__DEFAULT_RESOLUTION:
setDefaultResolution(DEFAULT_RESOLUTION_EDEFAULT);
return;
case BvrPackage.CHOICE_OCCURRENCE__IS_IMPLIED_BY_PARENT:
setIsImpliedByParent(IS_IMPLIED_BY_PARENT_EDEFAULT);
return;
case BvrPackage.CHOICE_OCCURRENCE__VTYPE:
setVType((VType)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case BvrPackage.CHOICE_OCCURRENCE__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case BvrPackage.CHOICE_OCCURRENCE__NOTE:
return note != null && !note.isEmpty();
case BvrPackage.CHOICE_OCCURRENCE__RESOLUTION_TIME:
return RESOLUTION_TIME_EDEFAULT == null ? resolutionTime != null : !RESOLUTION_TIME_EDEFAULT.equals(resolutionTime);
case BvrPackage.CHOICE_OCCURRENCE__TARGET:
return target != null;
case BvrPackage.CHOICE_OCCURRENCE__DEFAULT_RESOLUTION:
return defaultResolution != DEFAULT_RESOLUTION_EDEFAULT;
case BvrPackage.CHOICE_OCCURRENCE__IS_IMPLIED_BY_PARENT:
return isImpliedByParent != IS_IMPLIED_BY_PARENT_EDEFAULT;
case BvrPackage.CHOICE_OCCURRENCE__VTYPE:
return vType != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == NamedElement.class) {
switch (derivedFeatureID) {
case BvrPackage.CHOICE_OCCURRENCE__NAME: return BvrPackage.NAMED_ELEMENT__NAME;
case BvrPackage.CHOICE_OCCURRENCE__NOTE: return BvrPackage.NAMED_ELEMENT__NOTE;
default: return -1;
}
}
if (baseClass == VSpec.class) {
switch (derivedFeatureID) {
case BvrPackage.CHOICE_OCCURRENCE__RESOLUTION_TIME: return BvrPackage.VSPEC__RESOLUTION_TIME;
case BvrPackage.CHOICE_OCCURRENCE__TARGET: return BvrPackage.VSPEC__TARGET;
default: return -1;
}
}
if (baseClass == ChoiceVSpec.class) {
switch (derivedFeatureID) {
case BvrPackage.CHOICE_OCCURRENCE__DEFAULT_RESOLUTION: return BvrPackage.CHOICE_VSPEC__DEFAULT_RESOLUTION;
case BvrPackage.CHOICE_OCCURRENCE__IS_IMPLIED_BY_PARENT: return BvrPackage.CHOICE_VSPEC__IS_IMPLIED_BY_PARENT;
default: return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == NamedElement.class) {
switch (baseFeatureID) {
case BvrPackage.NAMED_ELEMENT__NAME: return BvrPackage.CHOICE_OCCURRENCE__NAME;
case BvrPackage.NAMED_ELEMENT__NOTE: return BvrPackage.CHOICE_OCCURRENCE__NOTE;
default: return -1;
}
}
if (baseClass == VSpec.class) {
switch (baseFeatureID) {
case BvrPackage.VSPEC__RESOLUTION_TIME: return BvrPackage.CHOICE_OCCURRENCE__RESOLUTION_TIME;
case BvrPackage.VSPEC__TARGET: return BvrPackage.CHOICE_OCCURRENCE__TARGET;
default: return -1;
}
}
if (baseClass == ChoiceVSpec.class) {
switch (baseFeatureID) {
case BvrPackage.CHOICE_VSPEC__DEFAULT_RESOLUTION: return BvrPackage.CHOICE_OCCURRENCE__DEFAULT_RESOLUTION;
case BvrPackage.CHOICE_VSPEC__IS_IMPLIED_BY_PARENT: return BvrPackage.CHOICE_OCCURRENCE__IS_IMPLIED_BY_PARENT;
default: return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(", resolutionTime: ");
result.append(resolutionTime);
result.append(", defaultResolution: ");
result.append(defaultResolution);
result.append(", isImpliedByParent: ");
result.append(isImpliedByParent);
result.append(')');
return result.toString();
}
} //ChoiceOccurrenceImpl
|
package cn.eiden.hsm.controller;
import cn.eiden.hsm.controller.order.Invoker;
import cn.eiden.hsm.controller.order.OrderType;
import cn.eiden.hsm.output.HearthLinkContext;
import cn.eiden.hsm.output.OutputInfo;
import cn.eiden.hsm.util.EnumUtils;
import java.util.Objects;
/**
* @author Eiden J.P Zhou
* @date 2020/4/30 8:53
*/
public class TemplateController {
private Invoker gamerInvoker;
private Invoker enemyInvoker;
private Invoker nowInvoker;
private boolean finishFlag;
public TemplateController(Invoker gamerInvoker, Invoker enemyInvoker) {
this.gamerInvoker = gamerInvoker;
this.enemyInvoker = enemyInvoker;
this.finishFlag = false;
}
public void gameStart(boolean b) {
nowInvoker = b ? gamerInvoker : enemyInvoker;
while (!finishFlag) {
runTurn();
}
}
/**
* 切换当前执行者
*/
private void reverseInvoker() {
nowInvoker = nowInvoker == gamerInvoker ? enemyInvoker : gamerInvoker;
}
/**
* 开始一个新回合
*/
private void runTurn() {
// if (nowInvoker == enemyInvoker){
// OutputInfo.info("测试模式下跳过对手回合");
// this.reverseInvoker();
// return;
// }
if (nowInvoker.getGamer().getInputMessageQueue() != null){
nowInvoker.getGamer().getInputMessageQueue().clear();
}
nowInvoker.callStartTurn();
boolean endTurnFlag = false;
while (!endTurnFlag) {
nowInvoker.callHelp();
final String poll = waitOrder();
OrderType orderType = Objects.requireNonNull(EnumUtils.getEnumObject(
OrderType.class,
e -> e.getCode().equals(poll)))
.orElse(OrderType.INVALID);
redirectOrder(orderType);
if (orderType == OrderType.END) {
endTurnFlag = true;
this.reverseInvoker();
}
}
}
/**
* 等待命令
*/
private String waitOrder() {
String order = "";
try {
if (nowInvoker.getGamer().getInputMessageQueue() != null){
order = nowInvoker.getGamer().getInputMessageQueue().take();
}else {
order = HearthLinkContext.inputMessage.take();
}
} catch (InterruptedException e) {
nowInvoker.getGamer().printPublicQueue(e.getMessage());
}
return order;
}
/**
* 命令分派
*/
void redirectOrder(OrderType orderType) {
switch (orderType) {
case END:
nowInvoker.callEnd();
break;
case PLAY:
nowInvoker.callPlay();
break;
case HERO_POWER:
nowInvoker.callSpell();
break;
case ATK:
nowInvoker.callAtk();
break;
case HELP:
nowInvoker.callHelp();
break;
case SHOW:
nowInvoker.callShow();
case INVALID:
default:
}
}
}
|
package com.zxf.lib_android.views;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zxf.lib_android.R;
/**
* Created by zxf on 2019/8/13.
*/
public class ScalableText extends LinearLayout {
protected TextView contentView; //文本正文
protected TextView expandView; //展开按钮
//对应styleable中的属性
protected int textColor;
protected float textSize;
protected int maxLine;
protected String text;
//默认属性值
public int defaultTextColor = Color.BLACK;
public int defaultTextSize = 12;
public int defaultLine = 4;
public int blueColor = Color.parseColor("#0000ff");
public int defaultBottomSpace = 4;
public ScalableText(Context context) {
super(context, null);
init();
bindTextView(defaultTextColor, defaultTextSize, defaultLine, text);
initAttr(context, null);
bindListener();
}
public ScalableText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
bindTextView(defaultTextColor, defaultTextSize, defaultLine, text);
initAttr(context, attrs);
bindListener();
}
public ScalableText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
bindTextView(defaultTextColor, defaultTextSize, defaultLine, text);
initAttr(context, attrs);
bindListener();
}
private void init() {
setOrientation(VERTICAL); //设置垂直布局
setGravity(Gravity.LEFT); //左对齐
int padding = dip2px(getContext(), 5);
final int space = dip2px(getContext(), defaultBottomSpace);
//初始化textView并添加
contentView = new TextView(getContext());
LayoutParams llpContent = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
contentView.setLayoutParams(llpContent);
addView(contentView, llpContent);
//初始化“展开/收起”文本并添加
expandView = new TextView(getContext());
LayoutParams llp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(0, padding, 0, 0);
expandView.setLayoutParams(llp);
expandView.setText("全文");
addView(expandView, llp);
expandView.setOnClickListener(new OnClickListener() {
boolean isExpand;// 是否折叠
@Override
public void onClick(View v) {
isExpand = !isExpand;
contentView.clearAnimation();
final int deltaValue;// 动画执行的相对距离
final int startValue = contentView.getHeight();// 开始的距离
int durationMillis = 200;
if (isExpand) {
deltaValue = contentView.getLineHeight() * contentView.getLineCount() - startValue + space;
// RotateAnimation animation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// animation.setDuration(durationMillis);
// animation.setFillAfter(true);
// expandView.startAnimation(animation);
expandView.setText("收起");
} else {
deltaValue = contentView.getLineHeight() * maxLine - startValue + space;
// RotateAnimation animation = new RotateAnimation(180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// animation.setDuration(durationMillis);
// animation.setFillAfter(true);
// expandView.startAnimation(animation);
expandView.setText("全文");
}
Animation animation = new Animation() {
protected void applyTransformation(float interpolatedTime, Transformation t) {
contentView.setHeight((int) (startValue + deltaValue * interpolatedTime));
}
};
animation.setDuration(durationMillis);
contentView.startAnimation(animation);
}
});
}
private void initAttr(Context context, AttributeSet attrs) {
if (null == attrs) {
return;
}
@SuppressLint("CustomViewStyleable") TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ScalableTextStyle);
textColor = typedArray.getColor(R.styleable.ScalableTextStyle_textColor, defaultTextColor); //取颜色值,默认defaultTextColor
textSize = typedArray.getDimensionPixelSize(R.styleable.ScalableTextStyle_textSize, defaultTextSize);//取颜字体大小,默认defaultTextSize
maxLine = typedArray.getInt(R.styleable.ScalableTextStyle_maxLine, defaultLine);//取颜显示行数,默认defaultLine
text = typedArray.getString(R.styleable.ScalableTextStyle_text);//取文本内容
//绑定到textView bindTextView(textColor,textSize,maxLine,text);
typedArray.recycle();//回收释放
}
//绑定到textView
protected void bindTextView(int color, float size, final int line, String text) {
contentView.setTextColor(color);
contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
contentView.setText(text);
int space = dip2px(getContext(), defaultBottomSpace);
contentView.setHeight(contentView.getLineHeight() * line + space);
expandView.setTextColor(blueColor);
post(new Runnable() {
@Override
public void run() {
// 由于在OnCreate方法中定义设置的textView不会马上渲染并显示,
// 所以textview的getLineCount()获取到的值一般都为零,
// 因此使用post会在其绘制完成后对 TextView(展开、收起) 进行显示控制
int visible = contentView.getLineCount() > line ? View.VISIBLE : View.GONE;
expandView.setVisibility(visible);
}
});
}
protected void bindListener() {
setOnClickListener(new OnClickListener() {
boolean isExpand;// 是否折叠
@Override
public void onClick(View v) {
}
});
}
public TextView getTextView() {
return contentView;
}
public void setText(CharSequence charSequence) {
contentView.setText(charSequence);
}
private int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}
|
/*
* Copyright 2013-2018 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.netflix.hystrix;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.actuate.endpoint.web.EndpointServlet;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpoint;
import java.util.Map;
import java.util.function.Supplier;
/**
* {@link org.springframework.boot.actuate.endpoint.annotation.Endpoint} to expose a Jolokia {@link HystrixMetricsStreamServlet}.
*
* @author Phillip Webb
* @since 2.0.0
*/
@ServletEndpoint(id = "hystrix.stream")
public class HystrixStreamEndpoint implements Supplier<EndpointServlet> {
private final Map<String, String> initParameters;
public HystrixStreamEndpoint(Map<String, String> initParameters) {
this.initParameters = initParameters;
}
@Override
public EndpointServlet get() {
return new EndpointServlet(HystrixMetricsStreamServlet.class)
.withInitParameters(this.initParameters);
}
}
|
package com.mapfinal.resource;
import com.mapfinal.MapfinalObject;
/**
* 数据集
* @author yangyong
*
*/
public interface DataSet extends MapfinalObject {
String getName();
}
|
/* ###
* IP: GHIDRA
*
* 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 ghidra.framework.options;
import static org.junit.Assert.*;
import java.awt.Color;
import java.awt.Font;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.util.*;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import org.jdom.Element;
import org.junit.*;
import generic.test.AbstractGenericTest;
import ghidra.util.HelpLocation;
import ghidra.util.bean.opteditor.OptionsVetoException;
import ghidra.util.exception.InvalidInputException;
public class OptionsTest extends AbstractGenericTest {
public enum FRUIT {
Apple, Orange, Pear
}
private ToolOptions options;
public OptionsTest() {
super();
}
@Before
public void setUp() throws Exception {
options = new ToolOptions("Test");
}
@Test
public void testGettingDefaultWhenNoOptionsExist() {
assertEquals(5, options.getInt("Foo", 5));
}
@Test
public void testGetName() {
assertEquals("Test", options.getName());
}
@Test
public void testGettingValueWhenAlreadySet() {
options.setInt("Foo", 32);
assertEquals(32, options.getInt("Foo", 5));
}
@Test
public void testDefaultsNotSaved() {
options.registerOption("Foo", 5, null, null);
assertTrue(options.contains("Foo"));
assertEquals(5, options.getInt("Foo", 0));
saveAndRestoreOptions();
assertFalse(options.contains("Foo"));
}
@Test
public void testMixingTypesForSameName() {
options.setInt("Foo", 5);
try {
options.getString("Foo", "Default");
Assert.fail("Expected Illegal State Exception");
}
catch (IllegalStateException e) {
// expected
}
}
@Test
public void testSaveIntOption() {
options.setInt("Foo", 32);
saveAndRestoreOptions();
assertEquals(32, options.getInt("Foo", 5));
}
@Test
public void testSaveLongOption() {
options.setLong("Foo", 5);
saveAndRestoreOptions();
assertEquals(5, options.getLong("Foo", 5));
}
@Test
public void testSaveFloatOption() {
options.setFloat("Foo", (float) 5.3);
saveAndRestoreOptions();
assertEquals((float) 5.3, options.getFloat("Foo", 0), 0);
}
@Test
public void testSaveDoubleOption() {
options.setDouble("Foo", 5.3);
saveAndRestoreOptions();
assertEquals(5.3, options.getDouble("Foo", 0), 0);
}
@Test
public void testSaveBooleanOption() {
options.setBoolean("Bool", true);
saveAndRestoreOptions();
assertEquals(true, options.getBoolean("Bool", false));
}
@Test
public void testSaveStringOption() {
options.setString("Foo", "Hey");
saveAndRestoreOptions();
assertEquals("Hey", options.getString("Foo", "Default"));
}
@Test
public void testSaveByteArray() {
byte[] bytes = new byte[] { (byte) 1, (byte) 2, (byte) 3 };
options.setByteArray("BYTES", bytes);
saveAndRestoreOptions();
assertTrue(Arrays.equals(bytes, options.getByteArray("BYTES", null)));
}
@Test
public void testSaveColorOption() {
options.setColor("Foo", Color.RED);
saveAndRestoreOptions();
assertEquals(Color.RED, options.getColor("Foo", Color.BLUE));
}
@Test
public void testSaveFileOption() {
File file = new File("/Users/foo").getAbsoluteFile();
options.setFile("Foo", file);
saveAndRestoreOptions();
assertEquals(file, options.getFile("Foo", new File("/")));
}
@Test
public void testSaveDateOption() {
Date date = new Date();
options.setDate("Foo", date);
saveAndRestoreOptions();
assertEquals(date, options.getDate("Foo", new Date()));
}
@Test
public void testSaveKeyStrokeOption() {
options.setKeyStroke("Foo", KeyStroke.getKeyStroke('a', 0));
saveAndRestoreOptions();
assertEquals(KeyStroke.getKeyStroke('a', 0),
options.getKeyStroke("Foo", KeyStroke.getKeyStroke('b', 0)));
}
@Test
public void testSaveFontOption() {
Font font = new Font("Monospaced", Font.BOLD, 12);
options.setFont("Foo", font);
saveAndRestoreOptions();
assertEquals(font, options.getFont("Foo", null));
}
@Test
public void testSaveCustomOption() {
MyCustomOption option = new MyCustomOption(7);
options.setCustomOption("Foo", option);
assertEquals(option, options.getCustomOption("Foo", new MyCustomOption(3)));
saveAndRestoreOptions();
assertEquals(option, options.getCustomOption("Foo", new MyCustomOption(3)));
}
@Test
public void testSaveEnumOption() {
options.setEnum("SNACK", FRUIT.Orange);
assertEquals(FRUIT.Orange, options.getEnum("SNACK", (FRUIT) null));
saveAndRestoreOptions();
assertEquals(FRUIT.Orange, options.getEnum("SNACK", (FRUIT) null));
}
@Test
public void testCopy() {
options.setInt("Foo", 3);
options.setColor("COLOR", Color.RED);
options.getLong("LONG", 10);
options.registerOption("Bar", true, null, null);
Options optionsCopy = options.copy();
assertTrue(optionsCopy.contains("Foo"));
assertTrue(optionsCopy.contains("COLOR"));
assertTrue(optionsCopy.contains("LONG"));
assertTrue(optionsCopy.contains("Bar"));
assertEquals(3, optionsCopy.getInt("Foo", 3));
}
@Test
public void testHasNonDefaultValues() {
assertFalse(hasNonDefaultValues(options));
options.getLong("LONG", 10);
assertFalse(hasNonDefaultValues(options));
options.setLong("LONG", 3);
assertTrue(hasNonDefaultValues(options));
}
private boolean hasNonDefaultValues(Options opts) {
List<String> optionNames = opts.getOptionNames();
for (String string : optionNames) {
if (!opts.isDefaultValue(string)) {
return true;
}
}
return false;
}
@Test
public void testPuttingNonSaveableObject() {
try {
options.putObject("FOO", new Object());
Assert.fail("Should not have been able to put a non-saveable object");
}
catch (Exception e) {
// expected
}
}
@Test
public void testVeto() {
options.setColor("COLOR", Color.RED);
OptionsChangeListenerForTestVeto listener1 = new OptionsChangeListenerForTestVeto();
OptionsChangeListenerForTestVeto listener2 = new OptionsChangeListenerForTestVeto();
options.addOptionsChangeListener(listener1);
options.addOptionsChangeListener(listener2);
options.setColor("COLOR", Color.BLUE);
assertEquals(Color.RED, options.getColor("COLOR", Color.RED));
if (listener1.callOrder == 1) {
assertEquals(Color.RED, listener1.value);
assertEquals(null, listener2.value);
}
if (listener2.callOrder == 1) {
assertEquals(Color.RED, listener2.value);
assertEquals(null, listener1.value);
}
}
@Test
public void testRemove() {
options.setColor("COLOR", Color.RED);
assertTrue(options.contains("COLOR"));
options.removeOption("COLOR");
assertTrue(!options.contains("COLOR"));
}
@Test
public void testGetOptionNames() {
options.setColor("COLOR", Color.red);
options.setInt("INT", 3);
List<String> optionNames = options.getOptionNames();
assertEquals(2, optionNames.size());
assertTrue((optionNames.get(0).equals("INT") && optionNames.get(1).equals("COLOR")) ||
(optionNames.get(0).equals("COLOR") && optionNames.get(1).equals("INT")));
}
@Test
public void testGetDefaultValue() {
options.registerOption("Foo", Color.RED, null, null);
options.setColor("Foo", Color.BLUE);
assertEquals(Color.BLUE, options.getColor("Foo", null));
assertEquals(Color.RED, options.getDefaultValue("Foo"));
}
@Test
public void testRegisterPropertyEditor() {
MyPropertyEditor editor = new MyPropertyEditor();
options.registerOption("color", OptionType.COLOR_TYPE, Color.RED, null, null, editor);
assertEquals(editor, options.getRegisteredPropertyEditor("color"));
}
@Test
public void testGetHelpLocation() {
HelpLocation helpLocation = new HelpLocation("topic", "anchor");
options.registerOption("Foo", 3, helpLocation, null);
assertEquals(helpLocation, options.getHelpLocation("Foo"));
}
@Test
public void testRestoreOptionValue() {
options.registerOption("Foo", Color.RED, null, null);
options.setColor("Foo", Color.BLUE);
assertEquals(Color.BLUE, options.getColor("Foo", null));
options.restoreDefaultValue("Foo");
assertEquals(Color.RED, options.getColor("Foo", null));
}
@Test
public void testOptionsHelp() {
assertNull(options.getOptionsHelpLocation());
HelpLocation helpLocation = new HelpLocation("topic", "anchor");
options.setOptionsHelpLocation(helpLocation);
assertEquals(helpLocation, options.getOptionsHelpLocation());
Options subOptions = options.getOptions("SUB");
assertNull(subOptions.getOptionsHelpLocation());
subOptions.setOptionsHelpLocation(helpLocation);
assertEquals(helpLocation, subOptions.getOptionsHelpLocation());
}
@Test
public void testIllegalNames() {
try {
options.setInt("a..b", 3);
Assert.fail("Didn't catch bad option name");
}
catch (Exception e) {
//expected
}
try {
options.setInt(".a", 3);
Assert.fail("Didn't catch bad option name");
}
catch (Exception e) {
//expected
}
try {
options.setInt("a.", 3);
Assert.fail("Didn't catch bad option name");
}
catch (Exception e) {
//expected
}
}
@Test
public void testIsDefaultValue() {
assertTrue(options.isDefaultValue("Foo"));
options.getInt("Foo", 2);
assertTrue(options.isDefaultValue("Foo"));
options.setInt("Foo", 3);
assertTrue(!options.isDefaultValue("Foo"));
}
@Test
public void testIsRegistered() {
assertTrue(!options.isRegistered("Foo"));
options.setInt("Foo", 3);
assertTrue(options.isRegistered("Foo"));
assertTrue(!options.isRegistered("Bar"));
options.getInt("Bar", 10);
assertTrue(!options.isRegistered("Bar"));
assertTrue(!options.isRegistered("aaa"));
options.registerOption("aaa", 3, null, null);
assertTrue(options.isRegistered("aaa"));
}
@Test
public void testRestoreDefaults() {
options.registerOption("Foo", 10, null, null);
options.setInt("Foo", 2);
options.registerOption("Bar", 100, null, null);
options.setInt("Bar", 1);
options.restoreDefaultValues();
assertEquals(10, options.getInt("Foo", 0));
assertEquals(100, options.getInt("Bar", 0));
}
@Test
public void testDescription() {
assertEquals("Unregistered Option", options.getDescription("Foo"));
options.registerOption("Foo", 5, null, "Hey");
assertEquals("Hey", options.getDescription("Foo"));
options.setInt("Foo", 3);
assertEquals("Hey", options.getDescription("Foo"));
options.registerOption("Foo", 7, null, "There");// first register wins!
assertEquals("Hey", options.getDescription("Foo"));
}
@Test
public void testIsEmpty() {
assertTrue(options.getOptionNames().isEmpty());
options.setInt("Foo", 3);
assertTrue(!options.getOptionNames().isEmpty());
}
@Test
public void testRemoveUnusedOptions() {
options.setBoolean("Foo", false);
options.setInt("Bar", 3);
assertTrue(options.contains("Foo"));
assertTrue(options.contains("Bar"));
saveAndRestoreOptions();
assertTrue(options.contains("Foo"));
assertTrue(options.contains("Bar"));
options.registerOption("Bar", 0, null, null);
options.removeUnusedOptions();
assertFalse(options.contains("Foo"));
assertTrue(options.contains("Bar"));
}
@Test
public void testCopyOptions() {
options.setInt("INT", 3);
options.setColor("COLOR", Color.RED);
ToolOptions options2 = new ToolOptions("aaa");
options2.copyOptions(options);
assertEquals(3, options.getInt("INT", 3));
assertEquals(Color.RED, options.getColor("COLOR", null));
}
@Test
public void testSubOptions() {
options.setInt("Z", 1);
options.setInt("A.B", 2);
options.setInt("A.D.E", 3);
options.setInt("B.F", 4);
List<Options> childOptions = options.getChildOptions();
assertEquals(2, childOptions.size());
assertEquals("A", childOptions.get(0).getName());
assertEquals("B", childOptions.get(1).getName());
Options childOptions0 = childOptions.get(0);
List<String> optionNames = childOptions0.getOptionNames();
assertEquals(2, optionNames.size());
assertEquals("B", optionNames.get(0));
assertEquals("D.E", optionNames.get(1));
List<Options> grandChildOptions = childOptions0.getChildOptions();
assertEquals(1, grandChildOptions.size());
assertEquals("E", grandChildOptions.get(0).getOptionNames().get(0));
assertEquals(3, grandChildOptions.get(0).getInt("E", 0));
}
@Test
public void testAlias() {
options.setInt("AAA", 4);
options.createAlias("BBB", options, "AAA");
assertEquals(4, options.getInt("BBB", 0));
assertTrue(options.isAlias("BBB"));
assertFalse(options.isAlias("AAA"));
}
@Test
public void testAliasAcrossSubOptions() {
Options fooOptions = options.getOptions("Foo");
Options barOptions = options.getOptions("Bar");
fooOptions.setInt("XXX", 5);
barOptions.createAlias("YYY", fooOptions, "XXX");
assertEquals(5, barOptions.getInt("YYY", 0));
barOptions.setInt("YYY", 10);
assertEquals(10, fooOptions.getInt("XXX", 0));
}
@Test
public void testGetLeafOptionNames() {
options.setInt("aaa", 5);
options.setInt("bbb", 6);
options.setInt("ccc.ddd", 10);
List<String> leafOptionNames = options.getLeafOptionNames();
assertEquals(2, leafOptionNames.size());
assertTrue(leafOptionNames.contains("aaa"));
assertTrue(leafOptionNames.contains("bbb"));
}
@Test
public void testGetLeafOptionNamesInSubOptions() {
Options subOptions = options.getOptions("foo");
subOptions.setInt("aaa", 5);
subOptions.setInt("bbb", 6);
subOptions.setInt("ccc.ddd", 10);
List<String> leafOptionNames = subOptions.getLeafOptionNames();
assertEquals(2, leafOptionNames.size());
assertTrue(leafOptionNames.contains("aaa"));
assertTrue(leafOptionNames.contains("bbb"));
}
@Test
public void testGetID() {
Options subOptions = options.getOptions("foo");
subOptions.setInt("aaa", 5);
assertEquals("Test.foo.aaa", subOptions.getID("aaa"));
}
@Test
public void testGetValueAsString() {
options.setInt("foo", 5);
assertEquals("5", options.getValueAsString("foo"));
assertNull(options.getValueAsString("bar"));
}
@Test
public void testGetDefaultValueAsString() {
options.registerOption("foo", 7, null, null);
options.setInt("foo", 5);
assertEquals("7", options.getDefaultValueAsString("foo"));
assertNull(options.getDefaultValueAsString("bar"));
}
@Test
public void testResgisteringOptionWithNullValue() {
try {
options.registerOption("Foo", null, null, null);
Assert.fail("Should not be able to register an options with a default value");
}
catch (IllegalArgumentException e) {
// expected
}
}
@Test
public void testRegisteringOptionWithUnsupportedType() {
try {
options.registerOption("Foo", new ArrayList<String>(), null, null);
Assert.fail(
"Should not be able to register an options with an ArrayList as a default value");
}
catch (IllegalArgumentException e) {
// expected
}
}
@Test
public void testRegisteringOptionWithTypeNone() {
try {
options.registerOption("Foo", OptionType.NO_TYPE, null, null, null);
Assert.fail("Should not be able to register an options of type NONE");
}
catch (IllegalArgumentException e) {
// expected
}
}
@Test
public void testRegisteringOptionsEditor() {
MyOptionsEditor myOptionsEditor = new MyOptionsEditor();
options.registerOptionsEditor(myOptionsEditor);
assertEquals(myOptionsEditor, options.getOptionsEditor());
Options subOptions = options.getOptions("SUB");
subOptions.registerOptionsEditor(myOptionsEditor);
assertEquals(myOptionsEditor, subOptions.getOptionsEditor());
}
@Test
public void testSettingValueToNull() {
options.setColor("Bar", Color.red);
options.setColor("Bar", null);
assertEquals(null, options.getColor("Bar", null));
}
@Test
public void testNullValueWillUsedPassedInDefault() {
options.setColor("Bar", Color.red);
options.setColor("Bar", null);
assertEquals(Color.BLUE, options.getColor("Bar", Color.BLUE));
}
@Test
public void testGetType() {
options.setInt("fool", 5);
assertEquals(OptionType.INT_TYPE, options.getType("fool"));
assertEquals(OptionType.NO_TYPE, options.getType("bar"));// there is no bar
}
private void saveAndRestoreOptions() {
Element root = options.getXmlRoot(false);
options = new ToolOptions(root);
}
private static class OptionsChangeListenerForTestVeto implements OptionsChangeListener {
static int count = 0;
private Object value;
private int callOrder = -1;
@Override
public void optionsChanged(ToolOptions options, String optionName, Object oldValue,
Object newValue) {
if (callOrder < 0) {
callOrder = ++count;
}
if (callOrder > 1) {
throw new OptionsVetoException("Test");
}
value = newValue;
}
@Override
public int hashCode() {
return 1;// set so that this listener gets called after the storingOptionsListener
}
}
private static class MyCustomOption implements CustomOption {
int value;
@SuppressWarnings("unused")
MyCustomOption() {
// used by reflection
}
MyCustomOption(int value) {
this.value = value;
}
@Override
public void readState(SaveState saveState) {
value = saveState.getInt("VALUE", 0);
}
@Override
public void writeState(SaveState saveState) {
saveState.putInt("VALUE", value);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MyCustomOption) {
return ((MyCustomOption) obj).value == value;
}
return false;
}
@Override
public int hashCode() {
return 0;
}
}
static class MyOptionsEditor implements OptionsEditor {
@Override
public void apply() throws InvalidInputException {
// dummy
}
@Override
public void dispose() {
// dummy
}
@Override
public void cancel() {
// dummy
}
@Override
public void reload() {
// dummy
}
@Override
public void setOptionsPropertyChangeListener(PropertyChangeListener listener) {
// dummy
}
@Override
public JComponent getEditorComponent(Options options,
EditorStateFactory editorStateFactory) {
return null;
}
}
public static class MyPropertyEditor extends PropertyEditorSupport {
// stub
}
}
|
// ***********************************************************************
// TestServo
// ***********************************************************************
// Manages the testing of a single servo on a robot
package org.firstinspires.ftc.teamcode.testing;
import com.qualcomm.robotcore.hardware.Servo;
public class TestServo {
private Servo servo;
private String sName;
private Boolean isCR;
private double targetValue;
// Create a version of a motor, tracking the motor to use and the name
public TestServo( Servo useServo, Boolean isContinuousRotation, String useName ){
this.servo = useServo;
this.sName = useName;
this.isCR = isContinuousRotation;
// stop any movement
stopMoving();
}
public String getName() {
return sName;
}
public double getTarget() {
return targetValue;
}
// set the servo speed/position
public void setPosition( double newPosition ){
double workPosition;
targetValue = newPosition;
// set the servo based on a scaled position
// -- incoming data is -1 to 1, shift to 0 to 1
workPosition = ( newPosition / 2.0 ) + 0.5;
if ( workPosition < 0.0 ) {
workPosition = 0;
} else if ( workPosition > 1.0 ) {
workPosition = 1.0;
}
servo.setPosition( workPosition );
}
// give a general way to stop movement
public void stopMoving() {
// stop any movement
// ... for non-CR servos, we do NOTHING
if ( isCR ) {
this.setPosition( 0 );
}
}
}
|
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import kidozen.client.DataSource;
import kidozen.client.KZApplication;
import kidozen.client.ServiceEvent;
import kidozen.client.ServiceEventListener;
import kidozen.client.ServiceResponseListener;
import kidozen.client.SynchronousException;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
/**
* Created by christian on 2/28/14.
*/
@RunWith(RobolectricTestRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Config(manifest= Config.NONE)
public class DsSyncTest {
public static final int TEST_TIMEOUT_IN_SECONDS = 10;
private static final String INVOKE_DATA_SOURCE_NAME = "InvokeCityWeather";
private static final String QUERY_DATA_SOURCE_NAME = "GetCityWeather";
KZApplication kidozen = null;
JSONObject data;
@Before
public void Setup()
{
try {
data = new JSONObject().put("city", "London");
final CountDownLatch signal = new CountDownLatch(1);
kidozen = new KZApplication(AppSettings.KZ_TENANT, AppSettings.KZ_APP, AppSettings.KZ_KEY, false);
kidozen.Authenticate(AppSettings.KZ_USER, AppSettings.KZ_PASS,AppSettings.KZ_PROVIDER, kidoAuthCallback(signal));
signal.await(TEST_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
}
catch (Exception e)
{
fail(e.getMessage());
}
}
@Test
public void ShouldExecuteInvokeWithParameters() throws Exception, SynchronousException {
DataSource dataSource = kidozen.DataSource(INVOKE_DATA_SOURCE_NAME);
try {
JSONObject result = dataSource.Invoke(data);
assertTrue(result.toString().contains("London"));
} catch (SynchronousException e) {
fail();
}
}
@Test
public void ShouldExecuteInvokeWithDefaults() throws Exception, SynchronousException {
DataSource dataSource = kidozen.DataSource(INVOKE_DATA_SOURCE_NAME);
try {
JSONObject result = dataSource.Invoke();
assertTrue(result.toString().contains("Buenos Aires"));
} catch (SynchronousException e) {
fail();
}
}
@Test
public void ShouldExecuteQueryWithParameters() throws Exception{
DataSource dataSource = kidozen.DataSource(QUERY_DATA_SOURCE_NAME);
try {
JSONObject result = dataSource.Query(data);
assertTrue(result.toString().contains("London"));
} catch (SynchronousException e) {
fail();
}
}
@Test
public void ShouldExecuteQueryWithDefaults() throws Exception {
DataSource dataSource = kidozen.DataSource(QUERY_DATA_SOURCE_NAME);
try {
JSONObject result = dataSource.Query();
assertTrue(result.toString().contains("Buenos Aires"));
} catch (ExecutionException e) {
fail();
} catch (InterruptedException e) {
fail();
} catch (SynchronousException e) {
fail();
}
}
private ServiceEventListener kidoAuthCallback(final CountDownLatch signal) {
return new ServiceEventListener() {
@Override
public void onFinish(ServiceEvent e) {
assertThat(e.StatusCode, equalTo( HttpStatus.SC_OK));
signal.countDown();
}
};
}
}
|
package slimeknights.tconstruct.smeltery.data;
import lombok.Getter;
import net.minecraft.item.Item;
import net.minecraftforge.fluids.ForgeFlowingFluid;
import slimeknights.mantle.registration.object.FluidObject;
import slimeknights.tconstruct.fluids.TinkerFluids;
import java.util.Locale;
/** Enum holding all relevant smeltery compat */
public enum SmelteryCompat {
// ores
TIN (TinkerFluids.moltenTin, true, Byproduct.COPPER),
ALUMINUM(TinkerFluids.moltenAluminum, true, Byproduct.IRON),
LEAD (TinkerFluids.moltenLead, true, Byproduct.SILVER, Byproduct.GOLD),
SILVER (TinkerFluids.moltenSilver, true, Byproduct.LEAD, Byproduct.GOLD),
NICKEL (TinkerFluids.moltenNickel, true, Byproduct.PLATINUM, Byproduct.IRON),
ZINC (TinkerFluids.moltenZinc, true, Byproduct.TIN, Byproduct.COPPER),
PLATINUM(TinkerFluids.moltenPlatinum, true, Byproduct.GOLD),
TUNGSTEN(TinkerFluids.moltenTungsten, true, Byproduct.PLATINUM, Byproduct.GOLD),
OSMIUM (TinkerFluids.moltenOsmium, true, Byproduct.IRON),
URANIUM (TinkerFluids.moltenUranium, true, Byproduct.LEAD, Byproduct.COPPER),
// alloys
BRONZE (TinkerFluids.moltenBronze, false),
BRASS (TinkerFluids.moltenBrass, false),
ELECTRUM (TinkerFluids.moltenElectrum, false),
INVAR (TinkerFluids.moltenInvar, false),
CONSTANTAN(TinkerFluids.moltenConstantan, false),
PEWTER (TinkerFluids.moltenPewter, false),
STEEL (TinkerFluids.moltenSteel, false);
@Getter
private final String name = this.name().toLowerCase(Locale.US);
private final FluidObject<? extends ForgeFlowingFluid> fluid;
@Getter
private final boolean isOre;
@Getter
private final Byproduct[] byproducts;
SmelteryCompat(FluidObject<? extends ForgeFlowingFluid> fluid, boolean isOre, Byproduct... byproducts) {
this.fluid = fluid;
this.isOre = isOre;
this.byproducts = byproducts;
}
/** Gets teh fluid for this compat */
public ForgeFlowingFluid getFluid() {
return fluid.get();
}
/** Gets teh bucket for this compat */
public Item getBucket() {
return fluid.asItem();
}
}
|
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Denise Smith - October 2012
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.unmarshaller.autodetect;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.eclipse.persistence.oxm.MediaType;
import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases;
public class AutoDetectFailsTestCases extends AutoDetectMediaTypeTestCases {
private final static String XML_RESOURCE = "org/eclipse/persistence/testing/jaxb/unmarshaller/autodetect/employee-collection-fails.xml";
private final static String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/unmarshaller/autodetect/employee-collection-fails.json";
public AutoDetectFailsTestCases(String name) throws Exception {
super(name);
setControlDocument(XML_RESOURCE);
setControlJSON(JSON_RESOURCE);
jaxbUnmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
}
public MediaType getXMLUnmarshalMediaType(){
return MediaType.APPLICATION_XML;
}
public MediaType getJSONUnmarshalMediaType(){
return MediaType.APPLICATION_JSON;
}
}
|
/*
* 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.ens.model.v20171110;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
/**
* @author auto create
* @version
*/
public class CreateLoadBalancerTCPListenerRequest extends RpcAcsRequest<CreateLoadBalancerTCPListenerResponse> {
private String healthCheckURI;
private Integer establishedTimeout;
private Integer persistenceTimeout;
private String healthCheckDomain;
private String loadBalancerId;
private Integer healthCheckInterval;
private Integer backendServerPort;
private Integer healthCheckConnectTimeout;
private String description;
private Integer unhealthyThreshold;
private Integer healthyThreshold;
private String scheduler;
private String eipTransmit;
private Integer listenerPort;
private String healthCheckType;
private String healthCheckHttpCode;
private Integer healthCheckConnectPort;
public CreateLoadBalancerTCPListenerRequest() {
super("Ens", "2017-11-10", "CreateLoadBalancerTCPListener", "ens");
setMethod(MethodType.POST);
}
public String getHealthCheckURI() {
return this.healthCheckURI;
}
public void setHealthCheckURI(String healthCheckURI) {
this.healthCheckURI = healthCheckURI;
if(healthCheckURI != null){
putQueryParameter("HealthCheckURI", healthCheckURI);
}
}
public Integer getEstablishedTimeout() {
return this.establishedTimeout;
}
public void setEstablishedTimeout(Integer establishedTimeout) {
this.establishedTimeout = establishedTimeout;
if(establishedTimeout != null){
putQueryParameter("EstablishedTimeout", establishedTimeout.toString());
}
}
public Integer getPersistenceTimeout() {
return this.persistenceTimeout;
}
public void setPersistenceTimeout(Integer persistenceTimeout) {
this.persistenceTimeout = persistenceTimeout;
if(persistenceTimeout != null){
putQueryParameter("PersistenceTimeout", persistenceTimeout.toString());
}
}
public String getHealthCheckDomain() {
return this.healthCheckDomain;
}
public void setHealthCheckDomain(String healthCheckDomain) {
this.healthCheckDomain = healthCheckDomain;
if(healthCheckDomain != null){
putQueryParameter("HealthCheckDomain", healthCheckDomain);
}
}
public String getLoadBalancerId() {
return this.loadBalancerId;
}
public void setLoadBalancerId(String loadBalancerId) {
this.loadBalancerId = loadBalancerId;
if(loadBalancerId != null){
putQueryParameter("LoadBalancerId", loadBalancerId);
}
}
public Integer getHealthCheckInterval() {
return this.healthCheckInterval;
}
public void setHealthCheckInterval(Integer healthCheckInterval) {
this.healthCheckInterval = healthCheckInterval;
if(healthCheckInterval != null){
putQueryParameter("HealthCheckInterval", healthCheckInterval.toString());
}
}
public Integer getBackendServerPort() {
return this.backendServerPort;
}
public void setBackendServerPort(Integer backendServerPort) {
this.backendServerPort = backendServerPort;
if(backendServerPort != null){
putQueryParameter("BackendServerPort", backendServerPort.toString());
}
}
public Integer getHealthCheckConnectTimeout() {
return this.healthCheckConnectTimeout;
}
public void setHealthCheckConnectTimeout(Integer healthCheckConnectTimeout) {
this.healthCheckConnectTimeout = healthCheckConnectTimeout;
if(healthCheckConnectTimeout != null){
putQueryParameter("HealthCheckConnectTimeout", healthCheckConnectTimeout.toString());
}
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
if(description != null){
putQueryParameter("Description", description);
}
}
public Integer getUnhealthyThreshold() {
return this.unhealthyThreshold;
}
public void setUnhealthyThreshold(Integer unhealthyThreshold) {
this.unhealthyThreshold = unhealthyThreshold;
if(unhealthyThreshold != null){
putQueryParameter("UnhealthyThreshold", unhealthyThreshold.toString());
}
}
public Integer getHealthyThreshold() {
return this.healthyThreshold;
}
public void setHealthyThreshold(Integer healthyThreshold) {
this.healthyThreshold = healthyThreshold;
if(healthyThreshold != null){
putQueryParameter("HealthyThreshold", healthyThreshold.toString());
}
}
public String getScheduler() {
return this.scheduler;
}
public void setScheduler(String scheduler) {
this.scheduler = scheduler;
if(scheduler != null){
putQueryParameter("Scheduler", scheduler);
}
}
public String getEipTransmit() {
return this.eipTransmit;
}
public void setEipTransmit(String eipTransmit) {
this.eipTransmit = eipTransmit;
if(eipTransmit != null){
putQueryParameter("EipTransmit", eipTransmit);
}
}
public Integer getListenerPort() {
return this.listenerPort;
}
public void setListenerPort(Integer listenerPort) {
this.listenerPort = listenerPort;
if(listenerPort != null){
putQueryParameter("ListenerPort", listenerPort.toString());
}
}
public String getHealthCheckType() {
return this.healthCheckType;
}
public void setHealthCheckType(String healthCheckType) {
this.healthCheckType = healthCheckType;
if(healthCheckType != null){
putQueryParameter("HealthCheckType", healthCheckType);
}
}
public String getHealthCheckHttpCode() {
return this.healthCheckHttpCode;
}
public void setHealthCheckHttpCode(String healthCheckHttpCode) {
this.healthCheckHttpCode = healthCheckHttpCode;
if(healthCheckHttpCode != null){
putQueryParameter("HealthCheckHttpCode", healthCheckHttpCode);
}
}
public Integer getHealthCheckConnectPort() {
return this.healthCheckConnectPort;
}
public void setHealthCheckConnectPort(Integer healthCheckConnectPort) {
this.healthCheckConnectPort = healthCheckConnectPort;
if(healthCheckConnectPort != null){
putQueryParameter("HealthCheckConnectPort", healthCheckConnectPort.toString());
}
}
@Override
public Class<CreateLoadBalancerTCPListenerResponse> getResponseClass() {
return CreateLoadBalancerTCPListenerResponse.class;
}
}
|
package problem_3;
public class Knight extends Piece {
public Knight(Position pos1) {
this.pos1 = pos1;
}
public boolean isLegalMove(Position pos2) {
return Piece.isLegalMove(this.pos1, pos2) && Knight.isLegalMove(this.pos1, pos2);
}
public static boolean isLegalMove(Position pos1, Position pos2) {
if ((Math.abs(pos1.letter - pos2.letter) == 2 &&
Math.abs(pos1.num - pos2.num) == 1) ||
(Math.abs(pos1.letter - pos2.letter) == 1 &&
Math.abs(pos1.num - pos2.num) == 2)) {
return true;
} else {
return false;
}
}
}
|
package mongo.service;
import api.domain.Gateway;
import api.service.GatewayService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import mongo.dao.MongoGatewayRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
/**
* Created by mirceac on 6/1/16.
*/
@Component
public class MongoGatewayService implements GatewayService {
@Autowired
MongoGatewayRepository gatewayRepository;
@Autowired
DBCollection gatewayCollection;
@PostConstruct
public void init() {
gatewayCollection.createIndex(new BasicDBObject("serialNumber", 1), new BasicDBObject("unique", true));
}
@Override
public Gateway getGateway(String accountId, String serialNumber) {
return gatewayRepository.findByAccountIdAndSerialNumber(accountId, serialNumber);
}
@Override
public Gateway saveGateway(String accountId, Gateway gateway) {
gateway.setAccountId(accountId);
return gatewayRepository.save(gateway);
}
@Override
public List<? extends Gateway> getGateways(String accountId) {
return gatewayRepository.findByAccountId(accountId);
}
@Override
public List<? extends Gateway> getGateways(String accountId, String model) {
return gatewayRepository.findByAccountIdAndModel(accountId, model);
}
@Override
public Gateway getGatewayById(String accountId, String gatewayId) {
return gatewayRepository.findByAccountIdAndId(accountId, gatewayId);
}
@Override
public Long deleteGateway(String accountId, String serialNumber) {
return gatewayRepository.deleteByAccountIdAndSerialNumber(accountId, serialNumber);
}
@Override
public Long deleteGateways(String accountId, Collection<String> gatewayIds) {
return gatewayRepository.deleteByAccountIdAndIdIn(accountId, gatewayIds);
}
@Override
public Long deleteGateways(String accountId) {
return gatewayRepository.deleteByAccountId(accountId);
}
}
|
/*
* 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.usergrid.chop.client.ssh;
public enum CommandType {
SCP, SSH
}
|
/*
* Copyright 2016 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.robotframework.ide.eclipse.main.plugin.hyperlink;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.robotframework.red.junit.jupiter.ProjectExtension.getFile;
import java.util.function.Consumer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.text.Region;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.extension.ExtendWith;
import org.robotframework.red.junit.jupiter.Project;
import org.robotframework.red.junit.jupiter.ProjectExtension;
@ExtendWith(ProjectExtension.class)
public class FileHyperlinkTest {
@Project(files = { "file.txt" })
static IProject project;
@AfterAll
public static void afterSuite() {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeAllEditors(false);
}
@Test
public void testFileHyperlinkProperties() {
final FileHyperlink link = new FileHyperlink(new Region(20, 50), getFile(project, "file.txt"),
"Link label", null);
assertThat(link.getTypeLabel()).isNull();
assertThat(link.getHyperlinkRegion()).isEqualTo(new Region(20, 50));
assertThat(link.getHyperlinkText()).isEqualTo("Link label");
}
@Test
public void testIfFileOpensProperly() throws Exception {
final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
assertThat(page.getEditorReferences()).isEmpty();
@SuppressWarnings("unchecked")
final Consumer<IFile> operation = mock(Consumer.class);
final FileHyperlink link = new FileHyperlink(new Region(20, 50), getFile(project, "file.txt"), "Link label",
operation);
link.open();
assertThat(page.getEditorReferences()).hasSize(1);
final IFileEditorInput editorInput = (IFileEditorInput) page.getEditorReferences()[0].getEditorInput();
assertThat(editorInput.getFile()).isEqualTo(getFile(project, "file.txt"));
verify(operation).accept(eq(getFile(project, "file.txt")));
}
}
|
package com.emu.apps.shared.converters;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WaterMarkPdfTest {
@Test
void watermarkPdfTest() throws IOException {
File file = new File("Java-Interview-questions-VALIDATED-watermaked.pdf");
FileOutputStream fos = new FileOutputStream(file);
WaterMarkPdf.watermarkPdf(WaterMarkPdfTest.class.getResourceAsStream("/Java-Interview-questions-VALIDATED-2.pdf"),
fos);
}
}
|
/*
* Copyright 2015-2018 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.glowroot.agent.impl;
import org.junit.jupiter.api.Test;
import org.glowroot.agent.plugin.api.Message;
import org.glowroot.agent.plugin.api.MessageSupplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TraceEntryComponentTest {
@Test
public void testTooManyPops() {
// given
ThreadContextImpl threadContext = mock(ThreadContextImpl.class);
MessageSupplier messageSupplier = mock(MessageSupplier.class);
when(messageSupplier.get()).thenReturn(Message.create("abc"));
TimerImpl timer = mock(TimerImpl.class);
TraceEntryComponent traceEntryComponent =
new TraceEntryComponent(threadContext, messageSupplier, timer, 0);
// when
traceEntryComponent.popEntry(traceEntryComponent.getRootEntry(), 0);
traceEntryComponent.popEntry(traceEntryComponent.getRootEntry(), 0);
// then ok
}
@Test
public void testMissedPop() {
// given
ThreadContextImpl threadContext = mock(ThreadContextImpl.class);
MessageSupplier messageSupplier1 = mock(MessageSupplier.class);
MessageSupplier messageSupplier2 = mock(MessageSupplier.class);
when(messageSupplier1.get()).thenReturn(Message.create("abc"));
when(messageSupplier2.get()).thenReturn(Message.create("xyz"));
TimerImpl timer1 = mock(TimerImpl.class);
TimerImpl timer2 = mock(TimerImpl.class);
TraceEntryComponent traceEntryComponent =
new TraceEntryComponent(threadContext, messageSupplier1, timer1, 0);
// when
traceEntryComponent.pushEntry(0, messageSupplier2, timer2, null, null, 0);
traceEntryComponent.popEntry(traceEntryComponent.getRootEntry(), 0);
// then
assertThat(traceEntryComponent.isCompleted()).isTrue();
}
@Test
public void testPopNonExisting() {
// given
ThreadContextImpl threadContext = mock(ThreadContextImpl.class);
MessageSupplier messageSupplier1 = mock(MessageSupplier.class);
MessageSupplier messageSupplier2 = mock(MessageSupplier.class);
when(messageSupplier1.get()).thenReturn(Message.create("abc"));
when(messageSupplier2.get()).thenReturn(Message.create("xyz"));
TimerImpl timer1 = mock(TimerImpl.class);
TimerImpl timer2 = mock(TimerImpl.class);
TraceEntryComponent traceEntryComponent =
new TraceEntryComponent(threadContext, messageSupplier1, timer1, 0);
// when
traceEntryComponent.pushEntry(0, messageSupplier2, timer2, null, null, 0);
traceEntryComponent.popEntry(mock(TraceEntryImpl.class), 0);
// then
assertThat(traceEntryComponent.isCompleted()).isFalse();
}
}
|
package com.example.radibarq.pokemongotradecenter;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
package ic2.api.network;
/**
* Allows a tile entity to receive field sync updates received from the server.
*/
public interface INetworkUpdateListener {
/**
* Called when a field is synchronized.
*
* @param field field synchronized
*/
void onNetworkUpdate(String field);
}
|
package ut.org.ndrone.api.service;
import com.atlassian.bitbucket.repository.Repository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.ndrone.SecurityUtils;
import org.ndrone.api.TeamCity;
import org.ndrone.api.dao.TeamCityTriggerConfigDao;
import org.ndrone.api.dao.TeamCityTriggerConfiguration;
import org.ndrone.api.service.TeamCityService;
import org.ndrone.api.service.TeamCityServiceImpl;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* @author Nicholas Drone on 5/2/17.
*/
@RunWith(MockitoJUnitRunner.class)
public class TeamCityServiceTest
{
private TeamCityService service;
private TeamCityTriggerConfigDao dao;
@Before
public void setUp()
{
dao = Mockito.mock(TeamCityTriggerConfigDao.class);
Mockito.reset(dao);
service = new TeamCityServiceImpl(dao);
}
@Test
public void findNoPreviousObject()
{
Repository repository = Mockito.mock(Repository.class);
Mockito.when(repository.getId()).thenReturn(1);
setupNoConfigurations();
TeamCity teamCity = service.find(repository);
Assert.assertEquals("1", teamCity.getId());
Assert.assertNull(teamCity.getBuildConfigId());
Assert.assertNull(teamCity.getUsername());
Assert.assertNull(teamCity.getPassword());
Assert.assertNull(teamCity.getUrl());
Assert.assertNull(teamCity.getBuildConfigName());
}
@Test
public void find()
{
Repository repository = Mockito.mock(Repository.class);
Mockito.when(repository.getId()).thenReturn(1);
try
{
setupConfigurations();
}
catch (Exception e)
{
Assert.fail();
}
TeamCity teamCity = service.find(repository);
Assert.assertEquals("1", teamCity.getId());
Assert.assertEquals("1", teamCity.getBuildConfigId());
Assert.assertEquals("test", teamCity.getUsername());
Assert.assertNotNull(teamCity.getPassword());
Assert.assertEquals("test", teamCity.getUrl());
Assert.assertEquals("test", teamCity.getBuildConfigName());
}
@Test
public void deleteObjectNonExistent()
{
setupNoConfigurations();
service.delete(new TeamCity.Builder().withId("1").build());
Mockito.verify(dao, Mockito.never())
.delete(Mockito.any(TeamCityTriggerConfiguration.class));
}
@Test
public void delete()
{
try
{
setupConfigurations();
}
catch (Exception e)
{
Assert.fail();
}
service.delete(new TeamCity.Builder().withId("1").build());
Mockito.verify(dao, Mockito.times(1))
.delete(Mockito.any(TeamCityTriggerConfiguration.class));
}
@Test
public void saveNewObject()
throws BadPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException
{
setupNoConfigurations();
service.save(new TeamCity.Builder().withId("1").withUsername("test").withPassword("test")
.withUrl("test").withBuildConfigId("1").withBuildConfigName("test").build());
Mockito.verify(dao, Mockito.times(1)).save(Mockito.eq(1), Mockito.eq("test"),
Mockito.anyString(), Mockito.anyString(), Mockito.eq("test"), Mockito.eq("1"),
Mockito.eq("test"));
Mockito.verify(dao, Mockito.never())
.update(Mockito.any(TeamCityTriggerConfiguration.class));
}
@Test
public void updateSameObject()
throws BadPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException
{
Repository repository = Mockito.mock(Repository.class);
Mockito.when(repository.getId()).thenReturn(1);
setupConfigurations();
service.save(service.find(repository));
Mockito.verify(dao, Mockito.never()).save(Mockito.anyInt(), Mockito.anyString(),
Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
Mockito.anyString());
Mockito.verify(dao, Mockito.never())
.update(Mockito.any(TeamCityTriggerConfiguration.class));
}
@Test
public void update()
throws BadPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException
{
setupConfigurations();
service.save(new TeamCity.Builder().withId("1").withUsername("test").withPassword("test")
.withUrl("test").withBuildConfigId("2").withBuildConfigName("test").build());
Mockito.verify(dao, Mockito.never()).save(Mockito.anyInt(), Mockito.anyString(),
Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
Mockito.anyString());
Mockito.verify(dao, Mockito.times(1))
.update(Mockito.any(TeamCityTriggerConfiguration.class));
}
@Test
public void comparePasswordNoDatabase()
throws InvalidKeyException, BadPaddingException, NoSuchAlgorithmException,
IllegalBlockSizeException, NoSuchPaddingException
{
setupNoConfigurations();
Assert.assertEquals("test", service
.comparePassword(new TeamCity.Builder().withId("1").withPassword("test").build()));
}
@Test
public void comparePasswordChanged()
{
try
{
setupConfigurations();
TeamCity teamCity = new TeamCity.Builder().withId("1").withUsername("test")
.withPassword("changed").withUrl("test").withBuildConfigId("test")
.withBuildConfigName("test").build();
Assert.assertEquals("changed", service.comparePassword(teamCity));
}
catch (Exception e)
{
Assert.fail();
}
}
private void setupNoConfigurations()
{
Mockito.when(dao.find(Mockito.anyInt())).thenReturn(new TeamCityTriggerConfiguration[]{});
}
private void setupConfigurations()
throws BadPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException
{
TeamCityTriggerConfiguration teamCityTriggerConfiguration = mocked();
Mockito.when(dao.find(Mockito.eq(1))).thenReturn(new TeamCityTriggerConfiguration[]{
teamCityTriggerConfiguration});
}
private TeamCityTriggerConfiguration mocked()
throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException,
BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException
{
TeamCityTriggerConfiguration configuration = Mockito
.mock(TeamCityTriggerConfiguration.class);
Mockito.when(configuration.getReposId()).thenReturn(1);
Mockito.when(configuration.getUsername()).thenReturn("test");
Mockito.when(configuration.getSecret())
.thenReturn(SecurityUtils.encrypt(SecurityUtils.generateSalt(), "test"));
Mockito.when(configuration.getUrl()).thenReturn("test");
Mockito.when(configuration.getBuildConfigId()).thenReturn("1");
Mockito.when(configuration.getBuildConfigName()).thenReturn("test");
return configuration;
}
}
|
package com.covens.common.integration.patchouli.processors;
import java.util.Objects;
import com.covens.api.ritual.EnumGlyphType;
import com.covens.common.content.ritual.AdapterIRitual;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ResourceLocation;
import vazkii.patchouli.api.IComponentProcessor;
import vazkii.patchouli.api.IVariableProvider;
import vazkii.patchouli.api.PatchouliAPI;
public class RitualProcessor implements IComponentProcessor {
private AdapterIRitual ritual;
@Override
public void setup(IVariableProvider<String> json) {
this.ritual = AdapterIRitual.REGISTRY.getValue(new ResourceLocation(json.get("ritual")));
Objects.requireNonNull(this.ritual);
}
@Override
public String process(String val) {
try {
if (val.startsWith("circle")) {
return this.getCircle(val.substring(6));
}
if (val.startsWith("input")) {
return this.getInput(val.substring(5));
}
if (val.startsWith("output")) {
return this.getOutput(val.substring(6));
}
if ("tick_cost".equals(val)) {
return ""+ritual.getRunningPower();
}
if ("start_cost".equals(val)) {
return ""+ritual.getRequiredStartingPower();
}
if ("ritualname".equals(val)) {
return I18n.format("ritual." + this.ritual.getRegistryName().toString().replace(':', '.') + ".short.name");
}
if ("ritual".equals(val)) {
return this.ritual.getRegistryName().toString();
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
throw new RuntimeException("Unrecognized ritual value: " + val);
}
private String getOutput(String substring) {
try {
int index = Integer.parseInt(substring) - 1;
return PatchouliAPI.instance.serializeItemStack(this.ritual.getOutputRaw().get(index));
} catch (Exception e) {
return "minecraft:air";
}
}
private String getInput(String substring) {
try {
int index = Integer.parseInt(substring) - 1;
return PatchouliAPI.instance.serializeItemStack(this.ritual.getInput().get(index).getCachedStacks().get(0));
} catch (Exception e) {
return "minecraft:air";
}
}
private String getCircle(String substring) {
int index = Integer.parseInt(substring);
if ((this.ritual.getCircles() & 3) < (index - 1)) {
return "covens:textures/gui/books/ritual/circle_center.png";
}
return "covens:textures/gui/books/ritual/circle_" + EnumGlyphType.fromMeta((this.ritual.getCircles() >> (2 * index)) & 3).name().toLowerCase() + "_" + index + ".png";
}
}
|
package name.remal.gradleplugins.toolkit.issues;
import static name.remal.gradleplugins.toolkit.HtmlToTextUtils.convertHtmlToText;
import org.intellij.lang.annotations.Language;
public class HtmlMessage extends Message {
public static HtmlMessage htmlMessageOf(@Language("HTML") String html) {
return new HtmlMessage(html);
}
private HtmlMessage(String value) {
super(value);
}
@Override
public String renderAsText() {
return convertHtmlToText(this.value);
}
}
|
/*
* Copyright (C) 2013 salesforce.com, 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.auraframework.http.resource;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpHeaders;
import org.auraframework.annotations.Annotations.ServiceComponent;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.SVGDef;
import org.auraframework.http.AuraServlet;
import org.auraframework.http.RequestParam.StringParam;
import org.auraframework.system.AuraContext;
import org.auraframework.system.AuraContext.Format;
import org.auraframework.throwable.quickfix.QuickFixException;
@ServiceComponent
public class ResourceSvg extends AuraResourceImpl {
private static final StringParam lookup = new StringParam(AuraServlet.AURA_PREFIX + "lookup", 0, false);
public ResourceSvg() {
super("resources.svg", Format.SVG);
}
@Override
public void write(HttpServletRequest request, HttpServletResponse response, AuraContext context) throws IOException {
try {
//For Security and caching we require the host to validate the cache. Thus we need to overwrite
//the original caching
response.setHeader(HttpHeaders.CACHE_CONTROL, "private,must-revalidate,max-age=0");
String fqn = lookup.get(request);
if (fqn == null || fqn.isEmpty()) {
fqn = context.getApplicationDescriptor().getQualifiedName();
}
DefDescriptor<SVGDef> svg = definitionService.getDefDescriptor(fqn, SVGDef.class);
SVGDef def = definitionService.getDefinition(svg);
//Get the original etag if exists
String etag = request.getHeader(HttpHeaders.IF_NONE_MATCH);
//generate the new etag from the definitions hash
//note per rfc7232 etags are a opaque quoted string
String hash = "\"" + def.getOwnHash() + "\"";
//For security reasons, if the user fetches the svg from the browser directly we
//force the browser to download the file
if (request.getHeader(HttpHeaders.REFERER) == null) {
response.setContentType(null);
response.setHeader("Content-Disposition", "attachment; filename=resources.svg");
//Otherwise check the etag, if it matches that reply with a 304, unchanged
} else if (etag != null && etag.equals(hash)) {
response.setStatus(304);
return;
}
//finally add the etag to the header and write the image
response.setHeader(HttpHeaders.ETAG, hash);
serverService.writeAppSvg(svg, response.getWriter());
} catch (QuickFixException qfe) {
servletUtilAdapter.handleServletException(qfe, true, context, request, response, false);
}
}
}
|
package com.king.tv.mvp.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.king.base.util.LogUtils;
import com.king.base.util.ToastUtils;
import com.king.tv.R;
import com.king.tv.bean.Room;
import com.king.tv.mvp.base.BaseFragment;
import com.king.tv.mvp.presenter.RoomPresenter;
import com.king.tv.mvp.view.IRoomView;
import com.king.view.flutteringlayout.FlutteringLayout;
import butterknife.BindView;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.BlurTransformation;
/**
* @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
* @since 2017/5/2
*/
public class FullRoomFragment extends BaseFragment<IRoomView, RoomPresenter> implements IRoomView {
@BindView(R.id.rlAnchorInfo)
View rlAnchorInfo;
@BindView(R.id.civAvatar)
ImageView civAvatar;
@BindView(R.id.tvName)
TextView tvName;
@BindView(R.id.tvFans)
TextView tvFans;
@BindView(R.id.ivCover)
ImageView ivCover;
@BindView(R.id.frameVideo)
FrameLayout frameVideo;
@BindView(R.id.ivBack)
ImageView ivBack;
@BindView(R.id.tvAccount)
TextView tvAccount;
@BindView(R.id.ivInput)
ImageView ivInput;
@BindView(R.id.ivFollow)
ImageView ivFollow;
@BindView(R.id.ivGift)
ImageView ivGift;
@BindView(R.id.ivShare)
ImageView ivShare;
@BindView(R.id.ivMessage)
ImageView ivMessage;
@BindView(R.id.rlRoomInfo)
LinearLayout rlRoomInfo;
@BindView(R.id.videoContent)
RelativeLayout videoContent;
@BindView(R.id.flutteringLayout)
FlutteringLayout flutteringLayout;
@BindView(R.id.btnHeart)
Button btnHeart;
private String uid;
private String coverUrl;
private VideoFragment videoFragment;
public static FullRoomFragment newInstance(String uid,String coverUrl) {
Bundle args = new Bundle();
FullRoomFragment fragment = new FullRoomFragment();
fragment.uid = uid;
fragment.coverUrl = coverUrl;
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public int getRootViewId() {
return R.layout.fragment_full_room;
}
@Override
public void initUI() {
tvAccount.setText(String.format(getString(R.string.qm_account),uid));
Glide.with(this).load(coverUrl).centerCrop().bitmapTransform(new BlurTransformation(context,18,3)).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivCover);
}
@Override
public void initData() {
getPresenter().enterRoom(uid,true);
}
@Override
public RoomPresenter createPresenter() {
return new RoomPresenter(getApp());
}
@Override
public void showProgress() {
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void enterRoom(Room room) {
LogUtils.d("enterRoom:" + room.getUid());
updateAnchorInfo(room);
}
@Override
public void playUrl(String url) {
LogUtils.d("playUrl:" + url);
if (videoFragment == null) {
videoFragment = VideoFragment.newInstance(url,true);
}
replaceChildFragment(R.id.frameVideo, videoFragment);
clickHeart();
}
private void updateAnchorInfo(Room room){
if(room!=null){
rlAnchorInfo.setVisibility(View.VISIBLE);
Glide.with(this).load(room.getAvatar()).placeholder(R.drawable.mine_default_avatar).error(R.drawable.mine_default_avatar).centerCrop().crossFade().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(civAvatar);
tvName.setText(room.getNick());
tvFans.setText(String.format(getString(R.string.fans_num),room.getFollow()));
}
}
private void clickInput(){
}
private void clickFollow(){
startLogin();
}
private void clickGift(){
}
private void clickShare(){
}
private void clickMessage(){
startLogin();
}
private void clickHeart(){
flutteringLayout.addHeart();
}
@OnClick({R.id.ivBack, R.id.ivInput, R.id.ivFollow, R.id.ivGift, R.id.ivShare, R.id.ivMessage,R.id.btnHeart})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.ivBack:
finish();
break;
case R.id.ivInput:
clickInput();
break;
case R.id.ivFollow:
clickFollow();
break;
case R.id.ivGift:
clickGift();
break;
case R.id.ivShare:
clickShare();
break;
case R.id.ivMessage:
clickMessage();
break;
case R.id.btnHeart:
clickHeart();
break;
}
}
}
|
/*
* 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.workspaces.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.workspaces.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* WorkspaceBundleMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class WorkspaceBundleMarshaller {
private static final MarshallingInfo<String> BUNDLEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("BundleId").build();
private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Name").build();
private static final MarshallingInfo<String> OWNER_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Owner").build();
private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build();
private static final MarshallingInfo<String> IMAGEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("ImageId").build();
private static final MarshallingInfo<StructuredPojo> ROOTSTORAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RootStorage").build();
private static final MarshallingInfo<StructuredPojo> USERSTORAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UserStorage").build();
private static final MarshallingInfo<StructuredPojo> COMPUTETYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ComputeType").build();
private static final MarshallingInfo<java.util.Date> LASTUPDATEDTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LastUpdatedTime").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<java.util.Date> CREATIONTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CreationTime").timestampFormat("unixTimestamp").build();
private static final WorkspaceBundleMarshaller instance = new WorkspaceBundleMarshaller();
public static WorkspaceBundleMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(WorkspaceBundle workspaceBundle, ProtocolMarshaller protocolMarshaller) {
if (workspaceBundle == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(workspaceBundle.getBundleId(), BUNDLEID_BINDING);
protocolMarshaller.marshall(workspaceBundle.getName(), NAME_BINDING);
protocolMarshaller.marshall(workspaceBundle.getOwner(), OWNER_BINDING);
protocolMarshaller.marshall(workspaceBundle.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(workspaceBundle.getImageId(), IMAGEID_BINDING);
protocolMarshaller.marshall(workspaceBundle.getRootStorage(), ROOTSTORAGE_BINDING);
protocolMarshaller.marshall(workspaceBundle.getUserStorage(), USERSTORAGE_BINDING);
protocolMarshaller.marshall(workspaceBundle.getComputeType(), COMPUTETYPE_BINDING);
protocolMarshaller.marshall(workspaceBundle.getLastUpdatedTime(), LASTUPDATEDTIME_BINDING);
protocolMarshaller.marshall(workspaceBundle.getCreationTime(), CREATIONTIME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
/*
* Copyright 2019 ThoughtWorks, 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.thoughtworks.go.config.materials.mercurial;
import com.thoughtworks.go.config.materials.ScmMaterial;
import com.thoughtworks.go.config.materials.ScmMaterialConfig;
import com.thoughtworks.go.config.materials.SubprocessExecutionContext;
import com.thoughtworks.go.config.migration.UrlDenormalizerXSLTMigration121;
import com.thoughtworks.go.domain.MaterialInstance;
import com.thoughtworks.go.domain.materials.*;
import com.thoughtworks.go.domain.materials.mercurial.HgCommand;
import com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance;
import com.thoughtworks.go.domain.materials.mercurial.HgVersion;
import com.thoughtworks.go.domain.materials.svn.MaterialUrl;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.GoConstants;
import com.thoughtworks.go.util.command.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.thoughtworks.go.util.ExceptionUtils.bomb;
import static com.thoughtworks.go.util.ExceptionUtils.bombIfFailedToRunCommandLine;
import static com.thoughtworks.go.util.FileUtil.createParentFolderIfNotExist;
import static java.lang.String.format;
/**
* @understands configuration for mercurial version control
*/
public class HgMaterial extends ScmMaterial {
private static final Pattern HG_VERSION_PATTERN = Pattern.compile(".*\\(.*\\s+(\\d(\\.\\d)+.*)\\)");
private static final Logger LOGGER = LoggerFactory.getLogger(HgMaterial.class);
private HgUrlArgument url;
//TODO: use iBatis to set the type for us, and we can get rid of this field.
public static final String TYPE = "HgMaterial";
private static final String ERROR_OLD_VERSION = "Please install Mercurial Version 1.0 or above."
+ " The current installed hg is ";
private static final String ERR_NO_HG_INSTALLED =
"Failed to find 'hg' on your PATH. Please ensure 'hg' is executable by the Go Server and on the Go Agents where this material will be used.";
private final String HG_DEFAULT_BRANCH = "default";
private HgMaterial() {
super(TYPE, new GoCipher());
}
public HgMaterial(String url, String folder) {
this();
this.url = new HgUrlArgument(url);
this.folder = folder;
}
public HgMaterial(HgMaterialConfig config) {
this(UrlDenormalizerXSLTMigration121.urlWithCredentials(config.getUrl(), config.getUserName(), config.getPassword()), config.getFolder());
this.userName = config.getUserName();
this.autoUpdate = config.getAutoUpdate();
this.filter = config.rawFilter();
this.invertFilter = config.getInvertFilter();
this.name = config.getName();
}
@Override
public MaterialConfig config() {
return new HgMaterialConfig(url, autoUpdate, filter, invertFilter, folder, name);
}
public List<Modification> latestModification(File baseDir, final SubprocessExecutionContext execCtx) {
HgCommand hgCommand = getHg(baseDir);
return hgCommand.latestOneModificationAsModifications();
}
public List<Modification> modificationsSince(File baseDir, Revision revision, final SubprocessExecutionContext execCtx) {
return getHg(baseDir).modificationsSince(revision);
}
public MaterialInstance createMaterialInstance() {
return new HgMaterialInstance(url.originalArgument(), UUID.randomUUID().toString());
}
@Override
protected void appendCriteria(Map<String, Object> parameters) {
parameters.put(ScmMaterialConfig.URL, url.originalArgument());
}
@Override
protected void appendAttributes(Map<String, Object> parameters) {
parameters.put("url", url);
}
private HgCommand getHg(File baseDir) {
InMemoryStreamConsumer output =
ProcessOutputStreamConsumer.inMemoryConsumer();
HgCommand hgCommand = null;
try {
hgCommand = hg(baseDir, output);
} catch (Exception e) {
bomb(e.getMessage() + " " + output.getStdError(), e);
}
return hgCommand;
}
public void updateTo(ConsoleOutputStreamConsumer outputStreamConsumer, File baseDir, RevisionContext revisionContext, final SubprocessExecutionContext execCtx) {
Revision revision = revisionContext.getLatestRevision();
try {
outputStreamConsumer.stdOutput(format("[%s] Start updating %s at revision %s from %s", GoConstants.PRODUCT_NAME, updatingTarget(), revision.getRevision(), url.forDisplay()));
File workingDir = execCtx.isServer() ? baseDir : workingdir(baseDir);
hg(workingDir, outputStreamConsumer).updateTo(revision, outputStreamConsumer);
outputStreamConsumer.stdOutput(format("[%s] Done.\n", GoConstants.PRODUCT_NAME));
} catch (Exception e) {
bomb(e);
}
}
public void add(File baseDir, ProcessOutputStreamConsumer outputStreamConsumer, File file) throws Exception {
hg(baseDir, outputStreamConsumer).add(outputStreamConsumer, file);
}
public void commit(File baseDir, ProcessOutputStreamConsumer consumer, String comment, String username)
throws Exception {
hg(baseDir, consumer).commit(consumer, comment, username);
}
public void push(File baseDir, ProcessOutputStreamConsumer consumer) throws Exception {
hg(baseDir, consumer).push(consumer);
}
boolean isVersionOneDotZeroOrHigher(String hgout) {
String hgVersion = parseHgVersion(hgout);
Float aFloat = NumberUtils.createFloat(hgVersion.subSequence(0, 3).toString());
return aFloat >= 1;
}
private String parseHgVersion(String hgOut) {
String[] lines = hgOut.split("\n");
String firstLine = lines[0];
Matcher m = HG_VERSION_PATTERN.matcher(firstLine);
if (m.matches()) {
return m.group(1);
} else {
throw bomb("can not parse hgout : " + hgOut);
}
}
public ValidationBean checkConnection(final SubprocessExecutionContext execCtx) {
HgCommand hgCommand = new HgCommand(null, null, null, null, secrets());
try {
hgCommand.checkConnection(url);
return ValidationBean.valid();
} catch (Exception e) {
try {
return handleException(e, hgCommand.version());
} catch (Exception ex) {
return ValidationBean.notValid(ERR_NO_HG_INSTALLED);
}
}
}
ValidationBean handleException(Exception e, HgVersion version) {
ValidationBean defaultResponse = ValidationBean.notValid(
"Repository " + url.forDisplay() + " not found!" + " : \n" + e.getMessage());
try {
if (version.isOlderThanOneDotZero()) {
return ValidationBean.notValid(ERROR_OLD_VERSION + version.toString());
} else {
return defaultResponse;
}
} catch (Exception e1) {
LOGGER.debug("Problem validating HG", e);
return defaultResponse;
}
}
private HgCommand hg(File workingFolder, ConsoleOutputStreamConsumer outputStreamConsumer) throws Exception {
HgCommand hgCommand = new HgCommand(getFingerprint(), workingFolder, getBranch(), getUrl(), secrets());
if (!isHgRepository(workingFolder) || isRepositoryChanged(hgCommand)) {
LOGGER.debug("Invalid hg working copy or repository changed. Delete folder: {}", workingFolder);
FileUtils.deleteQuietly(workingFolder);
}
if (!workingFolder.exists()) {
createParentFolderIfNotExist(workingFolder);
int returnValue = hgCommand.clone(outputStreamConsumer, url);
bombIfFailedToRunCommandLine(returnValue, "Failed to run hg clone command");
}
return hgCommand;
}
private List<SecretString> secrets() {
SecretString secretSubstitution = line -> line.replace(url.forCommandLine(), url.forDisplay());
return Collections.singletonList(secretSubstitution);
}
private boolean isHgRepository(File workingFolder) {
return new File(workingFolder, ".hg").isDirectory();
}
private boolean isRepositoryChanged(HgCommand hgCommand) {
ConsoleResult result = hgCommand.workingRepositoryUrl();
return !MaterialUrl.sameUrl(url.defaultRemoteUrl(), new HgUrlArgument(result.outputAsString()).defaultRemoteUrl());
}
public boolean isCheckExternals() {
return false;
}
@Override
public String getUrl() {
return url.originalArgument();
}
@Override
public String urlForCommandLine() {
return url.forCommandLine();
}
public UrlArgument getUrlArgument() {
return url;
}
public HgUrlArgument getHgUrlArgument() {
return url;
}
public String getLongDescription() {
return String.format("URL: %s", url.forDisplay());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
HgMaterial that = (HgMaterial) o;
if (url != null ? !url.equals(that.url) : that.url != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (url != null ? url.hashCode() : 0);
return result;
}
protected String getLocation() {
return getUrlArgument().forDisplay();
}
public String getTypeForDisplay() {
return "Mercurial";
}
@Override
public String getShortRevision(String revision) {
if (revision == null) return null;
if (revision.length() < 12) return revision;
return revision.substring(0, 12);
}
@Override
public Map<String, Object> getAttributes(boolean addSecureFields) {
Map<String, Object> materialMap = new HashMap<>();
materialMap.put("type", "mercurial");
Map<String, Object> configurationMap = new HashMap<>();
if (addSecureFields) {
configurationMap.put("url", url.forCommandLine());
} else {
configurationMap.put("url", url.forDisplay());
}
materialMap.put("mercurial-configuration", configurationMap);
return materialMap;
}
public Class getInstanceType() {
return HgMaterialInstance.class;
}
@Override
public String toString() {
return "HgMaterial{" +
"url=" + url +
'}';
}
public String getBranch() {
return getBranchFromUrl(url.originalArgument());
}
private String getBranchFromUrl(String url) {
String[] componentsOfUrl = StringUtils.split(url, HgUrlArgument.DOUBLE_HASH);
if (componentsOfUrl.length > 1) {
return componentsOfUrl[1];
}
return HG_DEFAULT_BRANCH;
}
}
|
package org.wapache.security.oauth2.server.demo.service;
import org.wapache.security.oauth2.server.demo.entity.User;
import java.util.List;
public interface UserService {
/**
* 创建用户
*
* @param user
*/
User createUser(User user);
User updateUser(User user);
void deleteUser(Long userId);
/**
* 修改密码
*
* @param userId
* @param newPassword
*/
void changePassword(Long userId, String newPassword);
User findOne(Long userId);
List<User> findAll();
/**
* 根据用户名查找用户
*
* @param username
* @return
*/
User findByUsername(String username);
}
|
package net.logicsquad.recurring;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import org.junit.Test;
public class UnionTest {
RangeEveryYear range = RangeEveryYear.of(Month.JUNE, Month.SEPTEMBER);
DayInMonth day = DayInMonth.of(DayOfWeek.SUNDAY, 1);
Union union = Union.of(range, day);
@Test
public void unionIncludesAnyDayInRange() {
assertTrue(union.includes(LocalDate.of(2018, 6, 1)));
assertTrue(union.includes(LocalDate.of(2018, 6, 30)));
assertTrue(union.includes(LocalDate.of(2018, 9, 1)));
assertTrue(union.includes(LocalDate.of(2018, 9, 30)));
return;
}
@Test
public void unionIncludesAnyDayInMonthMatch() {
assertTrue(union.includes(LocalDate.of(2019, 1, 6)));
assertTrue(union.includes(LocalDate.of(2019, 2, 3)));
assertTrue(union.includes(LocalDate.of(2019, 4, 7)));
assertTrue(union.includes(LocalDate.of(2020, 1, 5)));
return;
}
@Test
public void unionIncludesDayInMonthAndRangeMatch() {
assertTrue(union.includes(LocalDate.of(2018, 6, 3)));
assertTrue(union.includes(LocalDate.of(2018, 7, 1)));
assertTrue(union.includes(LocalDate.of(2018, 8, 5)));
assertTrue(union.includes(LocalDate.of(2018, 9, 2)));
return;
}
@Test
public void unionExcludesOtherDates() {
assertFalse(union.includes(LocalDate.of(2018, 4, 18)));
assertFalse(union.includes(LocalDate.of(2019, 2, 6)));
assertFalse(union.includes(LocalDate.of(2020, 4, 7)));
assertFalse(union.includes(LocalDate.of(2021, 5, 11)));
return;
}
@Test(expected=NullPointerException.class)
public void ofThrowsOnNullList() {
Union.of((List<TemporalExpression>) null);
}
@Test(expected=NullPointerException.class)
public void ofThrowsOnNullExpression() {
Union.of((TemporalExpression) null);
}
@Test(expected=NullPointerException.class)
public void ofThrowsOnNullExpressionArray() {
Union.of((TemporalExpression[]) null);
}
}
|
package excel;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
public class ExcelTest {
@Test
public void insertData() {
String filePath = "C:\\Users\\Administrator\\Desktop\\福建省医疗服务价格数据库编码1.xlsx";
try {
InputStream input = new FileInputStream(filePath);
XSSFWorkbook hw = new XSSFWorkbook(input);
XSSFSheet sheet = hw.getSheetAt(0);
int rownum = sheet.getPhysicalNumberOfRows();
for (int i = 1; i < rownum; i++) {
Row row = sheet.getRow(i);
if (row != null) {
if(row.getCell(0) == null) {
continue;
}
row.getCell(0).setCellType(CellType.STRING);//项目编码
row.getCell(1).setCellType(CellType.STRING);//项目名称
row.getCell(2).setCellType(CellType.STRING);//项目内涵
row.getCell(3).setCellType(CellType.STRING);//除外内容
row.getCell(4).setCellType(CellType.STRING);//计价单位
row.getCell(5).setCellType(CellType.STRING);//医院等级
row.getCell(6).setCellType(CellType.STRING);//医院地区级别
row.getCell(7).setCellType(CellType.STRING);//说明
row.getCell(8).setCellType(CellType.STRING);//类型;1:一般医疗服务;2:医技诊疗类;3:临床诊疗类;4:中医类;5:过渡期项目
//System.out.println(row.getCell(0).getStringCellValue() + ";" + row.getCell(1).getStringCellValue());
//System.out.println(row.getCell(2) != null ? row.getCell(2).getStringCellValue() : "");
//System.out.println(row.getCell(3) != null ? row.getCell(3).getStringCellValue() : "");
//System.out.println(row.getCell(4) != null ? row.getCell(4).getStringCellValue() : "");
//System.out.println(row.getCell(5) != null ? row.getCell(5).getStringCellValue() : "");
//System.out.println(row.getCell(6) != null ? row.getCell(6).getStringCellValue() : "");
//System.out.println(row.getCell(7) != null ? row.getCell(7).getStringCellValue() : "");
//System.out.println(row.getCell(8) != null ? row.getCell(8).getStringCellValue() : "");
String PROJECTCODE = row.getCell(0).getStringCellValue();
String NAME = row.getCell(1).getStringCellValue();
String CONNOTATION = row.getCell(2) != null ? row.getCell(2).getStringCellValue() : "";
String EXCLUDEDONTENT = row.getCell(3) != null ? row.getCell(3).getStringCellValue() : "";
String VALUATIONNUNIT = row.getCell(4) != null ? row.getCell(4).getStringCellValue() : "";
String THREE = row.getCell(5) != null ? row.getCell(5).getStringCellValue() : "";
String BELOWTHREE = row.getCell(6) != null ? row.getCell(6).getStringCellValue() : "";
String INSTRUCTION = row.getCell(7) != null ? row.getCell(7).getStringCellValue() : "";
String T = row.getCell(8) != null ? row.getCell(8).getStringCellValue() : "";
int type = -1;
if(T.contains("一般医疗服务")) {
type = 1;
}else if(T.contains("医技诊疗类")) {
type = 2;
}else if(T.contains("临床诊疗类")) {
type = 3;
}else if(T.contains("中医类")) {
type = 4;
}else if(T.contains("过渡期项目")) {
type = 5;
}
String sql = "insert into medicaserviceprice (" +
" ID, CODE, PROJECTCODE, NAME, CONNOTATION, " +
" EXCLUDEDONTENT, VALUATIONNUNIT, THREE, BELOWTHREE,INSTRUCTION," +
" TYPE)" +
" value(" + i + " , 'bf0d75ebdf434a73be8bff8ca05dc24f', '" + PROJECTCODE + "', '" + NAME + "', '" + CONNOTATION + "'," +
"'" + EXCLUDEDONTENT + "','" + VALUATIONNUNIT + "', '" + THREE + "','" + BELOWTHREE + "','" + INSTRUCTION + "'," +
type + ")";
System.out.println(sql);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void createExcel() {
try {
String filePath = "D:\\2.xlsx";
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("报表");
XSSFCellStyle style = wb.createCellStyle();
// 设置style---cell中水平的对齐方式
style.setAlignment(HorizontalAlignment.CENTER);
// 设置style---cell中垂直方向的对齐方式
style.setVerticalAlignment(VerticalAlignment.CENTER);
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue("test1");
cell.setCellStyle(style);
FileOutputStream outputStream = new FileOutputStream(filePath);
wb.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void work() {
try {
InputStream input = new FileInputStream("D:\\20191219.xlsx");
XSSFWorkbook hw = new XSSFWorkbook(input);
XSSFSheet sheet = hw.getSheetAt(0);
int rownum = sheet.getPhysicalNumberOfRows();
XSSFWorkbook newEcel = new XSSFWorkbook();
XSSFSheet newSheet = newEcel.createSheet("名单");
XSSFRow newRow0 = newSheet.createRow(0);
newRow0.createCell(0).setCellValue("医院");
newRow0.createCell(1).setCellValue("科室");
newRow0.createCell(2).setCellValue("医生");
newRow0.createCell(3).setCellValue("职称");
newRow0.createCell(4).setCellValue("职务");
newRow0.createCell(5).setCellValue("电话号码");
newRow0.createCell(6).setCellValue("执业证书编号");
for (int i = 1; i < rownum; i++) {
Row row = sheet.getRow(i);
String hostipal = row.getCell(2).getStringCellValue().trim();
String name = row.getCell(3).getStringCellValue().trim();
String ZC = row.getCell(7).getStringCellValue().trim();
String ZW = row.getCell(8).getStringCellValue().trim();
row.getCell(9).setCellType(CellType.STRING);
String phone = row.getCell(9).getStringCellValue().trim();
System.out.println(hostipal + "," + name + "," + ZC + "," + ZW + "," + phone);
XSSFRow newRow = newSheet.createRow(i);
newRow.createCell(0).setCellValue(hostipal);
newRow.createCell(1).setCellValue("神经外科");
newRow.createCell(2).setCellValue(name);
newRow.createCell(3).setCellValue(ZC);
newRow.createCell(4).setCellValue(ZW);
newRow.createCell(5).setCellValue(phone);
newRow.createCell(6).setCellValue("执业证书编号");
}
FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\add.xlsx"));
newEcel.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.