text
stringlengths 7
1.01M
|
|---|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.17 at 07:02:27 오후 KST
//
package com.athena.chameleon.engine.entity.xml.application.jeus.v6_0;
import javax.xml.bind.annotation.XmlEnum;
/**
* <p>Java class for loggingLevelType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="loggingLevelType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="FATAL"/>
* <enumeration value="NOTICE"/>
* <enumeration value="INFORMATION"/>
* <enumeration value="DEBUG"/>
* <enumeration value="OFF"/>
* <enumeration value="SEVERE"/>
* <enumeration value="WARNING"/>
* <enumeration value="INFO"/>
* <enumeration value="CONFIG"/>
* <enumeration value="FINE"/>
* <enumeration value="FINER"/>
* <enumeration value="FINEST"/>
* <enumeration value="ALL"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlEnum
public enum LoggingLevelType {
ALL,
CONFIG,
DEBUG,
FATAL,
FINE,
FINER,
FINEST,
INFO,
INFORMATION,
NOTICE,
OFF,
SEVERE,
WARNING;
public String value() {
return name();
}
public static LoggingLevelType fromValue(String v) {
return valueOf(v);
}
}
|
package com.xy.maill.maillproduct.service.impl;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
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.xy.maill.common.utils.PageUtils;
import com.xy.maill.common.utils.Query;
import com.xy.maill.maillproduct.dao.ProductAttrValueDao;
import com.xy.maill.maillproduct.entity.ProductAttrValueEntity;
import com.xy.maill.maillproduct.service.ProductAttrValueService;
import org.springframework.transaction.annotation.Transactional;
@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<ProductAttrValueEntity> page = this.page(
new Query<ProductAttrValueEntity>().getPage(params),
new QueryWrapper<ProductAttrValueEntity>()
);
return new PageUtils(page);
}
@Override
public void saveProductAttr(List<ProductAttrValueEntity> collect) {
this.saveBatch(collect);
}
@Transactional
@Override
public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> entities) {
//1、删除这个spuId之前对应的所有属性
this.baseMapper.delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));
List<ProductAttrValueEntity> collect = entities.stream().map(item -> {
item.setSpuId(spuId);
return item;
}).collect(Collectors.toList());
this.saveBatch(collect);
}
@Override
public List<ProductAttrValueEntity> baseAttrlistforspu(Long spuId) {
List<ProductAttrValueEntity> entities = this.baseMapper.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
return entities;
}
}
|
/*
* Copyright (c) 2012 The Broad Institute
*
* 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 htsjdk.variant.variantcontext.writer;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.util.BlockCompressedInputStream;
import htsjdk.samtools.util.TestUtil;
import htsjdk.tribble.AbstractFeatureReader;
import htsjdk.tribble.FeatureReader;
import htsjdk.tribble.Tribble;
import htsjdk.tribble.readers.AsciiLineReader;
import htsjdk.tribble.readers.AsciiLineReaderIterator;
import htsjdk.tribble.util.TabixUtils;
import htsjdk.variant.VariantBaseTest;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.GenotypeBuilder;
import htsjdk.variant.variantcontext.GenotypesContext;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.VariantContextBuilder;
import htsjdk.variant.vcf.VCFCodec;
import htsjdk.variant.vcf.VCFFileReader;
import htsjdk.variant.vcf.VCFHeader;
import htsjdk.variant.vcf.VCFHeaderLine;
import htsjdk.variant.vcf.VCFHeaderVersion;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* @author aaron
* <p/>
* Class VCFWriterUnitTest
* <p/>
* This class tests out the ability of the VCF writer to correctly write VCF files
*/
public class VCFWriterUnitTest extends VariantBaseTest {
private Set<VCFHeaderLine> metaData;
private Set<String> additionalColumns;
private File tempDir;
@BeforeClass
private void createTemporaryDirectory() {
tempDir = TestUtil.getTempDirectory("VCFWriter", "StaleIndex");
tempDir.deleteOnExit();
}
/** test, using the writer and reader, that we can output and input a VCF file without problems */
@Test(dataProvider = "vcfExtensionsDataProvider")
public void testBasicWriteAndRead(final String extension) throws IOException {
final File fakeVCFFile = File.createTempFile("testBasicWriteAndRead.", extension, tempDir);
fakeVCFFile.deleteOnExit();
if (".vcf.gz".equals(extension)) {
new File(fakeVCFFile.getAbsolutePath() + ".tbi");
} else {
Tribble.indexFile(fakeVCFFile).deleteOnExit();
}
metaData = new HashSet<>();
additionalColumns = new HashSet<>();
final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary();
final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict);
final VariantContextWriter writer = new VariantContextWriterBuilder()
.setOutputFile(fakeVCFFile)
.setReferenceDictionary(sequenceDict)
.setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY))
.build();
writer.writeHeader(header);
writer.add(createVC(header));
writer.add(createVC(header));
writer.close();
final VCFCodec codec = new VCFCodec();
final FeatureReader<VariantContext> reader = AbstractFeatureReader.getFeatureReader(fakeVCFFile.getAbsolutePath(), codec, false);
final VCFHeader headerFromFile = (VCFHeader)reader.getHeader();
int counter = 0;
// validate what we're reading in
validateHeader(headerFromFile, sequenceDict);
try {
final Iterator<VariantContext> it = reader.iterator();
while(it.hasNext()) {
it.next();
counter++;
}
Assert.assertEquals(counter, 2);
}
catch (final IOException e ) {
throw new RuntimeException(e.getMessage());
}
}
/** test, using the writer and reader, that we can output and input a VCF body without problems */
@Test(dataProvider = "vcfExtensionsDataProvider")
public void testWriteAndReadVCFHeaderless(final String extension) throws IOException {
final File fakeVCFFile = File.createTempFile("testWriteAndReadVCFHeaderless.", extension, tempDir);
fakeVCFFile.deleteOnExit();
if (".vcf.gz".equals(extension)) {
new File(fakeVCFFile.getAbsolutePath() + ".tbi");
} else {
Tribble.indexFile(fakeVCFFile).deleteOnExit();
}
metaData = new HashSet<>();
additionalColumns = new HashSet<>();
final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary();
final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict);
try (final VariantContextWriter writer = new VariantContextWriterBuilder()
.setOutputFile(fakeVCFFile).setReferenceDictionary(sequenceDict)
.setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY))
.build()) {
writer.setHeader(header);
writer.add(createVC(header));
writer.add(createVC(header));
}
final VCFCodec codec = new VCFCodec();
codec.setVCFHeader(header, VCFHeaderVersion.VCF4_2);
try (BlockCompressedInputStream bcis = new BlockCompressedInputStream(fakeVCFFile);
FileInputStream fis = new FileInputStream(fakeVCFFile)) {
AsciiLineReaderIterator iterator =
new AsciiLineReaderIterator(new AsciiLineReader(".vcf.gz".equals(extension) ? bcis : fis));
int counter = 0;
while (iterator.hasNext()) {
VariantContext context = codec.decode(iterator.next());
counter++;
}
Assert.assertEquals(counter, 2);
}
}
@Test(expectedExceptions = IllegalStateException.class)
public void testWriteHeaderTwice() {
final File fakeVCFFile = VariantBaseTest.createTempFile("testBasicWriteAndRead.", ".vcf");
fakeVCFFile.deleteOnExit();
final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary();
final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict);
// prevent writing header twice
try (final VariantContextWriter writer1 = new VariantContextWriterBuilder()
.setOutputFile(fakeVCFFile)
.setReferenceDictionary(sequenceDict)
.build()) {
writer1.writeHeader(header);
writer1.writeHeader(header);
}
}
@Test(expectedExceptions = IllegalStateException.class)
public void testChangeHeaderAfterWritingHeader() {
final File fakeVCFFile = VariantBaseTest.createTempFile("testBasicWriteAndRead.", ".vcf");
fakeVCFFile.deleteOnExit();
final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary();
final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict);
// prevent changing header if it's already written
try (final VariantContextWriter writer2 = new VariantContextWriterBuilder()
.setOutputFile(fakeVCFFile)
.setReferenceDictionary(sequenceDict)
.build()) {
writer2.writeHeader(header);
writer2.setHeader(header);
}
}
@Test(expectedExceptions = IllegalStateException.class)
public void testChangeHeaderAfterWritingBody() {
final File fakeVCFFile = VariantBaseTest.createTempFile("testBasicWriteAndRead.", ".vcf");
fakeVCFFile.deleteOnExit();
final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary();
final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict);
// prevent changing header if part of body is already written
try (final VariantContextWriter writer3 = new VariantContextWriterBuilder()
.setOutputFile(fakeVCFFile)
.setReferenceDictionary(sequenceDict)
.build()) {
writer3.setHeader(header);
writer3.add(createVC(header));
writer3.setHeader(header);
}
}
/**
* create a fake header of known quantity
* @param metaData the header lines
* @param additionalColumns the additional column names
* @return a fake VCF header
*/
private static VCFHeader createFakeHeader(final Set<VCFHeaderLine> metaData, final Set<String> additionalColumns,
final SAMSequenceDictionary sequenceDict) {
metaData.add(new VCFHeaderLine(VCFHeaderVersion.VCF4_0.getFormatString(), VCFHeaderVersion.VCF4_0.getVersionString()));
metaData.add(new VCFHeaderLine("two", "2"));
additionalColumns.add("extra1");
additionalColumns.add("extra2");
final VCFHeader ret = new VCFHeader(metaData, additionalColumns);
ret.setSequenceDictionary(sequenceDict);
return ret;
}
/**
* create a fake VCF record
* @param header the VCF header
* @return a VCFRecord
*/
private VariantContext createVC(final VCFHeader header) {
return createVCGeneral(header,"1",1);
}
private VariantContext createVCGeneral(final VCFHeader header, final String chrom, final int position) {
final List<Allele> alleles = new ArrayList<Allele>();
final Map<String, Object> attributes = new HashMap<String,Object>();
final GenotypesContext genotypes = GenotypesContext.create(header.getGenotypeSamples().size());
alleles.add(Allele.create("A",true));
alleles.add(Allele.create("ACC",false));
attributes.put("DP","50");
for (final String name : header.getGenotypeSamples()) {
final Genotype gt = new GenotypeBuilder(name,alleles.subList(1,2)).GQ(0).attribute("BB", "1").phased(true).make();
genotypes.add(gt);
}
return new VariantContextBuilder("RANDOM", chrom, position, position, alleles)
.genotypes(genotypes).attributes(attributes).make();
}
/**
* validate a VCF header
* @param header the header to validate
*/
private void validateHeader(final VCFHeader header, final SAMSequenceDictionary sequenceDictionary) {
// check the fields
int index = 0;
for (final VCFHeader.HEADER_FIELDS field : header.getHeaderFields()) {
Assert.assertEquals(VCFHeader.HEADER_FIELDS.values()[index], field);
index++;
}
Assert.assertEquals(header.getMetaDataInSortedOrder().size(), metaData.size() + sequenceDictionary.size());
index = 0;
for (final String key : header.getGenotypeSamples()) {
Assert.assertTrue(additionalColumns.contains(key));
index++;
}
Assert.assertEquals(index, additionalColumns.size());
}
@Test(dataProvider = "vcfExtensionsDataProvider")
public void TestWritingLargeVCF(final String extension) throws FileNotFoundException, InterruptedException {
final Set<VCFHeaderLine> metaData = new HashSet<VCFHeaderLine>();
final Set<String> Columns = new HashSet<String>();
for (int i = 0; i < 123; i++) {
Columns.add(String.format("SAMPLE_%d", i));
}
final SAMSequenceDictionary dict = createArtificialSequenceDictionary();
final VCFHeader header = createFakeHeader(metaData,Columns, dict);
final File vcf = new File(tempDir, "test" + extension);
final String indexExtension;
if (extension.equals(".vcf.gz")) {
indexExtension = TabixUtils.STANDARD_INDEX_EXTENSION;
} else {
indexExtension = Tribble.STANDARD_INDEX_EXTENSION;
}
final File vcfIndex = new File(vcf.getAbsolutePath() + indexExtension);
vcfIndex.deleteOnExit();
for(int count=1;count<2; count++){
final VariantContextWriter writer = new VariantContextWriterBuilder()
.setOutputFile(vcf)
.setReferenceDictionary(dict)
.setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY))
.build();
writer.writeHeader(header);
for (int i = 1; i < 17 ; i++) { // write 17 chromosomes
for (int j = 1; j < 10; j++) { //10 records each
writer.add(createVCGeneral(header, String.format("%d", i), j * 100));
}
}
writer.close();
Assert.assertTrue(vcf.lastModified() <= vcfIndex.lastModified());
}
}
@DataProvider(name = "vcfExtensionsDataProvider")
public Object[][]vcfExtensionsDataProvider() {
return new Object[][] {
// TODO: BCF doesn't work because header is not properly constructed.
// {".bcf"},
{".vcf"},
{".vcf.gz"}
};
}
/**
* A test to ensure that if we add a line to a VCFHeader it will persist through
* a round-trip write/read cycle via VariantContextWriter/VCFFileReader
*/
@Test
public void testModifyHeader() {
final File originalVCF = new File("src/test/resources/htsjdk/variant/HiSeq.10000.vcf");
final VCFFileReader reader = new VCFFileReader(originalVCF, false);
final VCFHeader header = reader.getFileHeader();
reader.close();
header.addMetaDataLine(new VCFHeaderLine("FOOBAR", "foovalue"));
final File outputVCF = createTempFile("testModifyHeader", ".vcf");
final VariantContextWriter writer = new VariantContextWriterBuilder().setOutputFile(outputVCF).setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER)).build();
writer.writeHeader(header);
writer.close();
final VCFFileReader roundtripReader = new VCFFileReader(outputVCF, false);
final VCFHeader roundtripHeader = roundtripReader.getFileHeader();
roundtripReader.close();
Assert.assertNotNull(roundtripHeader.getOtherHeaderLine("FOOBAR"), "Could not find FOOBAR header line after a write/read cycle");
Assert.assertEquals(roundtripHeader.getOtherHeaderLine("FOOBAR").getValue(), "foovalue", "Wrong value for FOOBAR header line after a write/read cycle");
}
}
|
package org.aksw.rdfunit.model.interfaces.shacl;
import org.aksw.rdfunit.model.interfaces.TestCase;
import org.apache.jena.rdf.model.Literal;
public interface SparqlConstraint {
Shape getShape();
Literal getMessage();
Validator getValidator();
TestCase getTestCase();
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.operations.utils.factories;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.expressions.Expression;
import org.apache.flink.table.expressions.UnresolvedCallExpression;
import org.apache.flink.table.expressions.UnresolvedReferenceExpression;
import org.apache.flink.table.expressions.utils.ApiExpressionDefaultVisitor;
import org.apache.flink.table.expressions.utils.ApiExpressionUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static org.apache.flink.table.expressions.utils.ApiExpressionUtils.unresolvedRef;
import static org.apache.flink.table.functions.BuiltInFunctionDefinitions.AS;
import static org.apache.flink.table.operations.utils.OperationExpressionsUtils.extractName;
/**
* 用于从列操作,创建投影表达式的实用程序类
* Utility class for creating projection expressions from column operation.
*/
@Internal
public final class ColumnOperationUtils {
private static final DropColumnsExtractor dropColumnsExtractor = new DropColumnsExtractor();
private static final RenameColumnExtractor renameColumnExtractor = new RenameColumnExtractor();
/**
* 创建一个投影列表,将现有列重命名为新名称
* Creates a projection list that renames existing columns to new names.
*
* <p><b>NOTE:</b> Resulting expression are still unresolved.
*
* @param inputFields names of current columns
* @param newAliases new aliases for current columns;as表达式,举例a as a1, b as b1
* @return projection expressions
*/
public static List<Expression> renameColumns(List<String> inputFields, List<Expression> newAliases) {
LinkedHashMap<String, Expression> finalFields = new LinkedHashMap<>();
inputFields.forEach(field -> finalFields.put(field, unresolvedRef(field)));
newAliases.forEach(expr -> {
String name = expr.accept(renameColumnExtractor);
finalFields.put(name, expr);
});
return new ArrayList<>(finalFields.values());
}
/**
* 创建一个投影列表,新增或者替换已有的列
* Creates a projection list that adds new or replaces existing (if a column with corresponding name already exists)
* columns.
*
* <p><b>NOTE:</b> Resulting expression are still unresolved.
*
* @param inputFields names of current columns
* @param newExpressions new columns to add
* @return projection expressions
*/
public static List<Expression> addOrReplaceColumns(List<String> inputFields, List<Expression> newExpressions) {
LinkedHashMap<String, Expression> finalFields = new LinkedHashMap<>();
inputFields.forEach(field -> finalFields.put(field, unresolvedRef(field)));
newExpressions.forEach(expr -> {
String name = extractName(expr).orElse(expr.toString());
finalFields.put(name, expr);
});
return new ArrayList<>(finalFields.values());
}
/**
* 创建一个投影列表,去除给定的列
* Creates a projection list that removes given columns.
*
* <p><b>NOTE:</b> Resulting expression are still unresolved.
*
* @param inputFields names of current columns
* @param dropExpressions columns to remove
* @return projection expressions
*/
public static List<Expression> dropFields(List<String> inputFields, List<Expression> dropExpressions) {
Set<String> columnsToDrop = dropExpressions.stream()
.map(expr -> expr.accept(dropColumnsExtractor))
.collect(Collectors.toSet());
columnsToDrop.forEach(c -> {
if (!inputFields.contains(c)) {
throw new ValidationException(format("Field %s does not exist in source table", c));
}
});
return inputFields.stream()
.filter(oldName -> !columnsToDrop.contains(oldName))
.map(ApiExpressionUtils::unresolvedRef)
.collect(Collectors.toList());
}
private static class DropColumnsExtractor extends ApiExpressionDefaultVisitor<String> {
@Override
public String visit(UnresolvedReferenceExpression unresolvedReference) {
return unresolvedReference.getName();
}
@Override
protected String defaultMethod(Expression expression) {
throw new ValidationException("Unexpected drop column expression: " + expression);
}
}
private static class RenameColumnExtractor extends ApiExpressionDefaultVisitor<String> {
@Override
public String visit(UnresolvedCallExpression unresolvedCall) {
if (unresolvedCall.getFunctionDefinition() == AS &&
unresolvedCall.getChildren().get(0) instanceof UnresolvedReferenceExpression) {
UnresolvedReferenceExpression resolvedFieldReference =
(UnresolvedReferenceExpression) unresolvedCall.getChildren().get(0);
return resolvedFieldReference.getName();
} else {
return defaultMethod(unresolvedCall);
}
}
@Override
protected String defaultMethod(Expression expression) {
throw new ValidationException(
format(
"Invalid alias for a renaming column operation. Renaming must add an alias to an" +
"existing field. E.g.: 'a as a1'. But was: %s",
expression));
}
}
private ColumnOperationUtils() {
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.exceptions;
/**
* Thrown when credential definition is invalid.
* @author K. Benedyczak
*/
public class IllegalCredentialException extends EngineException
{
public IllegalCredentialException(String msg, Throwable cause)
{
super(msg, cause);
}
public IllegalCredentialException(String msg)
{
super(msg);
}
}
|
/*
* 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.search.geo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.geo.builders.ShapeBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.mapper.LegacyGeoShapeFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.test.ESIntegTestCase;
import static org.elasticsearch.index.query.QueryBuilders.geoShapeQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
public class LegacyGeoShapeIntegrationIT extends ESIntegTestCase {
/**
* Test that orientation parameter correctly persists across cluster restart
*/
public void testOrientationPersistence() throws Exception {
String idxName = "orientation";
String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("shape")
.startObject("properties").startObject("location")
.field("type", "geo_shape")
.field("tree", "quadtree")
.field("orientation", "left")
.endObject().endObject()
.endObject().endObject());
// create index
assertAcked(prepareCreate(idxName).addMapping("shape", mapping, XContentType.JSON));
mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("shape")
.startObject("properties").startObject("location")
.field("type", "geo_shape")
.field("tree", "quadtree")
.field("orientation", "right")
.endObject().endObject()
.endObject().endObject());
assertAcked(prepareCreate(idxName+"2").addMapping("shape", mapping, XContentType.JSON));
ensureGreen(idxName, idxName+"2");
internalCluster().fullRestart();
ensureGreen(idxName, idxName+"2");
// left orientation test
IndicesService indicesService = internalCluster().getInstance(IndicesService.class, findNodeName(idxName));
IndexService indexService = indicesService.indexService(resolveIndex(idxName));
MappedFieldType fieldType = indexService.mapperService().fullName("location");
assertThat(fieldType, instanceOf(LegacyGeoShapeFieldMapper.GeoShapeFieldType.class));
LegacyGeoShapeFieldMapper.GeoShapeFieldType gsfm = (LegacyGeoShapeFieldMapper.GeoShapeFieldType)fieldType;
ShapeBuilder.Orientation orientation = gsfm.orientation();
assertThat(orientation, equalTo(ShapeBuilder.Orientation.CLOCKWISE));
assertThat(orientation, equalTo(ShapeBuilder.Orientation.LEFT));
assertThat(orientation, equalTo(ShapeBuilder.Orientation.CW));
// right orientation test
indicesService = internalCluster().getInstance(IndicesService.class, findNodeName(idxName+"2"));
indexService = indicesService.indexService(resolveIndex((idxName+"2")));
fieldType = indexService.mapperService().fullName("location");
assertThat(fieldType, instanceOf(LegacyGeoShapeFieldMapper.GeoShapeFieldType.class));
gsfm = (LegacyGeoShapeFieldMapper.GeoShapeFieldType)fieldType;
orientation = gsfm.orientation();
assertThat(orientation, equalTo(ShapeBuilder.Orientation.COUNTER_CLOCKWISE));
assertThat(orientation, equalTo(ShapeBuilder.Orientation.RIGHT));
assertThat(orientation, equalTo(ShapeBuilder.Orientation.CCW));
}
/**
* Test that ignore_malformed on GeoShapeFieldMapper does not fail the entire document
*/
public void testIgnoreMalformed() throws Exception {
// create index
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("geometry", "shape", "type=geo_shape,tree=quadtree,ignore_malformed=true").get());
ensureGreen();
// test self crossing ccw poly not crossing dateline
String polygonGeoJson = Strings.toString(XContentFactory.jsonBuilder().startObject().field("type", "Polygon")
.startArray("coordinates")
.startArray()
.startArray().value(176.0).value(15.0).endArray()
.startArray().value(-177.0).value(10.0).endArray()
.startArray().value(-177.0).value(-10.0).endArray()
.startArray().value(176.0).value(-15.0).endArray()
.startArray().value(-177.0).value(15.0).endArray()
.startArray().value(172.0).value(0.0).endArray()
.startArray().value(176.0).value(15.0).endArray()
.endArray()
.endArray()
.endObject());
indexRandom(true, client().prepareIndex("test", "geometry", "0").setSource("shape",
polygonGeoJson));
SearchResponse searchResponse = client().prepareSearch("test").setQuery(matchAllQuery()).get();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
}
/**
* Test that the indexed shape routing can be provided if it is required
*/
public void testIndexShapeRouting() throws Exception {
String mapping = "{\n" +
" \"_routing\": {\n" +
" \"required\": true\n" +
" },\n" +
" \"properties\": {\n" +
" \"shape\": {\n" +
" \"type\": \"geo_shape\",\n" +
" \"tree\" : \"quadtree\"\n" +
" }\n" +
" }\n" +
" }";
// create index
assertAcked(client().admin().indices().prepareCreate("test").addMapping("doc", mapping, XContentType.JSON).get());
ensureGreen();
String source = "{\n" +
" \"shape\" : {\n" +
" \"type\" : \"bbox\",\n" +
" \"coordinates\" : [[-45.0, 45.0], [45.0, -45.0]]\n" +
" }\n" +
"}";
indexRandom(true, client().prepareIndex("test", "doc", "0").setSource(source, XContentType.JSON).setRouting("ABC"));
SearchResponse searchResponse = client().prepareSearch("test").setQuery(
geoShapeQuery("shape", "0", "doc").indexedShapeIndex("test").indexedShapeRouting("ABC")
).get();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
}
private String findNodeName(String index) {
ClusterState state = client().admin().cluster().prepareState().get().getState();
IndexShardRoutingTable shard = state.getRoutingTable().index(index).shard(0);
String nodeId = shard.assignedShards().get(0).currentNodeId();
return state.getNodes().get(nodeId).getName();
}
}
|
package com.atguigu.gmall.pms.dao;
import com.atguigu.gmall.pms.entity.AttrEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品属性
*
* @author lixianfeng
* @email lxf@atguigu.com
* @date 2020-03-10 14:18:33
*/
@Mapper
public interface AttrDao extends BaseMapper<AttrEntity> {
}
|
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.adwords.awreporting.util;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import junit.framework.Assert;
import org.joda.time.DateTime;
import org.junit.Test;
/**
* Test case for the {@link TemplateStringsUtil} class.
*
* @author joeltoby
*/
public class TemplateStringsUtilTest {
private Calendar calendar = Calendar.getInstance();
private SimpleDateFormat format = new SimpleDateFormat("MMMMM yyyy");
private SimpleDateFormat abrieviatedFromat = new SimpleDateFormat("MMM yyyy");
/**
* Tests formatting date ranges e.g. 'March 2014 - April 2014'
*/
@Test
public void testFormatFullMonthDateRange() {
calendar.set(2014, Calendar.MARCH, 1);
Date startDate = calendar.getTime();
calendar.set(2014, Calendar.APRIL, 30);
Date endDate = calendar.getTime();
String dateRange = TemplateStringsUtil.formatFullMonthDateRange(startDate,
endDate);
Assert.assertEquals(format.format(startDate) + " - " + format.format(endDate), dateRange);
calendar.set(2014, Calendar.MARCH, 10);
endDate = calendar.getTime();
dateRange = TemplateStringsUtil
.formatFullMonthDateRange(startDate, endDate);
Assert.assertEquals(format.format(endDate), dateRange);
DateTime startDateTime = new DateTime(2014, 3, 1, 0, 0);
DateTime endDateTime = new DateTime(2014, 4, 30, 0, 0);
dateRange = TemplateStringsUtil.formatFullMonthDateRange(startDateTime,
endDateTime);
Assert.assertEquals(format.format(startDateTime.toDate()) + " - "
+ format.format(endDateTime.toDate()), dateRange);
endDateTime = new DateTime(2014, 3, 10, 0, 0);
dateRange = TemplateStringsUtil.formatFullMonthDateRange(startDateTime,
endDateTime);
Assert.assertEquals(format.format(startDateTime.toDate()), dateRange);
}
/**
* Tests formatting date ranges to 'MMMM yyyy' e.g. 'March 2014'
*/
@Test
public void testFormatDateFullMonthYear() {
calendar.set(2014, Calendar.MARCH, 8);
Date date = calendar.getTime();
String formatted = TemplateStringsUtil.formatDateFullMonthYear(date);
Assert.assertEquals(format.format(date), formatted);
DateTime dateTime = new DateTime(2014, 3, 8, 0, 0);
formatted = TemplateStringsUtil.formatDateFullMonthYear(dateTime);
}
/**
* Tests formatting date ranges to 'MMM yyyy' e.g. 'Sep 2015'
*/
@Test
public void testFormatDateAbrieviatedMonthYear() {
calendar.set(2015, Calendar.SEPTEMBER, 21);
Date date = calendar.getTime();
String formatted = TemplateStringsUtil.formatDateAbrieviatedMonthYear(date);
Assert.assertEquals(abrieviatedFromat.format(date), formatted);
DateTime dateTime = new DateTime(2015, 9, 21, 0, 0);
formatted = TemplateStringsUtil.formatDateAbrieviatedMonthYear(dateTime);
Assert.assertEquals(abrieviatedFromat.format(dateTime.toDate()), formatted);
}
}
|
package com.techdisqus.services.transaction.controller;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthAccounts;
import org.web3j.protocol.core.methods.response.EthCoinbase;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import com.techdisqus.services.transaction.model.TransactionRequest;
@RestController
@RequestMapping("/transaction")
public class TransactionController {
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionController.class);
public static final BigInteger GAS_PRICE = BigInteger.valueOf(1L);
public static final BigInteger GAS_LIMIT = BigInteger.valueOf(21_000L);
@Value("${contract-service.url}")
String url;
@Autowired
Web3j web3j;
@Autowired
RestTemplate template;
Credentials credentials;
@PostConstruct
public void init() throws IOException, CipherException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
EthCoinbase coinbase = web3j.ethCoinbase().send();
EthAccounts accounts = web3j.ethAccounts().send();
for (int i = 1; i < accounts.getAccounts().size(); i++) {
EthGetTransactionCount transactionCount = web3j.ethGetTransactionCount(coinbase.getAddress(), DefaultBlockParameterName.LATEST).send();
Transaction transaction = Transaction.createEtherTransaction(coinbase.getAddress(), transactionCount.getTransactionCount(), GAS_PRICE, GAS_LIMIT, accounts.getAccounts().get(i), BigInteger.valueOf(25_000_000_000L));
web3j.ethSendTransaction(transaction).send();
EthGetBalance balance = web3j.ethGetBalance(accounts.getAccounts().get(i), DefaultBlockParameterName.LATEST).send();
LOGGER.info("Balance: address={}, amount={}", accounts.getAccounts().get(i), balance.getBalance().longValue());
}
}
@PostMapping
public String performTransaction(@RequestBody TransactionRequest request) throws Exception {
EthAccounts accounts = web3j.ethAccounts().send();
String owner = template.getForObject(url, String.class);
EthGetTransactionCount transactionCount = web3j.ethGetTransactionCount(accounts.getAccounts().get(request.getFromId()), DefaultBlockParameterName.LATEST).send();
Transaction transaction = Transaction.createEtherTransaction(accounts.getAccounts().get(request.getFromId()), transactionCount.getTransactionCount(), GAS_PRICE, GAS_LIMIT, owner, BigInteger.valueOf(request.getAmount()));
EthSendTransaction response = web3j.ethSendTransaction(transaction).send();
if (response.getError() != null) {
LOGGER.error("Transaction error: {}", response.getError().getMessage());
return "ERR";
}
LOGGER.info("Transaction: {}", response.getResult());
EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt(response.getTransactionHash()).send();
if (receipt.getTransactionReceipt().isPresent()) {
TransactionReceipt r = receipt.getTransactionReceipt().get();
LOGGER.info("Tx receipt: from={}, to={}, gas={}, cumulativeGas={}", r.getFrom(), r.getTo(), r.getGasUsed().intValue(), r.getCumulativeGasUsed().intValue());
}
EthGetBalance balance = web3j.ethGetBalance(accounts.getAccounts().get(request.getFromId()), DefaultBlockParameterName.LATEST).send();
LOGGER.info("Balance: address={}, amount={}", accounts.getAccounts().get(request.getFromId()), balance.getBalance().longValue());
balance = web3j.ethGetBalance(owner, DefaultBlockParameterName.LATEST).send();
LOGGER.info("Balance: address={}, amount={}", owner, balance.getBalance().longValue());
return response.getTransactionHash();
}
}
|
/**
* Copyright (c) 2007-2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.qna.logic;
import java.util.List;
import org.sakaiproject.qna.model.QnaCategory;
import org.sakaiproject.qna.model.QnaQuestion;
/**
* QNA API for Category logic
*
*/
public interface CategoryLogic {
/**
* Get a category with a specific id
*
* @param categoryId
* unique id of a {@link QnaCategory}
* @return {@link QnaCategory} object or null
*/
public QnaCategory getCategoryById(String categoryId);
/**
* Check if a category exists
*
* @param questionid
* unique id of a {@link QnaCategory}
* @return boolean
* true if it exists, false if it doesn't
*/
public boolean existsCategory(String categoryId);
/**
* Saves a category
*
* @param category
* {@link QnaCategory} object to be saved
* @param locationId unique id for location
*/
public void saveCategory(QnaCategory category, String locationId);
/**
* Removes a category
*
* @param categoryId
* {@link QnaCategory} object id to be removed
* @param locationId unique id for location
*/
public void removeCategory(String categoryId, String locationId);
/**
* Get questions for as specific category
*
* @param categoryId id of a {@link QnaCategory}
* @return {@link List} of {@link QnaQuestion} with all questions for a category
*/
public List<QnaQuestion> getQuestionsForCategory(String categoryId);
/**
* Get a list of categories for a location
*
* @param locationId unique id for location
* @return {@link List} of {@link QnaCategory} for location
*/
public List<QnaCategory> getCategoriesForLocation(String locationId);
/**
* Creates a default category
*
* @param locationId unique id for location
* @param ownerId id of sakai user
* @param categoryText text for category
* @return QnaCategory new {@link QnaCategory} created
*/
public QnaCategory createDefaultCategory(String locationId, String ownerId, String categoryText);
/**
* Sets default values for a new {@link QnaCategory} object
*
* @param qnaCategory {@link QnaCategory} object to set values to
* @param locationId unique id for location
* @param ownerId id of sakai user
*/
public void setNewCategoryDefaults(QnaCategory qnaCategory,String locationId, String ownerId);
/**
* Get default category for location (first one)
*
* @param locationId unique id for location
* @return QnaCategory default {@link QnaCategory} for location
*/
public QnaCategory getDefaultCategory(String locationId);
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.weathertestdemo;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int category=0x7f020000;
public static final int cityhot_edittext_bg=0x7f020001;
public static final int fanhui=0x7f020002;
public static final int ic_launcher=0x7f020003;
public static final int item_selector=0x7f020004;
public static final int shadow=0x7f020005;
public static final int text_selector=0x7f020006;
public static final int wb_btn_off_normal=0x7f020007;
public static final int wb_search_icon=0x7f020008;
public static final int weather=0x7f020009;
}
public static final class id {
public static final int action_settings=0x7f08002f;
public static final int back=0x7f080001;
public static final int btnList=0x7f080013;
public static final int city_name=0x7f080014;
public static final int current_date=0x7f080016;
public static final int et_search=0x7f080002;
public static final int fram_lv=0x7f080003;
public static final int grid_lin=0x7f08000a;
public static final int gv_recent_visit_city=0x7f08000f;
public static final int ll_item=0x7f080010;
public static final int ll_main=0x7f08000c;
public static final int lv_city=0x7f080004;
public static final int lv_result=0x7f080006;
public static final int my_letterview=0x7f080008;
public static final int publish_text=0x7f080012;
public static final int realTemp=0x7f080019;
public static final int rl_title=0x7f080000;
public static final int tv=0x7f08002e;
public static final int tv_Day1=0x7f08001e;
public static final int tv_Day2=0x7f080022;
public static final int tv_Day3=0x7f080026;
public static final int tv_Day4=0x7f08002a;
public static final int tv_Max=0x7f08001d;
public static final int tv_Max1=0x7f080021;
public static final int tv_Max2=0x7f080025;
public static final int tv_Max3=0x7f080029;
public static final int tv_Max4=0x7f08002d;
public static final int tv_Min=0x7f08001c;
public static final int tv_Min1=0x7f080020;
public static final int tv_Min2=0x7f080024;
public static final int tv_Min3=0x7f080028;
public static final int tv_Min4=0x7f08002c;
public static final int tv_Today=0x7f08001a;
public static final int tv_Weather=0x7f08001b;
public static final int tv_Weather1=0x7f08001f;
public static final int tv_Weather2=0x7f080023;
public static final int tv_Weather3=0x7f080027;
public static final int tv_Weather4=0x7f08002b;
public static final int tv_alpha=0x7f08000d;
public static final int tv_city_name=0x7f08000b;
public static final int tv_dialog=0x7f080005;
public static final int tv_noresult=0x7f080007;
public static final int tv_recent_visit_city=0x7f08000e;
public static final int tv_text=0x7f080009;
public static final int weather_desp=0x7f080018;
public static final int weather_info_layout=0x7f080015;
public static final int weather_layout=0x7f080011;
public static final int week=0x7f080017;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int item_all_city_textview=0x7f030001;
public static final int item_city=0x7f030002;
public static final int item_city_list=0x7f030003;
public static final int item_recent_visit_city=0x7f030004;
public static final int item_search_list=0x7f030005;
public static final int weather_layout=0x7f030006;
public static final int weather_listview=0x7f030007;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
public static final int action_settings=0x7f050002;
public static final int app_name=0x7f050000;
public static final int datas=0x7f050003;
public static final int hello_world=0x7f050001;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
|
public class BuyOrderFactory extends OrderFactory {
// TODO
public static Order generateOrder(double x,double y,String countryName){
Order order = null;
int orderAmount = Common.getRandomGenerator().nextInt(5);
int destinationX = Common.getRandomGenerator().nextInt(1650);
int speed = Common.getRandomGenerator().nextInt(100);
Position destination = new Position(destinationX, Common.getUpperLineY());
order = new BuyOrder(x,y,destination,orderAmount,speed,countryName);
return order;
}
}
|
/*******************************************************************************
* Copyright (c) 2012, Institute for Pervasive Computing, ETH Zurich.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Californium (Cf) CoAP framework.
******************************************************************************/
package ch.ethz.inf.vs.californium.endpoint;
import java.net.SocketException;
import ch.ethz.inf.vs.californium.coap.CommunicatorFactory;
import ch.ethz.inf.vs.californium.coap.CommunicatorFactory.Communicator;
import ch.ethz.inf.vs.californium.coap.Response;
import ch.ethz.inf.vs.californium.util.Properties;
/**
* The class LocalEndpoint provides the functionality of a server endpoint as a
* subclass of {@link Endpoint}. A server implementation using Cf will override
* this class to provide custom resources. Internally, the main purpose of this
* class is to forward received requests to the corresponding resource specified
* by the Uri-Path option. Furthermore, it implements the root resource to
* return a brief server description to GET requests with empty Uri-Path.
*
* @author Francesco Corazza
*/
public class ServerEndpoint extends LocalEndpoint {
private String mcastAddress = null;
private int udpPort = 0;
private boolean runAsDaemon = false;
private int transferBlockSize = 0;
private int requestPerSecond = 0;
public ServerEndpoint() throws SocketException {
this(Properties.std.getInt("DEFAULT_PORT"));
}
/**
* Instantiates a new local endpoint.
*
* @param port
* the port
* @throws SocketException
* the socket exception
*/
public ServerEndpoint(int port) throws SocketException {
this(null, port, 0); // let TransferLayer decide default
}
/**
* Instantiates a new local endpoint.
*
* @param mcastAddr
* the multicast IP address
* @param port
* the port
* @throws SocketException
* the socket exception
*/
public ServerEndpoint(String mcastAddr, int port) throws SocketException {
this(mcastAddr, port, 0); // let TransferLayer decide default
}
/**
* Instantiates a new local endpoint.
*
* @param mcastAddr
* the multicast IP address
* @param port
* the port
* @param transferBlockSize
* the default block sze
* @throws SocketException
* the socket exception
*/
public ServerEndpoint(String mcastAddr, int port, int transferBlockSize) throws SocketException {
this(mcastAddr, port, transferBlockSize, false, 0); // no runAsDaemon, keep JVM
// running to
// handle requests
}
/**
* Instantiates a new local endpoint.
*
* @param mcastAddr
* the multicast IP address
* @param port
* the port
* @param transferBlockSize
* the default block sze
* @param runAsDaemon
* the runAsDaemon
* @throws SocketException
* the socket exception
*/
public ServerEndpoint(String mcastAddr, int udpPort, int transferBlockSize, boolean runAsDaemon, int requestPerSecond) throws SocketException {
super();
this.mcastAddress = mcastAddr;
this.udpPort = udpPort;
this.transferBlockSize = transferBlockSize;
this.runAsDaemon = runAsDaemon;
this.requestPerSecond = requestPerSecond;
}
@Override
protected void createCommunicator() {
// get the communicator factory
CommunicatorFactory factory = CommunicatorFactory.getInstance();
// set the parameters of the communicator
factory.setMulticastAddress(mcastAddress);
factory.setUdpPort(udpPort);
factory.setTransferBlockSize(transferBlockSize);
factory.setRunAsDaemon(runAsDaemon);
factory.setRequestPerSecond(requestPerSecond);
// initialize communicator
Communicator communicator = factory.getCommunicator();
// register the endpoint as a receiver
communicator.registerReceiver(this);
}
@Override
protected void responseProduced(Response response) {
// do nothing
}
}
|
package com.tracelink.prodsec.plugin.veracode.sca.controller;
import com.tracelink.prodsec.plugin.veracode.sca.VeracodeScaPlugin;
import com.tracelink.prodsec.plugin.veracode.sca.model.VeracodeScaIssue;
import com.tracelink.prodsec.plugin.veracode.sca.model.VeracodeScaProject;
import com.tracelink.prodsec.plugin.veracode.sca.service.VeracodeScaProjectService;
import com.tracelink.prodsec.synapse.mvc.SynapseModelAndView;
import com.tracelink.prodsec.synapse.products.service.ProductsService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* The Veracode SCA dashboard controller handles requests to the main landing page
* for viewing additional statistics and data from the Veracode SCA server.
*
* @author mcool
*/
@Controller
@RequestMapping(VeracodeScaPlugin.DASHBOARD_PAGE)
public class VeracodeScaDashboardController {
private final ProductsService productsService;
private final VeracodeScaProjectService projectService;
public VeracodeScaDashboardController(@Autowired ProductsService productsService,
@Autowired VeracodeScaProjectService projectService) {
this.productsService = productsService;
this.projectService = projectService;
}
/**
* Returns necessary model objects, content view, and scripts in a {@link SynapseModelAndView}
* object to render the Veracode SCA dashboard statistics and main graph.
*
* @return {@link SynapseModelAndView} containing all info to render the
* Veracode SCA dashboard page
*/
@GetMapping("")
public SynapseModelAndView getDashboard() {
// Content view
SynapseModelAndView mv = new SynapseModelAndView("veracode-sca-dashboard");
// Small statistics boxes
List<VeracodeScaProject> projects = projectService.getIncludedProjects();
mv.addObject("coveredProjects", projects.size());
mv.addObject("vulnerableProjects",
projects.stream().filter(VeracodeScaProject::isVulnerable).count());
mv.addObject("totalIssues", projects.stream()
.map(VeracodeScaProject::getUnresolvedIssuesForVisibleBranch).mapToLong(List::size)
.sum());
mv.addObject("highIssues", projects.stream()
.map(VeracodeScaProject::getUnresolvedIssuesForVisibleBranch).flatMap(List::stream)
.filter(i -> i.getSeverityString().equals(VeracodeScaIssue.SEVERITY_HIGH)).count());
mv.addObject("vulnerableMethods", projects.stream()
.map(VeracodeScaProject::getUnresolvedIssuesForVisibleBranch).flatMap(List::stream)
.filter(VeracodeScaIssue::isVulnerableMethod).count());
// Product lines, project filters and projects for the graph dropdown menus
mv.addObject("productLines", productsService.getAllProductLines());
mv.addObject("filters", productsService.getAllProjectFilters());
mv.addObject("projects", productsService.getAllProjects());
// Scripts
mv.addScriptReference("/scripts/veracode/sca/util.js");
mv.addScriptReference("/scripts/veracode/sca/dashboard.js");
mv.addStyleReference("/styles/veracode/sca/dashboard.css");
return mv;
}
}
|
/*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.testapp.program;
import org.hisp.dhis.android.core.program.ProgramRuleVariable;
import org.hisp.dhis.android.core.program.ProgramRuleVariableSourceType;
import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestFullDispatcher;
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import static com.google.common.truth.Truth.assertThat;
@RunWith(D2JunitRunner.class)
public class ProgramRuleVariableCollectionRepositoryMockIntegrationShould extends BaseMockIntegrationTestFullDispatcher {
@Test
public void find_all() {
List<ProgramRuleVariable> ruleVariables =
d2.programModule().programRuleVariables()
.blockingGet();
assertThat(ruleVariables.size()).isEqualTo(2);
}
@Test
public void filter_by_use_code_for_option_set() {
List<ProgramRuleVariable> ruleVariables =
d2.programModule().programRuleVariables()
.byUseCodeForOptionSet()
.isFalse()
.blockingGet();
assertThat(ruleVariables.size()).isEqualTo(1);
}
@Test
public void filter_by_program() {
List<ProgramRuleVariable> ruleVariables =
d2.programModule().programRuleVariables()
.byProgramUid()
.eq("lxAQ7Zs9VYR")
.blockingGet();
assertThat(ruleVariables.size()).isEqualTo(2);
}
@Test
public void filter_by_program_stage() {
List<ProgramRuleVariable> ruleVariables =
d2.programModule().programRuleVariables()
.byProgramStageUid()
.eq("dBwrot7S420")
.blockingGet();
assertThat(ruleVariables.size()).isEqualTo(1);
}
@Test
public void filter_by_data_element() {
List<ProgramRuleVariable> ruleVariables =
d2.programModule().programRuleVariables()
.byDataElementUid()
.eq("sWoqcoByYmD")
.blockingGet();
assertThat(ruleVariables.size()).isEqualTo(1);
}
@Test
public void filter_by_tracked_entity_attribute() {
List<ProgramRuleVariable> ruleVariables =
d2.programModule().programRuleVariables()
.byTrackedEntityAttributeUid()
.eq("cejWyOfXge6")
.blockingGet();
assertThat(ruleVariables.size()).isEqualTo(1);
}
@Test
public void filter_by_program_rule_variable_source_type() {
List<ProgramRuleVariable> ruleVariables =
d2.programModule().programRuleVariables()
.byProgramRuleVariableSourceType()
.eq(ProgramRuleVariableSourceType.DATAELEMENT_NEWEST_EVENT_PROGRAM)
.blockingGet();
assertThat(ruleVariables.size()).isEqualTo(2);
}
}
|
package com.internousdev.webproj2.action;
import com.internousdev.webproj2.dao.TestDAO;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private String username;
private String password;
public String execute() {
String ret = ERROR;
TestDAO dao = new TestDAO();
int count = dao.insert(username, password);
if(count > 0) {
ret = SUCCESS;
}
return ret;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package java1;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
public class NestedIterator implements Iterator<Integer>{
public static void main(String[] args) {
List<NestedInteger> nestedList = new ArrayList<NestedInteger>();
NestedIterator i = new NestedIterator(nestedList);
while (i.hasNext()){
System.out.println(i.next());
}
}
List<NestedInteger> nestedList;
Integer nextRet;
Iterator<NestedInteger> iterator;
NestedIterator internal;
public NestedIterator(List<NestedInteger> nestedList) {
this.nestedList = nestedList;
this.iterator = nestedList.iterator();
}
@Override
public Integer next() {
Integer retValue = nextRet;
nextRet = null;
return retValue;
}
@Override
public boolean hasNext() {
if(nextRet != null){
return true;
}
if(internal!=null && internal.hasNext()){
nextRet = internal.next();
return true;
}
internal = null;
while(iterator.hasNext()){
NestedInteger next = iterator.next();
if(next.isInteger()){
nextRet = next.getInteger();
return true;
}
List<NestedInteger> list = next.getList();
internal = new NestedIterator(list);
boolean internalNext = internal.hasNext();
if(internalNext){
nextRet = internal.next();
return true;
}
}
return false;
}
}
interface NestedInteger {
// @return true if this NestedInteger holds a single integer, rather than a nested list.
public boolean isInteger();
// @return the single integer that this NestedInteger holds, if it holds a single integer
// Return null if this NestedInteger holds a nested list
public Integer getInteger();
// @return the nested list that this NestedInteger holds, if it holds a nested list
// Return null if this NestedInteger holds a single integer
public List<NestedInteger> getList();
}
|
/**
* 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 io.snappydata.util.com.clearspring.analytics.stream.membership;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* Allows for the controlled serialization/deserialization of a given type.
*/
public interface ICompactSerializer<T> {
/**
* Serialize the specified type into the specified DataOutputStream instance.
*
* @param t type that needs to be serialized
* @param dos DataOutput into which serialization needs to happen.
* @throws IOException
*/
public void serialize(T t, DataOutputStream dos) throws IOException;
/**
* Deserialize into the specified DataInputStream instance.
*
* @param dis DataInput from which deserialization needs to happen.
* @return the type that was deserialized
* @throws IOException
*/
public T deserialize(DataInputStream dis) throws IOException;
}
|
/*
* Copyright 2011 Henry Coles
*
* 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.pitest.util;
import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Timings {
public enum Stage {
MUTATION_PRE_SCAN("pre-scan for mutations"),
BUILD_MUTATION_TESTS("build mutation tests"),
RUN_MUTATION_TESTS("run mutation analysis"),
SCAN_CLASS_PATH("scan classpath"),
COVERAGE("coverage and dependency analysis");
private final String description;
Stage(final String desc) {
this.description = desc;
}
@Override
public String toString() {
return this.description;
}
}
private final Map<Stage, TimeSpan> timings = new LinkedHashMap<>();
public void registerStart(final Stage stage) {
this.timings.put(stage, new TimeSpan(System.currentTimeMillis(), 0));
}
public void registerEnd(final Stage stage) {
final long end = System.currentTimeMillis();
this.timings.get(stage).setEnd(end);
}
public void report(final PrintStream ps) {
long total = 0;
for (final Entry<Stage, TimeSpan> each : this.timings.entrySet()) {
total = total + each.getValue().duration();
ps.println("> " + each.getKey() + " : " + each.getValue());
}
ps.println(StringUtil.separatorLine());
ps.println("> Total " + " : " + new TimeSpan(0, total));
ps.println(StringUtil.separatorLine());
}
}
|
/*
* Copyright 2016-2021 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.iotevents;
import javax.annotation.Generated;
import com.amazonaws.services.iotevents.model.*;
/**
* Interface for accessing AWS IoT Events asynchronously. Each asynchronous method will return a Java Future object
* representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive
* notification when an asynchronous operation completes.
* <p>
* <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from
* {@link com.amazonaws.services.iotevents.AbstractAWSIoTEventsAsync} instead.
* </p>
* <p>
* <p>
* AWS IoT Events monitors your equipment or device fleets for failures or changes in operation, and triggers actions
* when such events occur. You can use AWS IoT Events API operations to create, read, update, and delete inputs and
* detector models, and to list their versions.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public interface AWSIoTEventsAsync extends AWSIoTEvents {
/**
* <p>
* Creates an alarm model to monitor an AWS IoT Events input attribute. You can use the alarm to get notified when
* the value is outside a specified range. For more information, see <a
* href="https://docs.aws.amazon.com/iotevents/latest/developerguide/create-alarms.html">Create an alarm model</a>
* in the <i>AWS IoT Events Developer Guide</i>.
* </p>
*
* @param createAlarmModelRequest
* @return A Java Future containing the result of the CreateAlarmModel operation returned by the service.
* @sample AWSIoTEventsAsync.CreateAlarmModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/CreateAlarmModel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<CreateAlarmModelResult> createAlarmModelAsync(CreateAlarmModelRequest createAlarmModelRequest);
/**
* <p>
* Creates an alarm model to monitor an AWS IoT Events input attribute. You can use the alarm to get notified when
* the value is outside a specified range. For more information, see <a
* href="https://docs.aws.amazon.com/iotevents/latest/developerguide/create-alarms.html">Create an alarm model</a>
* in the <i>AWS IoT Events Developer Guide</i>.
* </p>
*
* @param createAlarmModelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CreateAlarmModel operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.CreateAlarmModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/CreateAlarmModel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<CreateAlarmModelResult> createAlarmModelAsync(CreateAlarmModelRequest createAlarmModelRequest,
com.amazonaws.handlers.AsyncHandler<CreateAlarmModelRequest, CreateAlarmModelResult> asyncHandler);
/**
* <p>
* Creates a detector model.
* </p>
*
* @param createDetectorModelRequest
* @return A Java Future containing the result of the CreateDetectorModel operation returned by the service.
* @sample AWSIoTEventsAsync.CreateDetectorModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/CreateDetectorModel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<CreateDetectorModelResult> createDetectorModelAsync(CreateDetectorModelRequest createDetectorModelRequest);
/**
* <p>
* Creates a detector model.
* </p>
*
* @param createDetectorModelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CreateDetectorModel operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.CreateDetectorModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/CreateDetectorModel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<CreateDetectorModelResult> createDetectorModelAsync(CreateDetectorModelRequest createDetectorModelRequest,
com.amazonaws.handlers.AsyncHandler<CreateDetectorModelRequest, CreateDetectorModelResult> asyncHandler);
/**
* <p>
* Creates an input.
* </p>
*
* @param createInputRequest
* @return A Java Future containing the result of the CreateInput operation returned by the service.
* @sample AWSIoTEventsAsync.CreateInput
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/CreateInput" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<CreateInputResult> createInputAsync(CreateInputRequest createInputRequest);
/**
* <p>
* Creates an input.
* </p>
*
* @param createInputRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the CreateInput operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.CreateInput
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/CreateInput" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<CreateInputResult> createInputAsync(CreateInputRequest createInputRequest,
com.amazonaws.handlers.AsyncHandler<CreateInputRequest, CreateInputResult> asyncHandler);
/**
* <p>
* Deletes an alarm model. Any alarm instances that were created based on this alarm model are also deleted. This
* action can't be undone.
* </p>
*
* @param deleteAlarmModelRequest
* @return A Java Future containing the result of the DeleteAlarmModel operation returned by the service.
* @sample AWSIoTEventsAsync.DeleteAlarmModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DeleteAlarmModel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DeleteAlarmModelResult> deleteAlarmModelAsync(DeleteAlarmModelRequest deleteAlarmModelRequest);
/**
* <p>
* Deletes an alarm model. Any alarm instances that were created based on this alarm model are also deleted. This
* action can't be undone.
* </p>
*
* @param deleteAlarmModelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DeleteAlarmModel operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.DeleteAlarmModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DeleteAlarmModel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DeleteAlarmModelResult> deleteAlarmModelAsync(DeleteAlarmModelRequest deleteAlarmModelRequest,
com.amazonaws.handlers.AsyncHandler<DeleteAlarmModelRequest, DeleteAlarmModelResult> asyncHandler);
/**
* <p>
* Deletes a detector model. Any active instances of the detector model are also deleted.
* </p>
*
* @param deleteDetectorModelRequest
* @return A Java Future containing the result of the DeleteDetectorModel operation returned by the service.
* @sample AWSIoTEventsAsync.DeleteDetectorModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DeleteDetectorModel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DeleteDetectorModelResult> deleteDetectorModelAsync(DeleteDetectorModelRequest deleteDetectorModelRequest);
/**
* <p>
* Deletes a detector model. Any active instances of the detector model are also deleted.
* </p>
*
* @param deleteDetectorModelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DeleteDetectorModel operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.DeleteDetectorModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DeleteDetectorModel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DeleteDetectorModelResult> deleteDetectorModelAsync(DeleteDetectorModelRequest deleteDetectorModelRequest,
com.amazonaws.handlers.AsyncHandler<DeleteDetectorModelRequest, DeleteDetectorModelResult> asyncHandler);
/**
* <p>
* Deletes an input.
* </p>
*
* @param deleteInputRequest
* @return A Java Future containing the result of the DeleteInput operation returned by the service.
* @sample AWSIoTEventsAsync.DeleteInput
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DeleteInput" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DeleteInputResult> deleteInputAsync(DeleteInputRequest deleteInputRequest);
/**
* <p>
* Deletes an input.
* </p>
*
* @param deleteInputRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DeleteInput operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.DeleteInput
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DeleteInput" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DeleteInputResult> deleteInputAsync(DeleteInputRequest deleteInputRequest,
com.amazonaws.handlers.AsyncHandler<DeleteInputRequest, DeleteInputResult> asyncHandler);
/**
* <p>
* Retrieves information about an alarm model. If you don't specify a value for the <code>alarmModelVersion</code>
* parameter, the latest version is returned.
* </p>
*
* @param describeAlarmModelRequest
* @return A Java Future containing the result of the DescribeAlarmModel operation returned by the service.
* @sample AWSIoTEventsAsync.DescribeAlarmModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeAlarmModel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribeAlarmModelResult> describeAlarmModelAsync(DescribeAlarmModelRequest describeAlarmModelRequest);
/**
* <p>
* Retrieves information about an alarm model. If you don't specify a value for the <code>alarmModelVersion</code>
* parameter, the latest version is returned.
* </p>
*
* @param describeAlarmModelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeAlarmModel operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.DescribeAlarmModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeAlarmModel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<DescribeAlarmModelResult> describeAlarmModelAsync(DescribeAlarmModelRequest describeAlarmModelRequest,
com.amazonaws.handlers.AsyncHandler<DescribeAlarmModelRequest, DescribeAlarmModelResult> asyncHandler);
/**
* <p>
* Describes a detector model. If the <code>version</code> parameter is not specified, information about the latest
* version is returned.
* </p>
*
* @param describeDetectorModelRequest
* @return A Java Future containing the result of the DescribeDetectorModel operation returned by the service.
* @sample AWSIoTEventsAsync.DescribeDetectorModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeDetectorModel"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DescribeDetectorModelResult> describeDetectorModelAsync(DescribeDetectorModelRequest describeDetectorModelRequest);
/**
* <p>
* Describes a detector model. If the <code>version</code> parameter is not specified, information about the latest
* version is returned.
* </p>
*
* @param describeDetectorModelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeDetectorModel operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.DescribeDetectorModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeDetectorModel"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DescribeDetectorModelResult> describeDetectorModelAsync(DescribeDetectorModelRequest describeDetectorModelRequest,
com.amazonaws.handlers.AsyncHandler<DescribeDetectorModelRequest, DescribeDetectorModelResult> asyncHandler);
/**
* <p>
* Retrieves runtime information about a detector model analysis.
* </p>
* <note>
* <p>
* After AWS IoT Events starts analyzing your detector model, you have up to 24 hours to retrieve the analysis
* results.
* </p>
* </note>
*
* @param describeDetectorModelAnalysisRequest
* @return A Java Future containing the result of the DescribeDetectorModelAnalysis operation returned by the
* service.
* @sample AWSIoTEventsAsync.DescribeDetectorModelAnalysis
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeDetectorModelAnalysis"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DescribeDetectorModelAnalysisResult> describeDetectorModelAnalysisAsync(
DescribeDetectorModelAnalysisRequest describeDetectorModelAnalysisRequest);
/**
* <p>
* Retrieves runtime information about a detector model analysis.
* </p>
* <note>
* <p>
* After AWS IoT Events starts analyzing your detector model, you have up to 24 hours to retrieve the analysis
* results.
* </p>
* </note>
*
* @param describeDetectorModelAnalysisRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeDetectorModelAnalysis operation returned by the
* service.
* @sample AWSIoTEventsAsyncHandler.DescribeDetectorModelAnalysis
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeDetectorModelAnalysis"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DescribeDetectorModelAnalysisResult> describeDetectorModelAnalysisAsync(
DescribeDetectorModelAnalysisRequest describeDetectorModelAnalysisRequest,
com.amazonaws.handlers.AsyncHandler<DescribeDetectorModelAnalysisRequest, DescribeDetectorModelAnalysisResult> asyncHandler);
/**
* <p>
* Describes an input.
* </p>
*
* @param describeInputRequest
* @return A Java Future containing the result of the DescribeInput operation returned by the service.
* @sample AWSIoTEventsAsync.DescribeInput
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeInput" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DescribeInputResult> describeInputAsync(DescribeInputRequest describeInputRequest);
/**
* <p>
* Describes an input.
* </p>
*
* @param describeInputRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeInput operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.DescribeInput
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeInput" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<DescribeInputResult> describeInputAsync(DescribeInputRequest describeInputRequest,
com.amazonaws.handlers.AsyncHandler<DescribeInputRequest, DescribeInputResult> asyncHandler);
/**
* <p>
* Retrieves the current settings of the AWS IoT Events logging options.
* </p>
*
* @param describeLoggingOptionsRequest
* @return A Java Future containing the result of the DescribeLoggingOptions operation returned by the service.
* @sample AWSIoTEventsAsync.DescribeLoggingOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeLoggingOptions"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DescribeLoggingOptionsResult> describeLoggingOptionsAsync(DescribeLoggingOptionsRequest describeLoggingOptionsRequest);
/**
* <p>
* Retrieves the current settings of the AWS IoT Events logging options.
* </p>
*
* @param describeLoggingOptionsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the DescribeLoggingOptions operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.DescribeLoggingOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/DescribeLoggingOptions"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<DescribeLoggingOptionsResult> describeLoggingOptionsAsync(DescribeLoggingOptionsRequest describeLoggingOptionsRequest,
com.amazonaws.handlers.AsyncHandler<DescribeLoggingOptionsRequest, DescribeLoggingOptionsResult> asyncHandler);
/**
* <p>
* Retrieves one or more analysis results of the detector model.
* </p>
* <note>
* <p>
* After AWS IoT Events starts analyzing your detector model, you have up to 24 hours to retrieve the analysis
* results.
* </p>
* </note>
*
* @param getDetectorModelAnalysisResultsRequest
* @return A Java Future containing the result of the GetDetectorModelAnalysisResults operation returned by the
* service.
* @sample AWSIoTEventsAsync.GetDetectorModelAnalysisResults
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/GetDetectorModelAnalysisResults"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<GetDetectorModelAnalysisResultsResult> getDetectorModelAnalysisResultsAsync(
GetDetectorModelAnalysisResultsRequest getDetectorModelAnalysisResultsRequest);
/**
* <p>
* Retrieves one or more analysis results of the detector model.
* </p>
* <note>
* <p>
* After AWS IoT Events starts analyzing your detector model, you have up to 24 hours to retrieve the analysis
* results.
* </p>
* </note>
*
* @param getDetectorModelAnalysisResultsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the GetDetectorModelAnalysisResults operation returned by the
* service.
* @sample AWSIoTEventsAsyncHandler.GetDetectorModelAnalysisResults
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/GetDetectorModelAnalysisResults"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<GetDetectorModelAnalysisResultsResult> getDetectorModelAnalysisResultsAsync(
GetDetectorModelAnalysisResultsRequest getDetectorModelAnalysisResultsRequest,
com.amazonaws.handlers.AsyncHandler<GetDetectorModelAnalysisResultsRequest, GetDetectorModelAnalysisResultsResult> asyncHandler);
/**
* <p>
* Lists all the versions of an alarm model. The operation returns only the metadata associated with each alarm
* model version.
* </p>
*
* @param listAlarmModelVersionsRequest
* @return A Java Future containing the result of the ListAlarmModelVersions operation returned by the service.
* @sample AWSIoTEventsAsync.ListAlarmModelVersions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListAlarmModelVersions"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<ListAlarmModelVersionsResult> listAlarmModelVersionsAsync(ListAlarmModelVersionsRequest listAlarmModelVersionsRequest);
/**
* <p>
* Lists all the versions of an alarm model. The operation returns only the metadata associated with each alarm
* model version.
* </p>
*
* @param listAlarmModelVersionsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListAlarmModelVersions operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.ListAlarmModelVersions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListAlarmModelVersions"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<ListAlarmModelVersionsResult> listAlarmModelVersionsAsync(ListAlarmModelVersionsRequest listAlarmModelVersionsRequest,
com.amazonaws.handlers.AsyncHandler<ListAlarmModelVersionsRequest, ListAlarmModelVersionsResult> asyncHandler);
/**
* <p>
* Lists the alarm models that you created. The operation returns only the metadata associated with each alarm
* model.
* </p>
*
* @param listAlarmModelsRequest
* @return A Java Future containing the result of the ListAlarmModels operation returned by the service.
* @sample AWSIoTEventsAsync.ListAlarmModels
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListAlarmModels" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListAlarmModelsResult> listAlarmModelsAsync(ListAlarmModelsRequest listAlarmModelsRequest);
/**
* <p>
* Lists the alarm models that you created. The operation returns only the metadata associated with each alarm
* model.
* </p>
*
* @param listAlarmModelsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListAlarmModels operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.ListAlarmModels
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListAlarmModels" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListAlarmModelsResult> listAlarmModelsAsync(ListAlarmModelsRequest listAlarmModelsRequest,
com.amazonaws.handlers.AsyncHandler<ListAlarmModelsRequest, ListAlarmModelsResult> asyncHandler);
/**
* <p>
* Lists all the versions of a detector model. Only the metadata associated with each detector model version is
* returned.
* </p>
*
* @param listDetectorModelVersionsRequest
* @return A Java Future containing the result of the ListDetectorModelVersions operation returned by the service.
* @sample AWSIoTEventsAsync.ListDetectorModelVersions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListDetectorModelVersions"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<ListDetectorModelVersionsResult> listDetectorModelVersionsAsync(
ListDetectorModelVersionsRequest listDetectorModelVersionsRequest);
/**
* <p>
* Lists all the versions of a detector model. Only the metadata associated with each detector model version is
* returned.
* </p>
*
* @param listDetectorModelVersionsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListDetectorModelVersions operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.ListDetectorModelVersions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListDetectorModelVersions"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<ListDetectorModelVersionsResult> listDetectorModelVersionsAsync(
ListDetectorModelVersionsRequest listDetectorModelVersionsRequest,
com.amazonaws.handlers.AsyncHandler<ListDetectorModelVersionsRequest, ListDetectorModelVersionsResult> asyncHandler);
/**
* <p>
* Lists the detector models you have created. Only the metadata associated with each detector model is returned.
* </p>
*
* @param listDetectorModelsRequest
* @return A Java Future containing the result of the ListDetectorModels operation returned by the service.
* @sample AWSIoTEventsAsync.ListDetectorModels
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListDetectorModels" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<ListDetectorModelsResult> listDetectorModelsAsync(ListDetectorModelsRequest listDetectorModelsRequest);
/**
* <p>
* Lists the detector models you have created. Only the metadata associated with each detector model is returned.
* </p>
*
* @param listDetectorModelsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListDetectorModels operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.ListDetectorModels
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListDetectorModels" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<ListDetectorModelsResult> listDetectorModelsAsync(ListDetectorModelsRequest listDetectorModelsRequest,
com.amazonaws.handlers.AsyncHandler<ListDetectorModelsRequest, ListDetectorModelsResult> asyncHandler);
/**
* <p>
* Lists one or more input routings.
* </p>
*
* @param listInputRoutingsRequest
* @return A Java Future containing the result of the ListInputRoutings operation returned by the service.
* @sample AWSIoTEventsAsync.ListInputRoutings
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListInputRoutings" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<ListInputRoutingsResult> listInputRoutingsAsync(ListInputRoutingsRequest listInputRoutingsRequest);
/**
* <p>
* Lists one or more input routings.
* </p>
*
* @param listInputRoutingsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListInputRoutings operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.ListInputRoutings
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListInputRoutings" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<ListInputRoutingsResult> listInputRoutingsAsync(ListInputRoutingsRequest listInputRoutingsRequest,
com.amazonaws.handlers.AsyncHandler<ListInputRoutingsRequest, ListInputRoutingsResult> asyncHandler);
/**
* <p>
* Lists the inputs you have created.
* </p>
*
* @param listInputsRequest
* @return A Java Future containing the result of the ListInputs operation returned by the service.
* @sample AWSIoTEventsAsync.ListInputs
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListInputs" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListInputsResult> listInputsAsync(ListInputsRequest listInputsRequest);
/**
* <p>
* Lists the inputs you have created.
* </p>
*
* @param listInputsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListInputs operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.ListInputs
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListInputs" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<ListInputsResult> listInputsAsync(ListInputsRequest listInputsRequest,
com.amazonaws.handlers.AsyncHandler<ListInputsRequest, ListInputsResult> asyncHandler);
/**
* <p>
* Lists the tags (metadata) you have assigned to the resource.
* </p>
*
* @param listTagsForResourceRequest
* @return A Java Future containing the result of the ListTagsForResource operation returned by the service.
* @sample AWSIoTEventsAsync.ListTagsForResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListTagsForResource" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest listTagsForResourceRequest);
/**
* <p>
* Lists the tags (metadata) you have assigned to the resource.
* </p>
*
* @param listTagsForResourceRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the ListTagsForResource operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.ListTagsForResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/ListTagsForResource" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<ListTagsForResourceResult> listTagsForResourceAsync(ListTagsForResourceRequest listTagsForResourceRequest,
com.amazonaws.handlers.AsyncHandler<ListTagsForResourceRequest, ListTagsForResourceResult> asyncHandler);
/**
* <p>
* Sets or updates the AWS IoT Events logging options.
* </p>
* <p>
* If you update the value of any <code>loggingOptions</code> field, it takes up to one minute for the change to
* take effect. If you change the policy attached to the role you specified in the <code>roleArn</code> field (for
* example, to correct an invalid policy), it takes up to five minutes for that change to take effect.
* </p>
*
* @param putLoggingOptionsRequest
* @return A Java Future containing the result of the PutLoggingOptions operation returned by the service.
* @sample AWSIoTEventsAsync.PutLoggingOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/PutLoggingOptions" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<PutLoggingOptionsResult> putLoggingOptionsAsync(PutLoggingOptionsRequest putLoggingOptionsRequest);
/**
* <p>
* Sets or updates the AWS IoT Events logging options.
* </p>
* <p>
* If you update the value of any <code>loggingOptions</code> field, it takes up to one minute for the change to
* take effect. If you change the policy attached to the role you specified in the <code>roleArn</code> field (for
* example, to correct an invalid policy), it takes up to five minutes for that change to take effect.
* </p>
*
* @param putLoggingOptionsRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the PutLoggingOptions operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.PutLoggingOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/PutLoggingOptions" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<PutLoggingOptionsResult> putLoggingOptionsAsync(PutLoggingOptionsRequest putLoggingOptionsRequest,
com.amazonaws.handlers.AsyncHandler<PutLoggingOptionsRequest, PutLoggingOptionsResult> asyncHandler);
/**
* <p>
* Performs an analysis of your detector model. For more information, see <a
* href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-analyze-api.html">Troubleshooting a
* detector model</a> in the <i>AWS IoT Events Developer Guide</i>.
* </p>
*
* @param startDetectorModelAnalysisRequest
* @return A Java Future containing the result of the StartDetectorModelAnalysis operation returned by the service.
* @sample AWSIoTEventsAsync.StartDetectorModelAnalysis
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/StartDetectorModelAnalysis"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<StartDetectorModelAnalysisResult> startDetectorModelAnalysisAsync(
StartDetectorModelAnalysisRequest startDetectorModelAnalysisRequest);
/**
* <p>
* Performs an analysis of your detector model. For more information, see <a
* href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-analyze-api.html">Troubleshooting a
* detector model</a> in the <i>AWS IoT Events Developer Guide</i>.
* </p>
*
* @param startDetectorModelAnalysisRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the StartDetectorModelAnalysis operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.StartDetectorModelAnalysis
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/StartDetectorModelAnalysis"
* target="_top">AWS API Documentation</a>
*/
java.util.concurrent.Future<StartDetectorModelAnalysisResult> startDetectorModelAnalysisAsync(
StartDetectorModelAnalysisRequest startDetectorModelAnalysisRequest,
com.amazonaws.handlers.AsyncHandler<StartDetectorModelAnalysisRequest, StartDetectorModelAnalysisResult> asyncHandler);
/**
* <p>
* Adds to or modifies the tags of the given resource. Tags are metadata that can be used to manage a resource.
* </p>
*
* @param tagResourceRequest
* @return A Java Future containing the result of the TagResource operation returned by the service.
* @sample AWSIoTEventsAsync.TagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/TagResource" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest tagResourceRequest);
/**
* <p>
* Adds to or modifies the tags of the given resource. Tags are metadata that can be used to manage a resource.
* </p>
*
* @param tagResourceRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the TagResource operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.TagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/TagResource" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<TagResourceResult> tagResourceAsync(TagResourceRequest tagResourceRequest,
com.amazonaws.handlers.AsyncHandler<TagResourceRequest, TagResourceResult> asyncHandler);
/**
* <p>
* Removes the given tags (metadata) from the resource.
* </p>
*
* @param untagResourceRequest
* @return A Java Future containing the result of the UntagResource operation returned by the service.
* @sample AWSIoTEventsAsync.UntagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UntagResource" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest untagResourceRequest);
/**
* <p>
* Removes the given tags (metadata) from the resource.
* </p>
*
* @param untagResourceRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UntagResource operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.UntagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UntagResource" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UntagResourceResult> untagResourceAsync(UntagResourceRequest untagResourceRequest,
com.amazonaws.handlers.AsyncHandler<UntagResourceRequest, UntagResourceResult> asyncHandler);
/**
* <p>
* Updates an alarm model. Any alarms that were created based on the previous version are deleted and then created
* again as new data arrives.
* </p>
*
* @param updateAlarmModelRequest
* @return A Java Future containing the result of the UpdateAlarmModel operation returned by the service.
* @sample AWSIoTEventsAsync.UpdateAlarmModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UpdateAlarmModel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UpdateAlarmModelResult> updateAlarmModelAsync(UpdateAlarmModelRequest updateAlarmModelRequest);
/**
* <p>
* Updates an alarm model. Any alarms that were created based on the previous version are deleted and then created
* again as new data arrives.
* </p>
*
* @param updateAlarmModelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UpdateAlarmModel operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.UpdateAlarmModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UpdateAlarmModel" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UpdateAlarmModelResult> updateAlarmModelAsync(UpdateAlarmModelRequest updateAlarmModelRequest,
com.amazonaws.handlers.AsyncHandler<UpdateAlarmModelRequest, UpdateAlarmModelResult> asyncHandler);
/**
* <p>
* Updates a detector model. Detectors (instances) spawned by the previous version are deleted and then re-created
* as new inputs arrive.
* </p>
*
* @param updateDetectorModelRequest
* @return A Java Future containing the result of the UpdateDetectorModel operation returned by the service.
* @sample AWSIoTEventsAsync.UpdateDetectorModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UpdateDetectorModel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<UpdateDetectorModelResult> updateDetectorModelAsync(UpdateDetectorModelRequest updateDetectorModelRequest);
/**
* <p>
* Updates a detector model. Detectors (instances) spawned by the previous version are deleted and then re-created
* as new inputs arrive.
* </p>
*
* @param updateDetectorModelRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UpdateDetectorModel operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.UpdateDetectorModel
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UpdateDetectorModel" target="_top">AWS
* API Documentation</a>
*/
java.util.concurrent.Future<UpdateDetectorModelResult> updateDetectorModelAsync(UpdateDetectorModelRequest updateDetectorModelRequest,
com.amazonaws.handlers.AsyncHandler<UpdateDetectorModelRequest, UpdateDetectorModelResult> asyncHandler);
/**
* <p>
* Updates an input.
* </p>
*
* @param updateInputRequest
* @return A Java Future containing the result of the UpdateInput operation returned by the service.
* @sample AWSIoTEventsAsync.UpdateInput
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UpdateInput" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UpdateInputResult> updateInputAsync(UpdateInputRequest updateInputRequest);
/**
* <p>
* Updates an input.
* </p>
*
* @param updateInputRequest
* @param asyncHandler
* Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
* implementation of the callback methods in this interface to receive notification of successful or
* unsuccessful completion of the operation.
* @return A Java Future containing the result of the UpdateInput operation returned by the service.
* @sample AWSIoTEventsAsyncHandler.UpdateInput
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UpdateInput" target="_top">AWS API
* Documentation</a>
*/
java.util.concurrent.Future<UpdateInputResult> updateInputAsync(UpdateInputRequest updateInputRequest,
com.amazonaws.handlers.AsyncHandler<UpdateInputRequest, UpdateInputResult> asyncHandler);
}
|
/*
* Copyright 2020 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.teku.beaconrestapi.handlers.v1.beacon;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.PARAM_STATE_ID;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.PARAM_STATE_ID_DESCRIPTION;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.RES_BAD_REQUEST;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.RES_INTERNAL_ERROR;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.RES_NOT_FOUND;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.RES_OK;
import static tech.pegasys.teku.beaconrestapi.RestApiConstants.TAG_BEACON;
import static tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_NOT_FOUND;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.javalin.http.Context;
import io.javalin.http.Handler;
import io.javalin.plugin.openapi.annotations.HttpMethod;
import io.javalin.plugin.openapi.annotations.OpenApi;
import io.javalin.plugin.openapi.annotations.OpenApiContent;
import io.javalin.plugin.openapi.annotations.OpenApiParam;
import io.javalin.plugin.openapi.annotations.OpenApiResponse;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.NotNull;
import tech.pegasys.teku.api.ChainDataProvider;
import tech.pegasys.teku.api.DataProvider;
import tech.pegasys.teku.api.response.v1.beacon.FinalityCheckpointsResponse;
import tech.pegasys.teku.api.response.v1.beacon.GetStateFinalityCheckpointsResponse;
import tech.pegasys.teku.beaconrestapi.handlers.AbstractHandler;
import tech.pegasys.teku.infrastructure.async.SafeFuture;
import tech.pegasys.teku.provider.JsonProvider;
public class GetStateFinalityCheckpoints extends AbstractHandler implements Handler {
public static final String ROUTE = "/eth/v1/beacon/states/:state_id/finality_checkpoints";
private final ChainDataProvider chainDataProvider;
public GetStateFinalityCheckpoints(
final DataProvider dataProvider, final JsonProvider jsonProvider) {
super(jsonProvider);
this.chainDataProvider = dataProvider.getChainDataProvider();
}
GetStateFinalityCheckpoints(
final ChainDataProvider chainDataProvider, final JsonProvider jsonProvider) {
super(jsonProvider);
this.chainDataProvider = chainDataProvider;
}
@OpenApi(
path = ROUTE,
method = HttpMethod.GET,
summary = "Get state finality checkpoints",
tags = {TAG_BEACON},
description =
"Returns finality checkpoints for state with given 'state_id'. In case finality is not yet achieved, checkpoint should return epoch 0 and ZERO_HASH as root.",
pathParams = {@OpenApiParam(name = PARAM_STATE_ID, description = PARAM_STATE_ID_DESCRIPTION)},
responses = {
@OpenApiResponse(
status = RES_OK,
content = @OpenApiContent(from = GetStateFinalityCheckpointsResponse.class)),
@OpenApiResponse(status = RES_BAD_REQUEST),
@OpenApiResponse(status = RES_NOT_FOUND),
@OpenApiResponse(status = RES_INTERNAL_ERROR)
})
@Override
public void handle(@NotNull final Context ctx) throws Exception {
final Map<String, String> pathParamMap = ctx.pathParamMap();
final SafeFuture<Optional<FinalityCheckpointsResponse>> future =
chainDataProvider.getStateFinalityCheckpoints(pathParamMap.get(PARAM_STATE_ID));
handleOptionalResult(ctx, future, this::handleResult, SC_NOT_FOUND);
}
private Optional<String> handleResult(Context ctx, final FinalityCheckpointsResponse response)
throws JsonProcessingException {
return Optional.of(
jsonProvider.objectToJSON(new GetStateFinalityCheckpointsResponse(response)));
}
}
|
package com.yapp.project.notification.service;
import com.yapp.project.common.exception.ExceptionMessage;
import com.yapp.project.common.exception.type.NotFoundException;
import com.yapp.project.member.entity.Member;
import com.yapp.project.member.repository.MemberRepository;
import com.yapp.project.notification.dto.NotificationResponse;
import com.yapp.project.notification.entity.Notification;
import com.yapp.project.notification.entity.Unread;
import com.yapp.project.notification.repository.NotificationRepository;
import com.yapp.project.notification.repository.UnreadRepository;
import com.yapp.project.post.entity.Post;
import com.yapp.project.post.repository.PostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class NotificationService {
private final NotificationRepository notificationRepository;
private final UnreadRepository unreadRepository;
private final NotificationConverter converter;
private final MemberRepository memberRepository;
private final PostRepository postRepository;
@Transactional
public void save(long receiverId, String title, String body, int notificationTypeCode, long relatedPostId) {
Member receiver = memberRepository.findById(receiverId)
.orElseThrow(() -> new NotFoundException(ExceptionMessage.MEMBER_NOT_FOUND));
Post relatedPost = postRepository.findById(relatedPostId)
.orElseThrow(() -> new NotFoundException(ExceptionMessage.NOT_EXIST_POST_ID));
Notification notification = converter.toEntity(receiver, title, body, notificationTypeCode, relatedPost);
notificationRepository.save(notification);
Optional<Unread> unreadOpt = unreadRepository.findByMemberId(receiverId);
if (unreadOpt.isPresent()) {
unreadOpt.get().addCount();
} else {
unreadRepository.save(new Unread(receiver, 1));
}
}
@Transactional(readOnly = true)
public Page<NotificationResponse> findAllByMember(Pageable pageable, long receiverId) {
Page<Notification> notiPage = notificationRepository.findAllByReceiverId(pageable, receiverId);
return notiPage.map(n -> converter.toNotificationResponse(n));
}
@Transactional
public void toggleReadStatus(long notificationId, long receiverId) { // 읽음 처리
Notification notification = notificationRepository.findById(notificationId)
.orElseThrow(() -> new NotFoundException(ExceptionMessage.BAD_REQUEST));
notification.validateMemberOrElseThrow(receiverId);
notification.updateIsRead(true);
Unread unread = unreadRepository.findByMemberId(receiverId)
.orElseThrow(() -> new NotFoundException(ExceptionMessage.MEMBER_NOT_FOUND));
unread.substractCount();
}
@Transactional(readOnly = true)
public int getUnreadCount(long currentMemberId) {
Optional<Unread> unreadOpt = unreadRepository.findByMemberId(currentMemberId);
if (unreadOpt.isEmpty()) {
return 0;
}
return unreadOpt.get().getCount();
}
}
|
package com.dragon.wtudragondesign.activity;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.dragon.wtudragondesign.R;
import com.dragon.wtudragondesign.bean.Const;
import com.dragon.wtudragondesign.bean.CourierDetailEntity;
import com.dragon.wtudragondesign.bean.ResultEntity;
import com.dragon.wtudragondesign.retrofit.ApiService;
import com.dragon.wtudragondesign.retrofit.RetrofitClient;
import retrofit2.Call;
import retrofit2.Response;
public class UpdateRewardActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView mFabChat;
private Button mBtnUpdateReward;
private int userId = 0;
private String picString = "";
private TextView mTvPublishName;
private TextView mTvTitle;
private TextView mTvContent;
private TextView mTvCount;
private TextView mBtnDeleteReward;
private ProgressDialog proDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
userId = intent.getIntExtra("userId",0);
picString = intent.getStringExtra("pic");
setContentView(R.layout.activity_update_reward);
init();
getDetailPush();
}
/**
* 初始化控件
*/
private void init() {
Toolbar toolbar = findViewById(R.id.courier_detail_toolbar);
CollapsingToolbarLayout collapsingToolbar = findViewById(R.id.collapsing_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
collapsingToolbar.setTitle("悬赏详情");
collapsingToolbar.setCollapsedTitleGravity(Gravity.CENTER_VERTICAL);
ImageView bg = findViewById(R.id.courier_detail_background);
if (TextUtils.isEmpty(picString))
Glide.with(this).load(R.mipmap.ti).into(bg);
else
Glide.with(this).load(Const.BASE_URL+picString).into(bg);
//悬浮按钮
mFabChat = findViewById(R.id.fab_photo);
mFabChat.setOnClickListener(this);
mBtnUpdateReward = findViewById(R.id.btn_update_reward);
mBtnUpdateReward.setOnClickListener(this);
mTvPublishName = findViewById(R.id.tv_publish_name);
mTvTitle = findViewById(R.id.tv_detail_title);
mTvContent = findViewById(R.id.tv_detail_content);
mTvCount = findViewById(R.id.tv_reward_count);
mBtnDeleteReward = findViewById(R.id.btn_delete_reward);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressLint("ResourceAsColor")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fab_photo:
Intent intent = new Intent(this, UserDataActivity.class);
startActivity(intent);
break;
case R.id.btn_update_reward:
//Toast.makeText(this,"求别点",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
// 获取悬赏数据详情
private void getDetailPush() {
showProgressDialog();
ApiService api = RetrofitClient.getInstance(this).Api();
Call<ResultEntity> call = api.publishDetail(userId);
call.enqueue(new retrofit2.Callback<ResultEntity>() {
@Override
public void onResponse(Call<ResultEntity> call,
Response<ResultEntity> response) {
if (response.body() == null) {
return;
}
ResultEntity result = response.body();
int res = result.getCode();
if (res == 1) {// 请求成功
hideProgressDialog();
CourierDetailEntity courierDetailEntity = JSON.parseObject(result.getData().toString(),CourierDetailEntity.class);
if (courierDetailEntity != null)
setData(courierDetailEntity);
else
Toast.makeText(UpdateRewardActivity.this,""+result.getMsg(),Toast.LENGTH_SHORT).show();
} else {
hideProgressDialog();
Toast.makeText(UpdateRewardActivity.this,""+result.getMsg(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResultEntity> arg0, Throwable arg1) {
hideProgressDialog();
}
});
}
private void setData(CourierDetailEntity courierDetailEntity){
mTvPublishName.setText(courierDetailEntity.getPublisherUserName());
mTvTitle.setText(courierDetailEntity.getTitle());
mTvContent.setText(courierDetailEntity.getContent());
mTvCount.setText(""+courierDetailEntity.getAmount());
}
//展示加载对话框
private void showProgressDialog() {
proDialog = android.app.ProgressDialog.show(UpdateRewardActivity.this, "", "正在加载");
proDialog.setCanceledOnTouchOutside(true);
}
private void hideProgressDialog() {
if (proDialog != null)
proDialog.dismiss();
}
}
|
package opt.web.admin;
import opt.web.admin.users.Users;
public class Add {
public static final String widget =
"<fieldset>\n"
+ "<legend>Add User</legend>\n"
+ " <form action='/addUser'>\n"
+ " <label for='adduid'>Username:</label> "
+ " <input type='text' id='adduid'> "
+ " <input type='checkbox' id='addadm' value='admin'>"
+ " <label for='addadm'>Admin</label><br>"
+ " <label for='addpwd'>Password:</label> "
+ " <input type='text' id='addpwd''>"
+ " <input type='button' id='add' onclick='addUser()' value='Add User'>\n"
+ " </form>"
+ "</fieldset>\n"
+"<script>"
+ "function addUser() {"
+ "var request = '/addUser'"
+ "+ '?'+document.getElementById('adduid').value"
+ "+ '&'+document.getElementById('addpwd').value"
+ "+ '&'+document.getElementById('addadm').checked;"
+ "document.cookie=\"param=\"+document.getElementById('addpwd').value;"
+ "var xhttp = new XMLHttpRequest();"
+ "xhttp.onreadystatechange = function() {"
+ "if (this.readyState == 4 && this.status == 200) {"
+ "document.getElementById('output').innerHTML = this.responseText;"
+ "}"
+ "};"
+ "xhttp.open('GET', request, true);"
+ "xhttp.send();"
+ "}"
+ "</script><br>\n";
public static String operation( String[] params ) {
//Audit.log( "adduser" );
return "<strong>Add User</strong><p>"
+ (Users.addUser(
params[ 0 ],
params[ 1 ],
params[ 2 ].equals( "true" )
) ?
"OK: " +(params[ 2 ].equals( "true" )?"admin":"user")+" "+ params[ 0 ] +" added" :
"Sorry: Username "+ params[ 0 ] +" already exists")
+ "</p>";
} }
|
/*
* Units of Measurement Reference Implementation
* Copyright (c) 2005-2022, Jean-Marie Dautelle, Werner Keil, Otavio Santana.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of JSR-385, Indriya nor the names of their contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tech.units.indriya.function;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.measure.MeasurementException;
import javax.measure.Quantity;
import javax.measure.Quantity.Scale;
import javax.measure.Unit;
import javax.measure.UnitConverter;
import tech.units.indriya.internal.function.Calculator;
import tech.units.indriya.internal.function.radix.MixedRadixSupport;
import tech.units.indriya.internal.function.radix.Radix;
import tech.units.indriya.quantity.CompoundQuantity;
import tech.units.indriya.quantity.MixedQuantity;
import tech.units.indriya.quantity.Quantities;
/**
* Immutable class that represents mixed-radix units (like "hour:min:sec" or
* "ft, in")
*
*
* @author Andi Huber
* @author Werner Keil
* @version 2.2, Feb 25, 2021
* @since 2.0
* @see <a href="https://en.wikipedia.org/wiki/Mixed_radix">Wikipedia: Mixed
* radix</a>
* @see <a href=
* "https://reference.wolfram.com/language/ref/MixedUnit.html">Wolfram
* Language & System: MixedUnit</a>
* @see <a href="https://en.wikipedia.org/wiki/Metrication">Wikipedia:
* Metrication</a>
* @see MixedQuantity
*/
public final class MixedRadix<Q extends Quantity<Q>> {
// -- PRIVATE FIELDS
@Override
public String toString() {
return "MixedRadix [units=" + mixedRadixUnits + "]";
}
private final PrimaryUnitPickState pickState;
private final Unit<Q> primaryUnit;
private final List<Unit<Q>> mixedRadixUnits;
private final MixedRadixSupport mixedRadixSupport;
// -- PRIMARY UNIT PICK CONVENTION
public static enum PrimaryUnitPick {
LEADING_UNIT, TRAILING_UNIT
}
public static final PrimaryUnitPick PRIMARY_UNIT_PICK_DEFAULT = PrimaryUnitPick.TRAILING_UNIT;
public static PrimaryUnitPick PRIMARY_UNIT_PICK = PRIMARY_UNIT_PICK_DEFAULT;
// -- FACTORIES
public static <X extends Quantity<X>> MixedRadix<X> of(Unit<X> leadingUnit) {
Objects.requireNonNull(leadingUnit);
return new MixedRadix<>(PrimaryUnitPickState.pickByConvention(), Collections.singletonList(leadingUnit));
}
@SafeVarargs
public static <X extends Quantity<X>> MixedRadix<X> of(Unit<X>... units) {
if (units == null || units.length < 1) {
throw new IllegalArgumentException("at least the leading unit is required");
}
return of(Arrays.asList(units));
}
public static <X extends Quantity<X>> MixedRadix<X> of(Collection<Unit<X>> units) {
if (units == null || units.size() < 1) {
throw new IllegalArgumentException("at least the leading unit is required");
}
MixedRadix<X> mixedRadix = null;
for (Unit<X> unit : units) {
mixedRadix = mixedRadix == null ? of(unit) : mixedRadix.mix(unit);
}
return mixedRadix;
}
public static <X extends Quantity<X>> MixedRadix<X> ofPrimary(Unit<X> primaryUnit) {
Objects.requireNonNull(primaryUnit);
return new MixedRadix<>(PrimaryUnitPickState.pickLeading(), Collections.singletonList(primaryUnit));
}
public MixedRadix<Q> mix(Unit<Q> mixedRadixUnit) {
Objects.requireNonNull(mixedRadixUnit);
return append(pickState, mixedRadixUnit); // pickState is immutable, so reuse
}
MixedRadix<Q> mixPrimary(Unit<Q> mixedRadixUnit) {
pickState.assertNotExplicitlyPicked();
Objects.requireNonNull(mixedRadixUnit);
return append(PrimaryUnitPickState.pickByExplicitIndex(getUnitCount()), mixedRadixUnit);
}
// -- GETTERS
public Unit<Q> getPrimaryUnit() {
return primaryUnit;
}
private Unit<Q> getTrailingUnit() {
return mixedRadixUnits.get(mixedRadixUnits.size() - 1);
}
public List<Unit<Q>> getUnits() {
return Collections.unmodifiableList(mixedRadixUnits);
}
private int getUnitCount() {
return mixedRadixUnits.size();
}
// -- QUANTITY FACTORY
/**
* Creates a {@link Quantity} from given {@code values} and {@code scale}.
* @param values - numbers corresponding to the radices in most significant first order,
* allowed to be of shorter length than the total count of radices of this {@code MixedRadix} instance
* @param scale - the {@link Scale} to be used for the returned {@link Quantity}
*/
public Quantity<Q> createQuantity(final Number[] values, final Scale scale) {
Objects.requireNonNull(scale);
guardAgainstIllegalNumbersArgument(values);
Number sum = mixedRadixSupport.sumMostSignificant(values);
return Quantities.getQuantity(sum, getTrailingUnit(), scale).to(getPrimaryUnit());
}
public Quantity<Q> createQuantity(Number... values) {
return createQuantity(values, Scale.ABSOLUTE);
}
/**
* Creates a {@link MixedQuantity} from given {@code values} and {@code scale}.
* <p>
* Note: Not every {@code MixedQuantity} can be represented by a {@code MixedRadix}.
* {@code MixedRadix} strictly requires its coefficients to be in decreasing order of significance,
* while a {@code MixedQuantity} in principle does not.
*
* @param values - numbers corresponding to the radix coefficients in most significant first order,
* allowed to be of shorter length than the total count of radix coefficients of this
* {@code MixedRadix} instance
* @param scale - the {@link Scale} to be used for the elements of the returned {@link MixedQuantity}
*/
public MixedQuantity<Q> createMixedQuantity(final Number[] values, final Scale scale) {
Objects.requireNonNull(scale);
guardAgainstIllegalNumbersArgument(values);
List<Quantity<Q>> quantities = new ArrayList<>();
for (int i = 0; i < values.length; i++) {
quantities.add(Quantities.getQuantity(values[i], mixedRadixUnits.get(i), scale));
}
return MixedQuantity.of(quantities);
}
public MixedQuantity<Q> createMixedQuantity(Number... values) {
return createMixedQuantity(values, Scale.ABSOLUTE);
}
/**
* Creates a {@link CompoundQuantity} from given {@code values} and {@code scale}.
* <p>
* Note: Not every {@code CompoundQuantity} can be represented by a {@code MixedRadix}.
* {@code MixedRadix} strictly requires its coefficients to be in decreasing order of significance,
* while a {@code CompoundQuantity} in principle does not.
*
* @param values - numbers corresponding to the radix coefficients in most significant first order,
* allowed to be of shorter length than the total count of radix coefficients of this
* {@code MixedRadix} instance
* @param scale - the {@link Scale} to be used for the elements of the returned {@link CompoundQuantity}
* @deprecated use #getMixedQuantity
*/
public CompoundQuantity<Q> createCompoundQuantity(final Number[] values, final Scale scale) {
Objects.requireNonNull(scale);
guardAgainstIllegalNumbersArgument(values);
List<Quantity<Q>> quantities = new ArrayList<>();
for (int i = 0; i < values.length; i++) {
quantities.add(Quantities.getQuantity(values[i], mixedRadixUnits.get(i), scale));
}
return CompoundQuantity.of(quantities);
}
@Deprecated
public CompoundQuantity<Q> createCompoundQuantity(Number... values) {
return createCompoundQuantity(values, Scale.ABSOLUTE);
}
// -- VALUE EXTRACTION
public Number[] extractValues(Quantity<Q> quantity) {
Objects.requireNonNull(quantity);
final Number[] target = new Number[mixedRadixUnits.size()];
return extractValuesInto(quantity, target);
}
public Number[] extractValuesInto(Quantity<Q> quantity, Number[] target) {
Objects.requireNonNull(quantity);
Objects.requireNonNull(target);
visitQuantity(quantity, target.length, (index, unit, value) -> {
target[index] = value;
});
return target;
}
// -- THE VISITOR
@FunctionalInterface
private static interface Visitor<Q extends Quantity<Q>> {
void accept(int index, Unit<Q> unit, Number value);
}
// -- IMPLEMENTATION DETAILS
private void guardAgainstIllegalNumbersArgument(Number[] values) {
if (values == null || values.length < 1) {
throw new IllegalArgumentException("at least the leading unit's number is required");
}
int totalValuesGiven = values.length;
int totalValuesAllowed = mixedRadixUnits.size();
if (totalValuesGiven > totalValuesAllowed) {
String message = String.format(
"number of values given <%d> exceeds the number of mixed-radix units available <%d>",
totalValuesGiven, totalValuesAllowed);
throw new IllegalArgumentException(message);
}
}
void visitQuantity(Quantity<Q> quantity, int maxPartsToVisit, Visitor<Q> partVisitor) {
final int partsToVisitCount = Math.min(maxPartsToVisit, getUnitCount());
// corner case (partsToVisitCount == 0)
if (partsToVisitCount == 0) {
return;
}
// for partsToVisitCount >= 1
final Number value_inTrailingUnits = quantity.to(getTrailingUnit()).getValue();
final List<Number> extractedValues = new ArrayList<>(getUnitCount());
mixedRadixSupport.visitRadixNumbers(value_inTrailingUnits, extractedValues::add);
for (int i = 0; i < partsToVisitCount; ++i) {
int invertedIndex = getUnitCount() - 1 - i;
partVisitor.accept(i, mixedRadixUnits.get(i), extractedValues.get(invertedIndex));
}
}
/**
*
* @param primaryUnitIndex - if negative, the index is relative to the number of
* units
* @param mixedRadixUnits
*/
private MixedRadix(PrimaryUnitPickState pickState, final List<Unit<Q>> mixedRadixUnits) {
this.pickState = pickState;
this.mixedRadixUnits = mixedRadixUnits;
this.primaryUnit = mixedRadixUnits.get(pickState.nonNegativePrimaryUnitIndex(getUnitCount()));
final Radix[] radices = new Radix[getUnitCount() - 1];
for (int i = 0; i < radices.length; ++i) {
Unit<Q> higher = mixedRadixUnits.get(i);
Unit<Q> lesser = mixedRadixUnits.get(i + 1);
radices[i] = toRadix(higher.getConverterTo(lesser));
}
this.mixedRadixSupport = new MixedRadixSupport(radices);
}
private Radix toRadix(UnitConverter converter) {
return Radix.ofMultiplyConverter(converter);
}
private MixedRadix<Q> append(PrimaryUnitPickState state, Unit<Q> mixedRadixUnit) {
Unit<Q> tail = getTrailingUnit();
assertDecreasingOrderOfSignificanceAndLinearity(tail, mixedRadixUnit);
final List<Unit<Q>> mixedRadixUnits = new ArrayList<>(this.mixedRadixUnits);
mixedRadixUnits.add(mixedRadixUnit);
return new MixedRadix<>(state, mixedRadixUnits);
}
private void assertDecreasingOrderOfSignificanceAndLinearity(Unit<Q> tail, Unit<Q> appended) {
final UnitConverter converter = appended.getConverterTo(tail);
if (!converter.isLinear()) {
String message = String.format("the appended mixed-radix unit <%s> " + "must be linear",
appended.getClass());
throw new IllegalArgumentException(message);
}
final Number factor = tail.getConverterTo(appended).convert(1);
if (Calculator.of(factor).abs().isLessThanOne()) {
String message = String.format("the appended mixed-radix unit <%s> " + "must be of lesser significance "
+ "than the one it is appended to: <%s>", appended.getClass(), tail.getClass());
throw new MeasurementException(message);
}
}
private static class PrimaryUnitPickState {
private final static int LEADING_IS_PRIMARY_UNIT = 0;
private final static int TRAILING_IS_PRIMARY_UNIT = -1;
private final boolean explicitlyPicked;
private final int pickedIndex;
private static PrimaryUnitPickState pickByConvention() {
final int pickedIndex_byConvention;
switch (PRIMARY_UNIT_PICK) {
case LEADING_UNIT:
pickedIndex_byConvention = LEADING_IS_PRIMARY_UNIT;
break;
case TRAILING_UNIT:
pickedIndex_byConvention = TRAILING_IS_PRIMARY_UNIT;
break;
default:
throw new MeasurementException(
String.format("internal error: unmatched switch case <%s>", PRIMARY_UNIT_PICK));
}
return new PrimaryUnitPickState(false, pickedIndex_byConvention);
}
private void assertNotExplicitlyPicked() {
if (explicitlyPicked) {
throw new IllegalStateException("a primary unit was already picked");
}
}
private static PrimaryUnitPickState pickByExplicitIndex(int explicitIndex) {
return new PrimaryUnitPickState(true, explicitIndex);
}
private static PrimaryUnitPickState pickLeading() {
return new PrimaryUnitPickState(true, LEADING_IS_PRIMARY_UNIT);
}
private PrimaryUnitPickState(boolean explicitlyPicked, int pickedIndex) {
this.explicitlyPicked = explicitlyPicked;
this.pickedIndex = pickedIndex;
}
private int nonNegativePrimaryUnitIndex(int unitCount) {
return pickedIndex < 0 ? unitCount + pickedIndex : pickedIndex;
}
}
}
|
/*
* Copyright (c) 2021 The lambda4j 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.lambda4j.function.tri.conversion;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.function.IntToDoubleFunction;
import java.util.function.IntToLongFunction;
import java.util.function.IntUnaryOperator;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Triple;
import org.lambda4j.Lambda;
import org.lambda4j.consumer.tri.TriShortConsumer;
import org.lambda4j.function.bi.conversion.BiShortToIntFunction;
import org.lambda4j.function.conversion.BooleanToShortFunction;
import org.lambda4j.function.conversion.ByteToShortFunction;
import org.lambda4j.function.conversion.CharToShortFunction;
import org.lambda4j.function.conversion.DoubleToShortFunction;
import org.lambda4j.function.conversion.FloatToShortFunction;
import org.lambda4j.function.conversion.IntToByteFunction;
import org.lambda4j.function.conversion.IntToCharFunction;
import org.lambda4j.function.conversion.IntToFloatFunction;
import org.lambda4j.function.conversion.IntToShortFunction;
import org.lambda4j.function.conversion.LongToShortFunction;
import org.lambda4j.function.conversion.ShortToIntFunction;
import org.lambda4j.function.to.ToShortFunction;
import org.lambda4j.function.tri.TriFunction;
import org.lambda4j.function.tri.TriShortFunction;
import org.lambda4j.function.tri.to.ToIntTriFunction;
import org.lambda4j.operator.ternary.IntTernaryOperator;
import org.lambda4j.operator.ternary.ShortTernaryOperator;
import org.lambda4j.operator.unary.ShortUnaryOperator;
import org.lambda4j.predicate.tri.TriShortPredicate;
/**
* Represents an operation that accepts three {@code short}-valued input arguments and produces a {@code int}-valued
* result. This is a primitive specialization of {@link TriFunction}.
* <p>
* This is a {@link FunctionalInterface} whose functional method is {@link #applyAsInt(short, short, short)}.
*
* @see TriFunction
*/
@SuppressWarnings("unused")
@FunctionalInterface
public interface TriShortToIntFunction extends Lambda {
/**
* Constructs a {@link TriShortToIntFunction} based on a lambda expression or a method reference. Thereby the given
* lambda expression or method reference is returned on an as-is basis to implicitly transform it to the desired
* type. With this method, it is possible to ensure that correct type is used from lambda expression or method
* reference.
*
* @param expression A lambda expression or (typically) a method reference, e.g. {@code this::method}
* @return A {@code TriShortToIntFunction} from given lambda expression or method reference.
* @implNote This implementation allows the given argument to be {@code null}, but only if {@code null} given,
* {@code null} will be returned.
* @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax">Lambda
* Expression</a>
* @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">Method Reference</a>
*/
@CheckForNull
@Nullable
static TriShortToIntFunction of(@Nullable TriShortToIntFunction expression) {
return expression;
}
/**
* Calls the given {@link TriShortToIntFunction} with the given arguments and returns its result.
*
* @param function The function to be called
* @param value1 The first argument to the function
* @param value2 The second argument to the function
* @param value3 The third argument to the function
* @return The result from the given {@code TriShortToIntFunction}.
* @throws NullPointerException If given argument is {@code null}
*/
static int call(@Nonnull TriShortToIntFunction function, short value1, short value2, short value3) {
Objects.requireNonNull(function);
return function.applyAsInt(value1, value2, value3);
}
/**
* Creates a {@link TriShortToIntFunction} which uses the {@code first} parameter of this one as argument for the
* given {@link ShortToIntFunction}.
*
* @param function The function which accepts the {@code first} parameter of this one
* @return Creates a {@code TriShortToIntFunction} which uses the {@code first} parameter of this one as argument
* for the given {@code ShortToIntFunction}.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
static TriShortToIntFunction onlyFirst(@Nonnull ShortToIntFunction function) {
Objects.requireNonNull(function);
return (value1, value2, value3) -> function.applyAsInt(value1);
}
/**
* Creates a {@link TriShortToIntFunction} which uses the {@code second} parameter of this one as argument for the
* given {@link ShortToIntFunction}.
*
* @param function The function which accepts the {@code second} parameter of this one
* @return Creates a {@code TriShortToIntFunction} which uses the {@code second} parameter of this one as argument
* for the given {@code ShortToIntFunction}.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
static TriShortToIntFunction onlySecond(@Nonnull ShortToIntFunction function) {
Objects.requireNonNull(function);
return (value1, value2, value3) -> function.applyAsInt(value2);
}
/**
* Creates a {@link TriShortToIntFunction} which uses the {@code third} parameter of this one as argument for the
* given {@link ShortToIntFunction}.
*
* @param function The function which accepts the {@code third} parameter of this one
* @return Creates a {@code TriShortToIntFunction} which uses the {@code third} parameter of this one as argument
* for the given {@code ShortToIntFunction}.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
static TriShortToIntFunction onlyThird(@Nonnull ShortToIntFunction function) {
Objects.requireNonNull(function);
return (value1, value2, value3) -> function.applyAsInt(value3);
}
/**
* Creates a {@link TriShortToIntFunction} which always returns a given value.
*
* @param ret The return value for the constant
* @return A {@code TriShortToIntFunction} which always returns a given value.
*/
@Nonnull
static TriShortToIntFunction constant(int ret) {
return (value1, value2, value3) -> ret;
}
/**
* Applies this function to the given arguments.
*
* @param value1 The first argument to the function
* @param value2 The second argument to the function
* @param value3 The third argument to the function
* @return The return value from the function, which is its result.
*/
int applyAsInt(short value1, short value2, short value3);
/**
* Applies this function partially to some arguments of this one, producing a {@link BiShortToIntFunction} as
* result.
*
* @param value1 The first argument to this function used to partially apply this function
* @return A {@code BiShortToIntFunction} that represents this function partially applied the some arguments.
*/
@Nonnull
default BiShortToIntFunction applyAsIntPartially(short value1) {
return (value2, value3) -> applyAsInt(value1, value2, value3);
}
/**
* Applies this function partially to some arguments of this one, producing a {@link ShortToIntFunction} as result.
*
* @param value1 The first argument to this function used to partially apply this function
* @param value2 The second argument to this function used to partially apply this function
* @return A {@code ShortToIntFunction} that represents this function partially applied the some arguments.
*/
@Nonnull
default ShortToIntFunction applyAsIntPartially(short value1, short value2) {
return value3 -> applyAsInt(value1, value2, value3);
}
/**
* Returns the number of arguments for this function.
*
* @return The number of arguments for this function.
* @implSpec The default implementation always returns {@code 3}.
*/
@Nonnegative
default int arity() {
return 3;
}
/**
* Returns a composed {@link ToIntTriFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation.
*
* @param <A> The type of the argument to the first given function, and of composed function
* @param <B> The type of the argument to the second given function, and of composed function
* @param <C> The type of the argument to the third given function, and of composed function
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code ToIntTriFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle every type.
*/
@Nonnull
default <A, B, C> ToIntTriFunction<A, B, C> compose(@Nonnull ToShortFunction<? super A> before1,
@Nonnull ToShortFunction<? super B> before2, @Nonnull ToShortFunction<? super C> before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (a, b, c) -> applyAsInt(before1.applyAsShort(a), before2.applyAsShort(b), before3.applyAsShort(c));
}
/**
* Returns a composed {@link TriBooleanToIntFunction} that first applies the {@code before} functions to its input,
* and then applies this function to the result. If evaluation of either operation throws an exception, it is
* relayed to the caller of the composed operation. This method is just convenience, to provide the ability to
* execute an operation which accepts {@code boolean} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriBooleanToIntFunction} that first applies the {@code before} functions to its input,
* and then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
* boolean}.
*/
@Nonnull
default TriBooleanToIntFunction composeFromBoolean(@Nonnull BooleanToShortFunction before1,
@Nonnull BooleanToShortFunction before2, @Nonnull BooleanToShortFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> applyAsInt(before1.applyAsShort(value1), before2.applyAsShort(value2),
before3.applyAsShort(value3));
}
/**
* Returns a composed {@link TriByteToIntFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to execute an
* operation which accepts {@code byte} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriByteToIntFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
* byte}.
*/
@Nonnull
default TriByteToIntFunction composeFromByte(@Nonnull ByteToShortFunction before1,
@Nonnull ByteToShortFunction before2, @Nonnull ByteToShortFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> applyAsInt(before1.applyAsShort(value1), before2.applyAsShort(value2),
before3.applyAsShort(value3));
}
/**
* Returns a composed {@link TriCharToIntFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to execute an
* operation which accepts {@code char} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriCharToIntFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
* char}.
*/
@Nonnull
default TriCharToIntFunction composeFromChar(@Nonnull CharToShortFunction before1,
@Nonnull CharToShortFunction before2, @Nonnull CharToShortFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> applyAsInt(before1.applyAsShort(value1), before2.applyAsShort(value2),
before3.applyAsShort(value3));
}
/**
* Returns a composed {@link TriDoubleToIntFunction} that first applies the {@code before} functions to its input,
* and then applies this function to the result. If evaluation of either operation throws an exception, it is
* relayed to the caller of the composed operation. This method is just convenience, to provide the ability to
* execute an operation which accepts {@code double} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriDoubleToIntFunction} that first applies the {@code before} functions to its input,
* and then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
* double}.
*/
@Nonnull
default TriDoubleToIntFunction composeFromDouble(@Nonnull DoubleToShortFunction before1,
@Nonnull DoubleToShortFunction before2, @Nonnull DoubleToShortFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> applyAsInt(before1.applyAsShort(value1), before2.applyAsShort(value2),
before3.applyAsShort(value3));
}
/**
* Returns a composed {@link TriFloatToIntFunction} that first applies the {@code before} functions to its input,
* and then applies this function to the result. If evaluation of either operation throws an exception, it is
* relayed to the caller of the composed operation. This method is just convenience, to provide the ability to
* execute an operation which accepts {@code float} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriFloatToIntFunction} that first applies the {@code before} functions to its input,
* and then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
* float}.
*/
@Nonnull
default TriFloatToIntFunction composeFromFloat(@Nonnull FloatToShortFunction before1,
@Nonnull FloatToShortFunction before2, @Nonnull FloatToShortFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> applyAsInt(before1.applyAsShort(value1), before2.applyAsShort(value2),
before3.applyAsShort(value3));
}
/**
* Returns a composed {@link IntTernaryOperator} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to execute an
* operation which accepts {@code int} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code IntTernaryOperator} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
* int}.
*/
@Nonnull
default IntTernaryOperator composeFromInt(@Nonnull IntToShortFunction before1,
@Nonnull IntToShortFunction before2, @Nonnull IntToShortFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> applyAsInt(before1.applyAsShort(value1), before2.applyAsShort(value2),
before3.applyAsShort(value3));
}
/**
* Returns a composed {@link TriLongToIntFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to execute an
* operation which accepts {@code long} input, before this primitive function is executed.
*
* @param before1 The first function to apply before this function is applied
* @param before2 The second function to apply before this function is applied
* @param before3 The third function to apply before this function is applied
* @return A composed {@code TriLongToIntFunction} that first applies the {@code before} functions to its input, and
* then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
* long}.
*/
@Nonnull
default TriLongToIntFunction composeFromLong(@Nonnull LongToShortFunction before1,
@Nonnull LongToShortFunction before2, @Nonnull LongToShortFunction before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> applyAsInt(before1.applyAsShort(value1), before2.applyAsShort(value2),
before3.applyAsShort(value3));
}
/**
* Returns a composed {@link TriShortToIntFunction} that first applies the {@code before} operators to its input,
* and then applies this function to the result. If evaluation of either operation throws an exception, it is
* relayed to the caller of the composed operation. This method is just convenience, to provide the ability to
* execute an operation which accepts {@code short} input, before this primitive function is executed.
*
* @param before1 The first operator to apply before this function is applied
* @param before2 The second operator to apply before this function is applied
* @param before3 The third operator to apply before this function is applied
* @return A composed {@code TriShortToIntFunction} that first applies the {@code before} operators to its input,
* and then applies this function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to handle primitive values. In this case this is {@code
* short}.
*/
@Nonnull
default TriShortToIntFunction composeFromShort(@Nonnull ShortUnaryOperator before1,
@Nonnull ShortUnaryOperator before2, @Nonnull ShortUnaryOperator before3) {
Objects.requireNonNull(before1);
Objects.requireNonNull(before2);
Objects.requireNonNull(before3);
return (value1, value2, value3) -> applyAsInt(before1.applyAsShort(value1), before2.applyAsShort(value2),
before3.applyAsShort(value3));
}
/**
* Returns a composed {@link TriShortFunction} that first applies this function to its input, and then applies the
* {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to the
* caller of the composed operation.
*
* @param <S> The type of return value from the {@code after} function, and of the composed function
* @param after The function to apply after this function is applied
* @return A composed {@code TriShortFunction} that first applies this function to its input, and then applies the
* {@code after} function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return every type.
*/
@Nonnull
default <S> TriShortFunction<S> andThen(@Nonnull IntFunction<? extends S> after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.apply(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link TriShortPredicate} that first applies this function to its input, and then applies the
* {@code after} predicate to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to transform this
* primitive function to an operation returning {@code boolean}.
*
* @param after The predicate to apply after this function is applied
* @return A composed {@code TriShortPredicate} that first applies this function to its input, and then applies the
* {@code after} predicate to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return primitive values. In this case this is {@code
* boolean}.
*/
@Nonnull
default TriShortPredicate andThenToBoolean(@Nonnull IntPredicate after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.test(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link TriShortToByteFunction} that first applies this function to its input, and then applies
* the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to transform this
* primitive function to an operation returning {@code byte}.
*
* @param after The function to apply after this function is applied
* @return A composed {@code TriShortToByteFunction} that first applies this function to its input, and then applies
* the {@code after} function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return primitive values. In this case this is {@code
* byte}.
*/
@Nonnull
default TriShortToByteFunction andThenToByte(@Nonnull IntToByteFunction after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.applyAsByte(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link TriShortToCharFunction} that first applies this function to its input, and then applies
* the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to transform this
* primitive function to an operation returning {@code char}.
*
* @param after The function to apply after this function is applied
* @return A composed {@code TriShortToCharFunction} that first applies this function to its input, and then applies
* the {@code after} function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return primitive values. In this case this is {@code
* char}.
*/
@Nonnull
default TriShortToCharFunction andThenToChar(@Nonnull IntToCharFunction after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.applyAsChar(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link TriShortToDoubleFunction} that first applies this function to its input, and then
* applies the {@code after} function to the result. If evaluation of either operation throws an exception, it is
* relayed to the caller of the composed operation. This method is just convenience, to provide the ability to
* transform this primitive function to an operation returning {@code double}.
*
* @param after The function to apply after this function is applied
* @return A composed {@code TriShortToDoubleFunction} that first applies this function to its input, and then
* applies the {@code after} function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return primitive values. In this case this is {@code
* double}.
*/
@Nonnull
default TriShortToDoubleFunction andThenToDouble(@Nonnull IntToDoubleFunction after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.applyAsDouble(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link TriShortToFloatFunction} that first applies this function to its input, and then
* applies the {@code after} function to the result. If evaluation of either operation throws an exception, it is
* relayed to the caller of the composed operation. This method is just convenience, to provide the ability to
* transform this primitive function to an operation returning {@code float}.
*
* @param after The function to apply after this function is applied
* @return A composed {@code TriShortToFloatFunction} that first applies this function to its input, and then
* applies the {@code after} function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return primitive values. In this case this is {@code
* float}.
*/
@Nonnull
default TriShortToFloatFunction andThenToFloat(@Nonnull IntToFloatFunction after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.applyAsFloat(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link TriShortToIntFunction} that first applies this function to its input, and then applies
* the {@code after} operator to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to transform this
* primitive function to an operation returning {@code int}.
*
* @param after The operator to apply after this function is applied
* @return A composed {@code TriShortToIntFunction} that first applies this function to its input, and then applies
* the {@code after} operator to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return primitive values. In this case this is {@code
* int}.
*/
@Nonnull
default TriShortToIntFunction andThenToInt(@Nonnull IntUnaryOperator after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.applyAsInt(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link TriShortToLongFunction} that first applies this function to its input, and then applies
* the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to transform this
* primitive function to an operation returning {@code long}.
*
* @param after The function to apply after this function is applied
* @return A composed {@code TriShortToLongFunction} that first applies this function to its input, and then applies
* the {@code after} function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return primitive values. In this case this is {@code
* long}.
*/
@Nonnull
default TriShortToLongFunction andThenToLong(@Nonnull IntToLongFunction after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.applyAsLong(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link ShortTernaryOperator} that first applies this function to its input, and then applies
* the {@code after} function to the result. If evaluation of either operation throws an exception, it is relayed to
* the caller of the composed operation. This method is just convenience, to provide the ability to transform this
* primitive function to an operation returning {@code short}.
*
* @param after The function to apply after this function is applied
* @return A composed {@code ShortTernaryOperator} that first applies this function to its input, and then applies
* the {@code after} function to the result.
* @throws NullPointerException If given argument is {@code null}
* @implSpec The input argument of this method is able to return primitive values. In this case this is {@code
* short}.
*/
@Nonnull
default ShortTernaryOperator andThenToShort(@Nonnull IntToShortFunction after) {
Objects.requireNonNull(after);
return (value1, value2, value3) -> after.applyAsShort(applyAsInt(value1, value2, value3));
}
/**
* Returns a composed {@link TriShortConsumer} that fist applies this function to its input, and then consumes the
* result using the given {@link IntConsumer}. If evaluation of either operation throws an exception, it is relayed
* to the caller of the composed operation.
*
* @param consumer The operation which consumes the result from this operation
* @return A composed {@code TriShortConsumer} that first applies this function to its input, and then consumes the
* result using the given {@code IntConsumer}.
* @throws NullPointerException If given argument is {@code null}
*/
@Nonnull
default TriShortConsumer consume(@Nonnull IntConsumer consumer) {
Objects.requireNonNull(consumer);
return (value1, value2, value3) -> consumer.accept(applyAsInt(value1, value2, value3));
}
/**
* Returns a reversed version of this function. This may be useful in recursive context.
*
* @return A reversed version of this function.
*/
@Nonnull
default TriShortToIntFunction reversed() {
return (value3, value2, value1) -> applyAsInt(value1, value2, value3);
}
/**
* Returns a memoized (caching) version of this {@link TriShortToIntFunction}. Whenever it is called, the mapping
* between the input parameters and the return value is preserved in a cache, making subsequent calls returning the
* memoized value instead of computing the return value again.
* <p>
* Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
* forever.
*
* @return A memoized (caching) version of this {@code TriShortToIntFunction}.
* @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
* resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
* @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
* thread-safe.
*/
@Nonnull
default TriShortToIntFunction memoized() {
if (isMemoized()) {
return this;
} else {
Map<Triple<Short, Short, Short>, Integer> cache = new ConcurrentHashMap<>();
return (TriShortToIntFunction & Memoized) (value1, value2, value3) -> {
return cache.computeIfAbsent(Triple.of(value1, value2, value3),
key -> applyAsInt(key.getLeft(), key.getMiddle(), key.getRight()));
};
}
}
/**
* Returns a composed {@link TriFunction} which represents this {@link TriShortToIntFunction}. Thereby the primitive
* input argument for this function is autoboxed. This method provides the possibility to use this {@code
* TriShortToIntFunction} with methods provided by the {@code JDK}.
*
* @return A composed {@code TriFunction} which represents this {@code TriShortToIntFunction}.
*/
@Nonnull
default TriFunction<Short, Short, Short, Integer> boxed() {
return this::applyAsInt;
}
}
|
package br.com.zup.mercadolivre.produto.detalheproduto;
import br.com.zup.mercadolivre.produto.Produto;
import br.com.zup.mercadolivre.produto.ProdutoRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class DetalheProdutoContoller {
private ProdutoRepository produtoRepository;
public DetalheProdutoContoller(ProdutoRepository produtoRepository) {
this.produtoRepository = produtoRepository;
}
@GetMapping("/produtos/{id}")
public ResponseEntity<DetalheProdutoResponse> detalharProduto(@PathVariable(name = "id") Long idProduto){
Optional<Produto> produtoEncontrado = produtoRepository.findById(idProduto);
if(produtoEncontrado.isEmpty()) {
return ResponseEntity.notFound().build();
}
DetalheProdutoResponse response = new DetalheProdutoResponse(produtoEncontrado.get());
return ResponseEntity.ok(response);
}
}
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.site_settings;
import static org.chromium.components.browser_ui.site_settings.WebsitePreferenceBridge.SITE_WILDCARD;
import android.util.Pair;
import androidx.test.filters.SmallTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.Callback;
import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.chrome.browser.browsing_data.BrowsingDataBridge;
import org.chromium.chrome.browser.browsing_data.BrowsingDataType;
import org.chromium.chrome.browser.browsing_data.TimePeriod;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.test.ChromeBrowserTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.components.browser_ui.site_settings.ChosenObjectInfo;
import org.chromium.components.browser_ui.site_settings.ContentSettingException;
import org.chromium.components.browser_ui.site_settings.LocalStorageInfo;
import org.chromium.components.browser_ui.site_settings.PermissionInfo;
import org.chromium.components.browser_ui.site_settings.SiteSettingsCategory;
import org.chromium.components.browser_ui.site_settings.StorageInfo;
import org.chromium.components.browser_ui.site_settings.Website;
import org.chromium.components.browser_ui.site_settings.WebsiteAddress;
import org.chromium.components.browser_ui.site_settings.WebsitePermissionsFetcher;
import org.chromium.components.browser_ui.site_settings.WebsitePreferenceBridge;
import org.chromium.components.browser_ui.site_settings.WebsitePreferenceBridgeJni;
import org.chromium.components.content_settings.ContentSettingValues;
import org.chromium.components.content_settings.ContentSettingsType;
import org.chromium.components.embedder_support.browser_context.BrowserContextHandle;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Tests for WebsitePermissionsFetcher.
*/
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE,
WebsitePermissionsFetcherTest.ENABLE_EXPERIMENTAL_WEB_PLATFORM_FEATURES,
WebsitePermissionsFetcherTest.ENABLE_WEB_BLUETOOTH_NEW_PERMISSIONS_BACKEND})
@Batch(Batch.PER_CLASS)
public class WebsitePermissionsFetcherTest {
@Rule
public final ChromeBrowserTestRule mBrowserTestRule = new ChromeBrowserTestRule();
/** Command line flag to enable experimental web platform features in tests. */
public static final String ENABLE_EXPERIMENTAL_WEB_PLATFORM_FEATURES =
"enable-experimental-web-platform-features";
/**
* Command line flag to enable the new Web Bluetooth permissions backend in
* tests.
*/
public static final String ENABLE_WEB_BLUETOOTH_NEW_PERMISSIONS_BACKEND =
"enable-features=WebBluetoothNewPermissionsBackend";
private static final BrowserContextHandle UNUSED_BROWSER_CONTEXT_HANDLE = null;
private static final String[] PERMISSION_URLS = {
"http://www.google.com/",
"http://www.youtube.com/",
"http://www.facebook.com/",
"http://www.baidu.com/",
"http://www.wikipedia.org/",
"http://www.yahoo.com/",
"http://www.google.co.in/",
"http://www.reddit.com/",
"http://www.qq.com/",
"http://www.taobao.com/",
"http://www.google.co.jp/",
"http://www.amazon.com/",
"http://www.twitter.com/",
"http://www.live.com/",
"http://www.instagram.com/",
"http://www.weibo.com/",
"http://www.google.de/",
"http://www.google.co.uk/",
"http://www.google.com.br/",
"http://www.google.fr/",
"http://www.google.ru/",
"http://www.linkedin.com/",
"http://www.google.com.hk/",
"http://www.yandex.ru/",
"http://www.google.it/",
"http://www.netflix.com/",
"http://www.yahoo.co.jp/",
"http://www.google.es/",
"http://www.t.co/",
"http://www.google.com.mx/",
"http://www.google.ca/",
"http://www.ebay.com/",
"http://www.alipay.com/",
"http://www.bing.com/",
"http://www.imgur.com/",
"http://www.twitch.tv/",
"http://www.msn.com/",
"http://www.apple.com/",
"http://www.aliexpress.com/",
"http://www.microsoft.com/",
"http://www.wordpress.com/",
"http://www.office.com/",
"http://www.mail.ru/",
"http://www.tumblr.com/",
"http://www.stackoverflow.com/",
"http://www.microsoftonline.com/",
"http://www.imdb.com/",
"http://www.github.com/",
"http://www.blogspot.com/",
"http://www.amazon.co.jp/",
"http://www.google.com.au/",
"http://www.google.com.tw/",
"http://www.google.com.tr/",
"http://www.paypal.com/",
"http://www.google.pl/",
"http://www.wikia.com/",
"http://www.pinterest.com/",
"http://www.whatsapp.com/",
"http://www.google.co.id/",
"http://www.espn.com/",
"http://www.adobe.com/",
"http://www.google.com.ar/",
"http://www.googleusercontent.com/",
"http://www.amazon.in/",
"http://www.dropbox.com/",
"http://www.amazon.de/",
"http://www.google.com.ua/",
"http://www.so.com/",
"http://www.google.com.pk/",
"http://www.cnn.com/",
"http://www.amazon.co.uk/",
"http://www.bbc.co.uk/",
"http://www.google.com.sa/",
"http://www.craigslist.org/",
"http://www.bbc.com/",
"http://www.google.co.th/",
"http://www.google.com.eg/",
"http://www.google.nl/",
"http://www.amazonaws.com/",
"http://www.soundcloud.com/",
"http://www.ask.com/",
"http://www.google.co.za/",
"http://www.booking.com/",
"http://www.nytimes.com/",
"http://www.google.co.ve/",
"http://www.google.co.kr/",
"http://www.quora.com/",
"http://www.mozilla.org/",
"http://www.dailymotion.com/",
"http://www.stackexchange.com/",
"http://www.salesforce.com/",
"http://www.detik.com/",
"http://www.blogger.com/",
"http://www.ebay.de/",
"http://www.vimeo.com/",
"http://www.theguardian.com/",
"http://www.tribunnews.com/",
"http://www.google.com.sg/",
"http://www.google.gr/",
"http://www.flipkart.com/",
"http://www.spotify.com/",
"http://www.slideshare.net/",
"http://www.chase.com/",
"http://www.google.com.ph/",
"http://www.ebay.co.uk/",
"http://www.google.se/",
"http://www.cnet.com/",
"http://www.google.be/",
"http://www.nih.gov/",
"http://www.google.cn/",
"http://www.steamcommunity.com/",
"http://www.mediafire.com/",
"http://www.xinhuanet.com/",
"http://www.google.az/",
"http://www.vice.com/",
"http://www.alibaba.com/",
"http://www.dailymail.co.uk/",
"http://www.google.com.co/",
"http://www.buzzfeed.com/",
"http://www.doubleclick.net/",
"http://www.google.com.ng/",
"http://www.google.co.ao/",
"http://www.google.at/",
"http://www.uol.com.br/",
"http://www.redd.it/",
"http://www.deviantart.com/",
"http://www.washingtonpost.com/",
"http://www.twimg.com/",
"http://www.w3schools.com/",
"http://www.godaddy.com/",
"http://www.wikihow.com/",
"http://www.etsy.com/",
"http://www.slack.com/",
"http://www.google.cz/",
"http://www.google.ch/",
"http://www.amazon.it/",
"http://www.steampowered.com/",
"http://www.google.com.vn/",
"http://www.walmart.com/",
"http://www.messenger.com/",
"http://www.discordapp.com/",
"http://www.google.cl/",
"http://www.amazon.fr/",
"http://www.yelp.com/",
"http://www.google.no/",
"http://www.google.pt/",
"http://www.google.ae/",
"http://www.weather.com/",
"http://www.mercadolivre.com.br/",
"http://www.google.ro/",
"http://www.bankofamerica.com/",
"http://www.blogspot.co.id/",
"http://www.trello.com/",
"http://www.gfycat.com/",
"http://www.ikea.com/",
"http://www.scribd.com/",
"http://www.china.com.cn/",
"http://www.forbes.com/",
"http://www.wellsfargo.com/",
"http://www.indiatimes.com/",
"http://www.cnblogs.com/",
"http://www.gamepedia.com/",
"http://www.outbrain.com/",
"http://www.9gag.com/",
"http://www.google.ie/",
"http://www.gearbest.com/",
"http://www.files.wordpress.com/",
"http://www.huffingtonpost.com/",
"http://www.speedtest.net/",
"http://www.google.dk/",
"http://www.google.fi/",
"http://www.wikimedia.org/",
"http://www.thesaurus.com/",
"http://www.livejournal.com/",
"http://www.nfl.com/",
"http://www.zillow.com/",
"http://www.foxnews.com/",
"http://www.researchgate.net/",
"http://www.amazon.cn/",
"http://www.google.hu/",
"http://www.google.co.il/",
"http://www.amazon.es/",
"http://www.wordreference.com/",
"http://www.blackboard.com/",
"http://www.google.dz/",
"http://www.tripadvisor.com/",
"http://www.shutterstock.com/",
"http://www.cloudfront.net/",
"http://www.aol.com/",
"http://www.weebly.com/",
"http://www.battle.net/",
"http://www.archive.org/",
};
private static class WebsitePermissionsWaiter
extends CallbackHelper implements WebsitePermissionsFetcher.WebsitePermissionsCallback {
@Override
public void onWebsitePermissionsAvailable(Collection<Website> sites) {
notifyCalled();
}
}
@After
public void tearDown() throws TimeoutException {
// Clean up permissions.
CallbackHelper helper = new CallbackHelper();
TestThreadUtils.runOnUiThreadBlocking(() -> {
BrowsingDataBridge.getInstance().clearBrowsingData(helper::notifyCalled,
new int[] {BrowsingDataType.SITE_SETTINGS}, TimePeriod.ALL_TIME);
});
helper.waitForCallback(0);
}
@Test
@SmallTest
public void testNullsCanBeHandled() {
// This is a smoke test to ensure that nulls do not cause crashes.
WebsitePermissionsFetcher.OriginAndEmbedder nullBoth =
new WebsitePermissionsFetcher.OriginAndEmbedder(null, null);
WebsitePermissionsFetcher.OriginAndEmbedder nullOrigin =
new WebsitePermissionsFetcher.OriginAndEmbedder(
WebsiteAddress.create("https://www.google.com"), null);
WebsitePermissionsFetcher.OriginAndEmbedder nullEmbedder =
new WebsitePermissionsFetcher.OriginAndEmbedder(
null, WebsiteAddress.create("https://www.google.com"));
HashMap<WebsitePermissionsFetcher.OriginAndEmbedder, String> map = new HashMap<>();
map.put(nullBoth, "nullBoth");
map.put(nullOrigin, "nullOrigin");
map.put(nullEmbedder, "nullEmbedder");
Assert.assertTrue(map.containsKey(nullBoth));
Assert.assertTrue(map.containsKey(nullOrigin));
Assert.assertTrue(map.containsKey(nullEmbedder));
Assert.assertEquals("nullBoth", map.get(nullBoth));
Assert.assertEquals("nullOrigin", map.get(nullOrigin));
Assert.assertEquals("nullEmbedder", map.get(nullEmbedder));
}
@Test
@SmallTest
@DisabledTest(message = "https://crbug.com/1085592")
public void testFetcherDoesNotTimeOutWithManyUrls() throws Exception {
final WebsitePermissionsWaiter waiter = new WebsitePermissionsWaiter();
// Set lots of permissions values.
TestThreadUtils.runOnUiThreadBlocking(() -> {
Profile profile = Profile.getLastUsedRegularProfile();
for (String url : PERMISSION_URLS) {
WebsitePreferenceBridgeJni.get().setSettingForOrigin(profile,
ContentSettingsType.GEOLOCATION, url, url, ContentSettingValues.BLOCK);
WebsitePreferenceBridgeJni.get().setSettingForOrigin(profile,
ContentSettingsType.MIDI_SYSEX, url, url, ContentSettingValues.ALLOW);
WebsitePreferenceBridgeJni.get().setSettingForOrigin(profile,
ContentSettingsType.PROTECTED_MEDIA_IDENTIFIER, url, url,
ContentSettingValues.BLOCK);
WebsitePreferenceBridgeJni.get().setSettingForOrigin(profile,
ContentSettingsType.NOTIFICATIONS, url, url, ContentSettingValues.ALLOW);
WebsitePreferenceBridgeJni.get().setSettingForOrigin(profile,
ContentSettingsType.MEDIASTREAM_MIC, url, url, ContentSettingValues.ALLOW);
WebsitePreferenceBridgeJni.get().setSettingForOrigin(profile,
ContentSettingsType.MEDIASTREAM_CAMERA, url, url,
ContentSettingValues.BLOCK);
}
// This should not time out. See crbug.com/732907.
WebsitePermissionsFetcher fetcher = new WebsitePermissionsFetcher(profile);
fetcher.fetchAllPreferences(waiter);
});
waiter.waitForCallback(0, 1, 1000L, TimeUnit.MILLISECONDS);
}
class FakeWebsitePreferenceBridge extends WebsitePreferenceBridge {
public List<PermissionInfo> mPermissionInfos;
public List<ContentSettingException> mContentSettingExceptions;
public List<ChosenObjectInfo> mChosenObjectInfos;
public HashMap<String, LocalStorageInfo> mLocalStorageInfoMap;
public HashMap<String, LocalStorageInfo> mImportantLocalStorageInfoMap;
public ArrayList<StorageInfo> mStorageInfos;
FakeWebsitePreferenceBridge() {
mPermissionInfos = new ArrayList<>();
mContentSettingExceptions = new ArrayList<>();
mChosenObjectInfos = new ArrayList<>();
mLocalStorageInfoMap = new HashMap<>();
mImportantLocalStorageInfoMap = new HashMap<>();
mStorageInfos = new ArrayList<>();
}
@Override
public List<PermissionInfo> getPermissionInfo(
BrowserContextHandle browserContextHandle, @ContentSettingsType int type) {
List<PermissionInfo> result = new ArrayList<>();
for (PermissionInfo info : mPermissionInfos) {
if (info.getContentSettingsType() == type) {
result.add(info);
}
}
return result;
}
@Override
public List<ContentSettingException> getContentSettingsExceptions(
BrowserContextHandle browserContextHandle,
@ContentSettingsType int contentSettingsType) {
List<ContentSettingException> result = new ArrayList<>();
for (ContentSettingException exception : mContentSettingExceptions) {
if (exception.getContentSettingType() == contentSettingsType) {
result.add(exception);
}
}
return result;
}
@Override
public void fetchLocalStorageInfo(BrowserContextHandle browserContextHandle,
Callback<HashMap> callback, boolean fetchImportant) {
if (fetchImportant) {
callback.onResult(mImportantLocalStorageInfoMap);
return;
}
callback.onResult(mLocalStorageInfoMap);
}
@Override
public void fetchStorageInfo(
BrowserContextHandle browserContextHandle, Callback<ArrayList> callback) {
callback.onResult(mStorageInfos);
}
@Override
public List<ChosenObjectInfo> getChosenObjectInfo(
BrowserContextHandle browserContextHandle, int contentSettingsType) {
List<ChosenObjectInfo> result = new ArrayList<>();
for (ChosenObjectInfo info : mChosenObjectInfos) {
if (info.getContentSettingsType() == contentSettingsType) {
result.add(info);
}
}
return result;
}
public void addPermissionInfo(PermissionInfo info) {
mPermissionInfos.add(info);
}
public void addContentSettingException(ContentSettingException exception) {
mContentSettingExceptions.add(exception);
}
public void resetContentSettingExceptions() {
mContentSettingExceptions.clear();
}
public void addLocalStorageInfoMapEntry(LocalStorageInfo info) {
if (info.isDomainImportant()) {
mImportantLocalStorageInfoMap.put(info.getOrigin(), info);
return;
}
mLocalStorageInfoMap.put(info.getOrigin(), info);
}
public void addStorageInfo(StorageInfo info) {
mStorageInfos.add(info);
}
public void addChosenObjectInfo(ChosenObjectInfo info) {
mChosenObjectInfos.add(info);
}
}
@Test
@SmallTest
public void testFetchAllPreferencesForSingleOrigin() {
WebsitePermissionsFetcher fetcher =
new WebsitePermissionsFetcher(UNUSED_BROWSER_CONTEXT_HANDLE);
FakeWebsitePreferenceBridge websitePreferenceBridge = new FakeWebsitePreferenceBridge();
fetcher.setWebsitePreferenceBridgeForTesting(websitePreferenceBridge);
String googleOrigin = "https://google.com";
websitePreferenceBridge.addPermissionInfo(
new PermissionInfo(ContentSettingsType.AR, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.IDLE_DETECTION, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.GEOLOCATION, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.MIDI_SYSEX, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(
new PermissionInfo(ContentSettingsType.PROTECTED_MEDIA_IDENTIFIER, googleOrigin,
SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(
new PermissionInfo(ContentSettingsType.NFC, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.NOTIFICATIONS, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.MEDIASTREAM_CAMERA, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.MEDIASTREAM_MIC, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.CLIPBOARD_READ_WRITE, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.SENSORS, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(
new PermissionInfo(ContentSettingsType.VR, googleOrigin, SITE_WILDCARD, false));
// Add content setting exception types.
String preferenceSource = "preference";
// If the ContentSettingsType.NUM_TYPES value changes *and* a new value has been exposed on
// Android, then please update this code block to include a test for your new type.
// Otherwise, just update count in the assert.
Assert.assertEquals(67, ContentSettingsType.NUM_TYPES);
websitePreferenceBridge.addContentSettingException(
new ContentSettingException(ContentSettingsType.COOKIES, googleOrigin,
ContentSettingValues.DEFAULT, preferenceSource));
websitePreferenceBridge.addContentSettingException(
new ContentSettingException(ContentSettingsType.POPUPS, googleOrigin,
ContentSettingValues.DEFAULT, preferenceSource));
websitePreferenceBridge.addContentSettingException(
new ContentSettingException(ContentSettingsType.ADS, googleOrigin,
ContentSettingValues.DEFAULT, preferenceSource));
websitePreferenceBridge.addContentSettingException(
new ContentSettingException(ContentSettingsType.JAVASCRIPT, googleOrigin,
ContentSettingValues.DEFAULT, preferenceSource));
websitePreferenceBridge.addContentSettingException(
new ContentSettingException(ContentSettingsType.SOUND, googleOrigin,
ContentSettingValues.DEFAULT, preferenceSource));
websitePreferenceBridge.addContentSettingException(
new ContentSettingException(ContentSettingsType.BACKGROUND_SYNC, googleOrigin,
ContentSettingValues.DEFAULT, preferenceSource));
websitePreferenceBridge.addContentSettingException(
new ContentSettingException(ContentSettingsType.AUTOMATIC_DOWNLOADS, googleOrigin,
ContentSettingValues.DEFAULT, preferenceSource));
websitePreferenceBridge.addContentSettingException(
new ContentSettingException(ContentSettingsType.INSECURE_PRIVATE_NETWORK,
googleOrigin, ContentSettingValues.DEFAULT, preferenceSource));
// Add storage info.
int storageSize = 256;
websitePreferenceBridge.addStorageInfo(new StorageInfo(googleOrigin, 0, storageSize));
// Add local storage info.
websitePreferenceBridge.addLocalStorageInfoMapEntry(
new LocalStorageInfo(googleOrigin, storageSize, false));
// Add chooser info types.
websitePreferenceBridge.addChosenObjectInfo(new ChosenObjectInfo(
ContentSettingsType.USB_CHOOSER_DATA, googleOrigin, "Gadget", "Object", false));
websitePreferenceBridge.addChosenObjectInfo(
new ChosenObjectInfo(ContentSettingsType.BLUETOOTH_CHOOSER_DATA, googleOrigin,
"Wireless", "Object", false));
fetcher.fetchAllPreferences((sites) -> {
Assert.assertEquals(1, sites.size());
Website site = sites.iterator().next();
Assert.assertTrue(site.getAddress().matches(googleOrigin));
// Check permission info types for |site|.
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.GEOLOCATION));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.IDLE_DETECTION));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.MIDI_SYSEX));
Assert.assertNotNull(
site.getPermissionInfo(ContentSettingsType.PROTECTED_MEDIA_IDENTIFIER));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.NOTIFICATIONS));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.MEDIASTREAM_CAMERA));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.MEDIASTREAM_MIC));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.CLIPBOARD_READ_WRITE));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.SENSORS));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.VR));
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.AR));
// Check content setting exception types.
Assert.assertEquals(Integer.valueOf(ContentSettingValues.DEFAULT),
site.getContentSetting(
UNUSED_BROWSER_CONTEXT_HANDLE, ContentSettingsType.COOKIES));
Assert.assertEquals(Integer.valueOf(ContentSettingValues.DEFAULT),
site.getContentSetting(
UNUSED_BROWSER_CONTEXT_HANDLE, ContentSettingsType.POPUPS));
Assert.assertEquals(Integer.valueOf(ContentSettingValues.DEFAULT),
site.getContentSetting(UNUSED_BROWSER_CONTEXT_HANDLE, ContentSettingsType.ADS));
Assert.assertEquals(Integer.valueOf(ContentSettingValues.DEFAULT),
site.getContentSetting(
UNUSED_BROWSER_CONTEXT_HANDLE, ContentSettingsType.JAVASCRIPT));
Assert.assertEquals(Integer.valueOf(ContentSettingValues.DEFAULT),
site.getContentSetting(
UNUSED_BROWSER_CONTEXT_HANDLE, ContentSettingsType.SOUND));
Assert.assertEquals(Integer.valueOf(ContentSettingValues.DEFAULT),
site.getContentSetting(
UNUSED_BROWSER_CONTEXT_HANDLE, ContentSettingsType.BACKGROUND_SYNC));
Assert.assertEquals(Integer.valueOf(ContentSettingValues.DEFAULT),
site.getContentSetting(UNUSED_BROWSER_CONTEXT_HANDLE,
ContentSettingsType.AUTOMATIC_DOWNLOADS));
// Check storage info.
ArrayList<StorageInfo> storageInfos = new ArrayList<>(site.getStorageInfo());
Assert.assertEquals(1, storageInfos.size());
StorageInfo storageInfo = storageInfos.get(0);
Assert.assertEquals(googleOrigin, storageInfo.getHost());
Assert.assertEquals(storageSize, storageInfo.getSize());
// Check local storage info.
LocalStorageInfo localStorageInfo = site.getLocalStorageInfo();
Assert.assertEquals(googleOrigin, localStorageInfo.getOrigin());
Assert.assertEquals(storageSize, localStorageInfo.getSize());
Assert.assertFalse(localStorageInfo.isDomainImportant());
// Check chooser info types.
ArrayList<ChosenObjectInfo> chosenObjectInfos =
new ArrayList<>(site.getChosenObjectInfo());
Assert.assertEquals(2, chosenObjectInfos.size());
Assert.assertEquals(ContentSettingsType.BLUETOOTH_CHOOSER_DATA,
chosenObjectInfos.get(0).getContentSettingsType());
Assert.assertEquals(ContentSettingsType.USB_CHOOSER_DATA,
chosenObjectInfos.get(1).getContentSettingsType());
});
}
@Test
@SmallTest
public void testFetchAllPreferencesForMultipleOrigins() {
WebsitePermissionsFetcher fetcher =
new WebsitePermissionsFetcher(UNUSED_BROWSER_CONTEXT_HANDLE);
FakeWebsitePreferenceBridge websitePreferenceBridge = new FakeWebsitePreferenceBridge();
fetcher.setWebsitePreferenceBridgeForTesting(websitePreferenceBridge);
String googleOrigin = "https://google.com";
String chromiumOrigin = "https://chromium.org";
String exampleOrigin = "https://example.com";
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.GEOLOCATION, googleOrigin, SITE_WILDCARD, false));
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.GEOLOCATION, chromiumOrigin, SITE_WILDCARD, false));
Website expectedGoogleWebsite =
new Website(WebsiteAddress.create(googleOrigin), WebsiteAddress.create(null));
Website expectedChromiumWebsite =
new Website(WebsiteAddress.create(chromiumOrigin), WebsiteAddress.create(null));
fetcher.fetchAllPreferences((sites) -> {
Assert.assertEquals(2, sites.size());
// The order of |sites| is unknown, so check if the array contains a geolocation
// permission for each of the sites.
ArrayList<Website> siteArray = new ArrayList<>(sites);
boolean containsGoogleOriginPermission = false;
boolean containsChromiumOriginPermission = false;
for (Website site : siteArray) {
if (site.compareByAddressTo(expectedGoogleWebsite) == 0) {
containsGoogleOriginPermission = true;
} else if (site.compareByAddressTo(expectedChromiumWebsite) == 0) {
containsChromiumOriginPermission = true;
}
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.GEOLOCATION));
}
Assert.assertTrue(containsGoogleOriginPermission);
Assert.assertTrue(containsChromiumOriginPermission);
});
websitePreferenceBridge.addPermissionInfo(new PermissionInfo(
ContentSettingsType.GEOLOCATION, exampleOrigin, SITE_WILDCARD, false));
Website expectedExampleWebsite =
new Website(WebsiteAddress.create(exampleOrigin), WebsiteAddress.create(null));
fetcher.fetchAllPreferences((sites) -> {
Assert.assertEquals(3, sites.size());
ArrayList<Website> siteArray = new ArrayList<>(sites);
boolean containsGoogleOriginPermission = false;
boolean containsChromiumOriginPermission = false;
boolean containsExampleOriginPermission = false;
for (Website site : siteArray) {
if (site.compareByAddressTo(expectedGoogleWebsite) == 0) {
containsGoogleOriginPermission = true;
} else if (site.compareByAddressTo(expectedChromiumWebsite) == 0) {
containsChromiumOriginPermission = true;
} else if (site.compareByAddressTo(expectedExampleWebsite) == 0) {
containsExampleOriginPermission = true;
}
Assert.assertNotNull(site.getPermissionInfo(ContentSettingsType.GEOLOCATION));
}
Assert.assertTrue(containsGoogleOriginPermission);
Assert.assertTrue(containsChromiumOriginPermission);
Assert.assertTrue(containsExampleOriginPermission);
});
}
public void assertContentSettingExceptionEquals(
ContentSettingException expected, ContentSettingException actual) {
Assert.assertEquals(expected.getSource(), actual.getSource());
Assert.assertEquals(expected.getPrimaryPattern(), actual.getPrimaryPattern());
Assert.assertEquals(expected.getSecondaryPattern(), actual.getSecondaryPattern());
Assert.assertEquals(expected.getContentSetting(), actual.getContentSetting());
}
@Test
@SmallTest
public void testFetchPreferencesForCategoryPermissionInfoTypes() {
WebsitePermissionsFetcher fetcher =
new WebsitePermissionsFetcher(UNUSED_BROWSER_CONTEXT_HANDLE);
FakeWebsitePreferenceBridge websitePreferenceBridge = new FakeWebsitePreferenceBridge();
fetcher.setWebsitePreferenceBridgeForTesting(websitePreferenceBridge);
String googleOrigin = "https://google.com";
// MIDI is excluded from this list because it does not have a top level category.
ArrayList<Integer> permissionInfoTypes = new ArrayList<>(
Arrays.asList(ContentSettingsType.AR, ContentSettingsType.MEDIASTREAM_CAMERA,
ContentSettingsType.CLIPBOARD_READ_WRITE, ContentSettingsType.GEOLOCATION,
ContentSettingsType.IDLE_DETECTION, ContentSettingsType.MEDIASTREAM_MIC,
ContentSettingsType.NFC, ContentSettingsType.NOTIFICATIONS,
ContentSettingsType.PROTECTED_MEDIA_IDENTIFIER, ContentSettingsType.SENSORS,
ContentSettingsType.VR));
for (@ContentSettingsType int type : permissionInfoTypes) {
PermissionInfo fakePermissionInfo =
new PermissionInfo(type, googleOrigin, SITE_WILDCARD, false);
websitePreferenceBridge.addPermissionInfo(fakePermissionInfo);
fetcher.fetchPreferencesForCategory(SiteSettingsCategory.createFromContentSettingsType(
UNUSED_BROWSER_CONTEXT_HANDLE, type),
(sites) -> {
Assert.assertEquals(1, sites.size());
Website site = sites.iterator().next();
Assert.assertNotNull(site.getPermissionInfo(type));
});
}
}
@Test
@SmallTest
public void testFetchPreferencesForCategoryContentSettingExceptionTypes() {
WebsitePermissionsFetcher fetcher =
new WebsitePermissionsFetcher(UNUSED_BROWSER_CONTEXT_HANDLE);
FakeWebsitePreferenceBridge websitePreferenceBridge = new FakeWebsitePreferenceBridge();
fetcher.setWebsitePreferenceBridgeForTesting(websitePreferenceBridge);
String googleOrigin = "https://google.com";
String preferenceSource = "preference";
ArrayList<Integer> contentSettingExceptionTypes = new ArrayList<>(
Arrays.asList(ContentSettingsType.ADS, ContentSettingsType.AUTOMATIC_DOWNLOADS,
ContentSettingsType.BACKGROUND_SYNC, ContentSettingsType.BLUETOOTH_SCANNING,
ContentSettingsType.COOKIES, ContentSettingsType.JAVASCRIPT,
ContentSettingsType.POPUPS, ContentSettingsType.SOUND));
for (@ContentSettingsType int type : contentSettingExceptionTypes) {
{
ContentSettingException fakeContentSettingException = new ContentSettingException(
type, googleOrigin, ContentSettingValues.DEFAULT, preferenceSource);
websitePreferenceBridge.addContentSettingException(fakeContentSettingException);
fetcher.fetchPreferencesForCategory(
SiteSettingsCategory.createFromContentSettingsType(
UNUSED_BROWSER_CONTEXT_HANDLE, type),
(sites) -> {
Assert.assertEquals(1, sites.size());
Website site = sites.iterator().next();
assertContentSettingExceptionEquals(fakeContentSettingException,
site.getContentSettingException(type));
});
}
// Make sure that the content setting value is updated.
{
ContentSettingException fakeContentSettingException = new ContentSettingException(
type, googleOrigin, ContentSettingValues.BLOCK, preferenceSource);
websitePreferenceBridge.addContentSettingException(fakeContentSettingException);
fetcher.fetchPreferencesForCategory(
SiteSettingsCategory.createFromContentSettingsType(
UNUSED_BROWSER_CONTEXT_HANDLE, type),
(sites) -> {
Assert.assertEquals(1, sites.size());
Website site = sites.iterator().next();
assertContentSettingExceptionEquals(fakeContentSettingException,
site.getContentSettingException(type));
});
}
}
}
@Test
@SmallTest
public void testFetchPreferencesForAdvancedCookieSettings() {
WebsitePermissionsFetcher fetcher =
new WebsitePermissionsFetcher(UNUSED_BROWSER_CONTEXT_HANDLE);
FakeWebsitePreferenceBridge websitePreferenceBridge = new FakeWebsitePreferenceBridge();
fetcher.setWebsitePreferenceBridgeForTesting(websitePreferenceBridge);
String mainSite = "https://a.com";
String thirdPartySite = "https://b.com";
String preferenceSource = "preference";
@ContentSettingsType
int contentSettingsType = ContentSettingsType.COOKIES;
// Test the advanced exception combinations of:
// b.com on a.com
// a.com on a.com
// * on a.com
ArrayList<Pair<String, String>> exceptions =
new ArrayList<>(Arrays.asList(new Pair<>(thirdPartySite, mainSite),
new Pair<>(mainSite, mainSite), new Pair<>(SITE_WILDCARD, mainSite)));
for (Pair<String, String> pair : exceptions) {
fetcher.resetContentSettingExceptions();
websitePreferenceBridge.resetContentSettingExceptions();
{
ContentSettingException fakeContentSettingException =
new ContentSettingException(contentSettingsType, pair.first, pair.second,
ContentSettingValues.DEFAULT, preferenceSource);
websitePreferenceBridge.addContentSettingException(fakeContentSettingException);
fetcher.fetchPreferencesForCategory(
SiteSettingsCategory.createFromContentSettingsType(
UNUSED_BROWSER_CONTEXT_HANDLE, contentSettingsType),
(sites) -> {
Assert.assertEquals(1, sites.size());
Website site = sites.iterator().next();
assertContentSettingExceptionEquals(fakeContentSettingException,
site.getContentSettingException(contentSettingsType));
});
}
// Make sure that the content setting value is updated.
{
ContentSettingException fakeContentSettingException =
new ContentSettingException(contentSettingsType, pair.first, pair.second,
ContentSettingValues.BLOCK, preferenceSource);
websitePreferenceBridge.addContentSettingException(fakeContentSettingException);
fetcher.fetchPreferencesForCategory(
SiteSettingsCategory.createFromContentSettingsType(
UNUSED_BROWSER_CONTEXT_HANDLE, contentSettingsType),
(sites) -> {
Assert.assertEquals(1, sites.size());
Website site = sites.iterator().next();
assertContentSettingExceptionEquals(fakeContentSettingException,
site.getContentSettingException(contentSettingsType));
});
}
}
}
@Test
@SmallTest
public void testFetchPreferencesForCategoryStorageInfo() {
WebsitePermissionsFetcher fetcher =
new WebsitePermissionsFetcher(UNUSED_BROWSER_CONTEXT_HANDLE);
FakeWebsitePreferenceBridge websitePreferenceBridge = new FakeWebsitePreferenceBridge();
fetcher.setWebsitePreferenceBridgeForTesting(websitePreferenceBridge);
String googleOrigin = "https://google.com";
String chromiumOrigin = "https://chromium.org";
int storageSize = 256;
StorageInfo fakeStorageInfo = new StorageInfo(googleOrigin, 0, storageSize);
LocalStorageInfo fakeLocalStorageInfo =
new LocalStorageInfo(googleOrigin, storageSize, false);
LocalStorageInfo fakeImportantLocalStorageInfo =
new LocalStorageInfo(chromiumOrigin, storageSize, true);
websitePreferenceBridge.addStorageInfo(fakeStorageInfo);
websitePreferenceBridge.addLocalStorageInfoMapEntry(fakeLocalStorageInfo);
websitePreferenceBridge.addLocalStorageInfoMapEntry(fakeImportantLocalStorageInfo);
fetcher.fetchPreferencesForCategory(
SiteSettingsCategory.createFromType(
UNUSED_BROWSER_CONTEXT_HANDLE, SiteSettingsCategory.Type.USE_STORAGE),
(sites) -> {
Assert.assertEquals(1, sites.size());
Website site = sites.iterator().next();
List<StorageInfo> storageInfos = site.getStorageInfo();
Assert.assertEquals(1, storageInfos.size());
StorageInfo storageInfo = storageInfos.get(0);
Assert.assertEquals(fakeStorageInfo.getSize(), storageInfo.getSize());
Assert.assertEquals(fakeStorageInfo.getHost(), storageInfo.getHost());
LocalStorageInfo localStorageInfo = site.getLocalStorageInfo();
Assert.assertFalse(localStorageInfo.isDomainImportant());
Assert.assertEquals(fakeLocalStorageInfo.getSize(), localStorageInfo.getSize());
Assert.assertEquals(
fakeLocalStorageInfo.getOrigin(), localStorageInfo.getOrigin());
});
// Test that the fetcher gets local storage info for important domains.
fetcher = new WebsitePermissionsFetcher(UNUSED_BROWSER_CONTEXT_HANDLE, true);
fetcher.setWebsitePreferenceBridgeForTesting(websitePreferenceBridge);
fetcher.fetchPreferencesForCategory(
SiteSettingsCategory.createFromType(
UNUSED_BROWSER_CONTEXT_HANDLE, SiteSettingsCategory.Type.USE_STORAGE),
(sites) -> {
Assert.assertEquals(2, sites.size());
for (Website site : sites) {
if (site.getAddress().matches(googleOrigin)) {
List<StorageInfo> storageInfos = site.getStorageInfo();
Assert.assertEquals(1, storageInfos.size());
StorageInfo storageInfo = storageInfos.get(0);
Assert.assertEquals(fakeStorageInfo.getSize(), storageInfo.getSize());
Assert.assertEquals(fakeStorageInfo.getHost(), storageInfo.getHost());
Assert.assertNull(site.getLocalStorageInfo());
} else if (site.getAddress().matches(chromiumOrigin)) {
List<StorageInfo> storageInfos = site.getStorageInfo();
Assert.assertEquals(0, storageInfos.size());
LocalStorageInfo localStorageInfo = site.getLocalStorageInfo();
Assert.assertTrue(localStorageInfo.isDomainImportant());
Assert.assertEquals(fakeImportantLocalStorageInfo.getSize(),
localStorageInfo.getSize());
Assert.assertEquals(fakeImportantLocalStorageInfo.getOrigin(),
localStorageInfo.getOrigin());
} else {
Assert.fail("The WebsitePermissionsFetcher should only return "
+ "Website objects for the granted origins.");
}
}
});
}
@Test
@SmallTest
public void testFetchPreferencesForCategoryChooserDataTypes() {
String googleOrigin = "https://google.com";
ArrayList<Integer> chooserDataTypes = new ArrayList<>(
Arrays.asList(SiteSettingsCategory.Type.USB, SiteSettingsCategory.Type.BLUETOOTH));
for (@SiteSettingsCategory.Type int type : chooserDataTypes) {
WebsitePermissionsFetcher fetcher =
new WebsitePermissionsFetcher(UNUSED_BROWSER_CONTEXT_HANDLE);
FakeWebsitePreferenceBridge websitePreferenceBridge = new FakeWebsitePreferenceBridge();
fetcher.setWebsitePreferenceBridgeForTesting(websitePreferenceBridge);
@ContentSettingsType
int chooserDataType = SiteSettingsCategory.objectChooserDataTypeFromGuard(
SiteSettingsCategory.contentSettingsType(type));
Assert.assertNotEquals(-1, chooserDataType);
ChosenObjectInfo fakeObjectInfo = new ChosenObjectInfo(
chooserDataType, googleOrigin, "Chosen Object", "SerializedObjectData", false);
websitePreferenceBridge.addChosenObjectInfo(fakeObjectInfo);
fetcher.fetchPreferencesForCategory(
SiteSettingsCategory.createFromType(UNUSED_BROWSER_CONTEXT_HANDLE, type),
(sites) -> {
Assert.assertEquals(1, sites.size());
List<ChosenObjectInfo> objectInfos =
new ArrayList<>(sites.iterator().next().getChosenObjectInfo());
Assert.assertEquals(1, objectInfos.size());
Assert.assertEquals(fakeObjectInfo, objectInfos.get(0));
});
}
}
}
|
package com.c4me.server.utils;
import lombok.AllArgsConstructor;
/**
* @Description: Domain object representing a student from students.csv
* @Author: Maciej Wlodek
* @CreateDate: 03-22-2020
*/
@AllArgsConstructor
public class StudentCSVRecord {
String userid;
String password;
String residence_state;
String high_school_name;
String high_school_city;
String high_school_state;
Double GPA;
Integer college_class;
String major_1;
String major_2;
Integer SAT_math;
Integer SAT_EBRW;
Integer ACT_English;
Integer ACT_math;
Integer ACT_reading;
Integer ACT_science;
Integer ACT_composite;
Integer SAT_literature;
Integer SAT_US_hist;
Integer SAT_world_hist;
Integer SAT_math_I;
Integer SAT_math_II;
Integer SAT_eco_bio;
Integer SAT_mol_bio;
Integer SAT_chemistry;
Integer SAT_physics;
Integer num_AP_passed;
}
|
/*
* 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 eu.linkedeodata.geotriples.utils;
class John_PairEntry<K,V> implements java.util.Map.Entry<K,V> {
K a;
V b;
@Override
public boolean equals(Object o) {
if (o != null && (o instanceof John_PairEntry<?,?>)) {
John_PairEntry<?,?> e = (John_PairEntry<?,?>) o;
return e.a.equals(a) && e.b.equals(b);
}
return false;
}
@Override
public K getKey() {
return a;
}
@Override
public V getValue() {
return b;
}
@Override
public int hashCode() {
return a.hashCode() ^ b.hashCode();
}
@Override
public V setValue(Object value) {
throw new UnsupportedOperationException();
}
John_PairEntry(K a, V b) {
this.a = a;
this.b = b;
}
}
|
/*
* Licensed to CRATE Technology GmbH ("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.sql.tree;
import com.google.common.base.Preconditions;
public class NotExpression
extends Expression {
private final Expression value;
public NotExpression(Expression value) {
Preconditions.checkNotNull(value, "value is null");
this.value = value;
}
public Expression getValue() {
return value;
}
@Override
public <R, C> R accept(AstVisitor<R, C> visitor, C context) {
return visitor.visitNotExpression(this, context);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NotExpression that = (NotExpression) o;
if (!value.equals(that.value)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return value.hashCode();
}
}
|
package edu.kit.exp.client.gui.screens.question.questionnaire;
import edu.kit.exp.client.gui.screens.question.QuestionItem;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
/**
* Created by tondaroder on 30.01.17.
*/
public abstract class QuestionnaireItem implements QuestionItem {
/** The question. */
private String question;
/** The base panel. */
protected JPanel basePanel;
/** answer to the question **/
private String answer;
/**
* This method gets the question.
*
* @return the question
*/
public String getQuestion() {
return question;
}
/**
* This method sets the question.
*
* @param question
* A String which contains the new question.
*/
public void setQuestion(String question) {
this.question = question;
}
/**
* This constructor instantiates a new quiz item by setting a question and
* creating a panel.
*
* @param question
* the question
*/
public QuestionnaireItem(String question) {
this.question = question;
basePanel = new JPanel();
basePanel.setBackground(Color.WHITE);
basePanel.setBorder(new EmptyBorder(10, 10, 10, 10));
}
/**
* This method gets the answer panel where a client can enter his answer.
*
* @return the answer panel
*/
public abstract JPanel getAnswerPanel();
/**
* This method checks if the client answer is valid.
*
* @return true, if the answer is valid
*/
public abstract boolean isValid();
public abstract String getAnswer();
}
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.dav.service.method;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.QName;
import com.zimbra.common.service.ServiceException;
import com.zimbra.cs.dav.DavContext;
import com.zimbra.cs.dav.DavElements;
import com.zimbra.cs.dav.DavException;
import com.zimbra.cs.dav.service.DavMethod;
public class Report extends DavMethod {
public static final String REPORT = "REPORT";
public String getName() {
return REPORT;
}
private static HashMap<QName,DavMethod> sReports;
static {
sReports = new HashMap<QName,DavMethod>();
sReports.put(DavElements.E_CALENDAR_QUERY, new CalendarQuery());
sReports.put(DavElements.E_CALENDAR_MULTIGET, new CalendarMultiget());
sReports.put(DavElements.E_FREE_BUSY_QUERY, new FreeBusyQuery());
sReports.put(DavElements.E_PRINCIPAL_PROPERTY_SEARCH, new AclReports());
sReports.put(DavElements.E_ACL_PRINCIPAL_PROP_SET, new AclReports());
sReports.put(DavElements.E_PRINCIPAL_MATCH, new AclReports());
sReports.put(DavElements.E_PRINCIPAL_SEARCH_PROPERTY_SET, new AclReports());
sReports.put(DavElements.E_EXPAND_PROPERTY, new ExpandProperty());
sReports.put(DavElements.CardDav.E_ADDRESSBOOK_QUERY, new AddressbookQuery());
sReports.put(DavElements.CardDav.E_ADDRESSBOOK_MULTIGET, new AddressbookMultiget());
}
public void handle(DavContext ctxt) throws DavException, IOException, ServiceException {
if (!ctxt.hasRequestMessage())
throw new DavException("empty request body", HttpServletResponse.SC_BAD_REQUEST, null);
Document req = ctxt.getRequestMessage();
Element top = req.getRootElement();
if (top == null)
throw new DavException("empty request body", HttpServletResponse.SC_BAD_REQUEST, null);
QName topName = top.getQName();
DavMethod report = sReports.get(topName);
if (report == null)
throw new DavException.UnsupportedReport(topName);
if (ctxt.getDepth() != DavContext.Depth.zero)
ctxt.getDavResponse().createResponse(ctxt);
report.handle(ctxt);
sendResponse(ctxt);
}
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.watcher.actions.index;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.xpack.core.ClientHelper;
import org.elasticsearch.xpack.core.watcher.actions.Action;
import org.elasticsearch.xpack.core.watcher.actions.Action.Result.Status;
import org.elasticsearch.xpack.core.watcher.actions.ExecutableAction;
import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext;
import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils;
import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.core.watcher.watch.Payload;
import org.elasticsearch.xpack.watcher.support.ArrayObjectIterator;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.xpack.core.watcher.support.Exceptions.illegalState;
public class ExecutableIndexAction extends ExecutableAction<IndexAction> {
private static final String INDEX_FIELD = "_index";
private static final String TYPE_FIELD = "_type";
private static final String ID_FIELD = "_id";
private final Client client;
private final TimeValue indexDefaultTimeout;
private final TimeValue bulkDefaultTimeout;
public ExecutableIndexAction(IndexAction action, Logger logger, Client client,
TimeValue indexDefaultTimeout, TimeValue bulkDefaultTimeout) {
super(action, logger);
this.client = client;
this.indexDefaultTimeout = action.timeout != null ? action.timeout : indexDefaultTimeout;
this.bulkDefaultTimeout = action.timeout != null ? action.timeout : bulkDefaultTimeout;
}
@Override
public Action.Result execute(String actionId, WatchExecutionContext ctx, Payload payload) throws Exception {
Map<String, Object> data = payload.data();
if (data.containsKey("_doc")) {
Object doc = data.get("_doc");
if (doc instanceof Iterable) {
return indexBulk((Iterable) doc, actionId, ctx);
}
if (doc.getClass().isArray()) {
return indexBulk(new ArrayObjectIterator.Iterable(doc), actionId, ctx);
}
if (doc instanceof Map) {
data = (Map<String, Object>) doc;
} else {
throw illegalState("could not execute action [{}] of watch [{}]. failed to index payload data." +
"[_data] field must either hold a Map or an List/Array of Maps", actionId, ctx.watch().id());
}
}
if (data.containsKey(INDEX_FIELD) || data.containsKey(TYPE_FIELD) || data.containsKey(ID_FIELD)) {
data = mutableMap(data);
}
IndexRequest indexRequest = new IndexRequest();
if (action.refreshPolicy != null) {
indexRequest.setRefreshPolicy(action.refreshPolicy);
}
indexRequest.index(getField(actionId, ctx.id().watchId(), "index", data, INDEX_FIELD, action.index));
indexRequest.id(getField(actionId, ctx.id().watchId(), "id",data, ID_FIELD, action.docId));
data = addTimestampToDocument(data, ctx.executionTime());
BytesReference bytesReference;
try (XContentBuilder builder = jsonBuilder()) {
indexRequest.source(builder.prettyPrint().map(data));
}
if (ctx.simulateAction(actionId)) {
return new IndexAction.Simulated(indexRequest.index(), MapperService.SINGLE_MAPPING_NAME, indexRequest.id(),
action.refreshPolicy, new XContentSource(indexRequest.source(), XContentType.JSON));
}
IndexResponse response = ClientHelper.executeWithHeaders(ctx.watch().status().getHeaders(), ClientHelper.WATCHER_ORIGIN, client,
() -> client.index(indexRequest).actionGet(indexDefaultTimeout));
try (XContentBuilder builder = jsonBuilder()) {
indexResponseToXContent(builder, response);
bytesReference = BytesReference.bytes(builder);
}
return new IndexAction.Result(Status.SUCCESS, new XContentSource(bytesReference, XContentType.JSON));
}
Action.Result indexBulk(Iterable list, String actionId, WatchExecutionContext ctx) throws Exception {
if (action.docId != null) {
throw illegalState("could not execute action [{}] of watch [{}]. [doc_id] cannot be used with bulk [_doc] indexing");
}
BulkRequest bulkRequest = new BulkRequest();
if (action.refreshPolicy != null) {
bulkRequest.setRefreshPolicy(action.refreshPolicy);
}
for (Object item : list) {
if (!(item instanceof Map)) {
throw illegalState("could not execute action [{}] of watch [{}]. failed to index payload data. " +
"[_data] field must either hold a Map or an List/Array of Maps", actionId, ctx.watch().id());
}
Map<String, Object> doc = (Map<String, Object>) item;
if (doc.containsKey(INDEX_FIELD) || doc.containsKey(TYPE_FIELD) || doc.containsKey(ID_FIELD)) {
doc = mutableMap(doc);
}
IndexRequest indexRequest = new IndexRequest();
indexRequest.index(getField(actionId, ctx.id().watchId(), "index", doc, INDEX_FIELD, action.index));
indexRequest.id(getField(actionId, ctx.id().watchId(), "id",doc, ID_FIELD, action.docId));
doc = addTimestampToDocument(doc, ctx.executionTime());
try (XContentBuilder builder = jsonBuilder()) {
indexRequest.source(builder.prettyPrint().map(doc));
}
bulkRequest.add(indexRequest);
}
BulkResponse bulkResponse = ClientHelper.executeWithHeaders(ctx.watch().status().getHeaders(), ClientHelper.WATCHER_ORIGIN, client,
() -> client.bulk(bulkRequest).actionGet(bulkDefaultTimeout));
try (XContentBuilder jsonBuilder = jsonBuilder().startArray()) {
for (BulkItemResponse item : bulkResponse) {
itemResponseToXContent(jsonBuilder, item);
}
jsonBuilder.endArray();
// different error states, depending on how successful the bulk operation was
long failures = Stream.of(bulkResponse.getItems()).filter(BulkItemResponse::isFailed).count();
if (failures == 0) {
return new IndexAction.Result(Status.SUCCESS, new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON));
} else if (failures == bulkResponse.getItems().length) {
return new IndexAction.Result(Status.FAILURE, new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON));
} else {
return new IndexAction.Result(Status.PARTIAL_FAILURE,
new XContentSource(BytesReference.bytes(jsonBuilder), XContentType.JSON));
}
}
}
private Map<String, Object> addTimestampToDocument(Map<String, Object> data, ZonedDateTime executionTime) {
if (action.executionTimeField != null) {
data = mutableMap(data);
data.put(action.executionTimeField, WatcherDateTimeUtils.formatDate(executionTime));
}
return data;
}
/**
* Extracts the specified field out of data map, or alternative falls back to the action value
*/
private String getField(String actionId, String watchId, String name, Map<String, Object> data, String fieldName, String defaultValue) {
Object obj = data.remove(fieldName);
if (obj != null) {
if (defaultValue != null) {
throw illegalState("could not execute action [{}] of watch [{}]. " +
"[ctx.payload.{}] or [ctx.payload._doc.{}] were set together with action [{}] field. Only set one of them",
actionId, watchId, fieldName, fieldName, name);
} else {
return obj.toString();
}
}
return defaultValue;
}
/**
* Guarantees that the {@code data} is mutable for any code that needs to modify the {@linkplain Map} before using it (e.g., from
* singleton, immutable {@code Map}s).
*
* @param data The map to make mutable
* @return Always a {@linkplain HashMap}
*/
private Map<String, Object> mutableMap(Map<String, Object> data) {
return data instanceof HashMap ? data : new HashMap<>(data);
}
private static void itemResponseToXContent(XContentBuilder builder, BulkItemResponse item) throws IOException {
if (item.isFailed()) {
builder.startObject()
.field("failed", item.isFailed())
.field("message", item.getFailureMessage())
.field("id", item.getId())
.field("index", item.getIndex())
.endObject();
} else {
indexResponseToXContent(builder, item.getResponse());
}
}
static void indexResponseToXContent(XContentBuilder builder, IndexResponse response) throws IOException {
builder.startObject()
.field("created", response.getResult() == DocWriteResponse.Result.CREATED)
.field("result", response.getResult().getLowercase())
.field("id", response.getId())
.field("version", response.getVersion())
.field("index", response.getIndex())
.endObject();
}
}
|
package org.ovirt.engine.api.restapi.types;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.ovirt.engine.api.model.GlusterBrick;
import org.ovirt.engine.api.model.GlusterBrickAdvancedDetails;
import org.ovirt.engine.core.common.businessentities.gluster.BrickDetails;
import org.ovirt.engine.core.common.businessentities.gluster.BrickProperties;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterClientInfo;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeAdvancedDetails;
import org.ovirt.engine.core.common.businessentities.gluster.MallInfo;
import org.ovirt.engine.core.common.businessentities.gluster.MemoryStatus;
import org.ovirt.engine.core.common.businessentities.gluster.Mempool;
import org.ovirt.engine.core.utils.RandomUtils;
public class GlusterBrickDetailMapperTest extends AbstractInvertibleMappingTest<GlusterVolumeAdvancedDetails,
GlusterBrick, GlusterBrick> {
public GlusterBrickDetailMapperTest() {
super(GlusterVolumeAdvancedDetails.class, GlusterBrick.class,
GlusterBrick.class);
}
@Override
protected void verify(GlusterVolumeAdvancedDetails model, GlusterVolumeAdvancedDetails transform) {
assertNotNull(transform);
}
@Test
public void testWithAllDetails() {
GlusterVolumeAdvancedDetails volDetailsEntity = new GlusterVolumeAdvancedDetails();
volDetailsEntity.setBrickDetails(getBrickDetails(1,2,4));
GlusterBrickAdvancedDetails model = GlusterBrickDetailMapper.map(volDetailsEntity, null);
assertNotNull(model);
assertEquals(model.getGlusterClients().getGlusterClients().size(), 2);
assertEquals(model.getMntOptions(), volDetailsEntity.getBrickDetails().get(0).getBrickProperties().getMntOptions());
assertEquals(model.getMemoryPools().getGlusterMemoryPools().size(), volDetailsEntity.getBrickDetails().get(0).getMemoryStatus().getMemPools().size());
}
@Test
public void testWithNoLists() {
GlusterVolumeAdvancedDetails volDetailsEntity = new GlusterVolumeAdvancedDetails();
volDetailsEntity.setBrickDetails(getBrickDetails(0,0,0));
GlusterBrickAdvancedDetails model = GlusterBrickDetailMapper.map(volDetailsEntity, null);
assertNotNull(model);
assertNull(model.getGlusterClients());
assertNull(model.getMntOptions());
}
@Test
public void testWithMultipleClientLists() {
GlusterVolumeAdvancedDetails volDetailsEntity = new GlusterVolumeAdvancedDetails();
volDetailsEntity.setBrickDetails(getBrickDetails(2,2,2));
GlusterBrickAdvancedDetails model = GlusterBrickDetailMapper.map(volDetailsEntity, null);
assertEquals(model.getGlusterClients().getGlusterClients().size(), 2);
assertEquals(model.getMntOptions(), volDetailsEntity.getBrickDetails().get(0).getBrickProperties().getMntOptions());
assertEquals(model.getMemoryPools().getGlusterMemoryPools().size(), volDetailsEntity.getBrickDetails().get(0).getMemoryStatus().getMemPools().size());
}
@Test
public void testWithNullChildObjects() {
GlusterVolumeAdvancedDetails volDetailsEntity = new GlusterVolumeAdvancedDetails();
volDetailsEntity.setBrickDetails(getBrickDetails(1,0,0));
volDetailsEntity.getBrickDetails().get(0).setClients(null);
volDetailsEntity.getBrickDetails().get(0).setMemoryStatus(null);
GlusterBrickAdvancedDetails model = GlusterBrickDetailMapper.map(volDetailsEntity, null);
assertNotNull(model);
assertNull(model.getGlusterClients());
assertEquals(model.getMntOptions(), volDetailsEntity.getBrickDetails().get(0).getBrickProperties().getMntOptions());
assertNull(model.getMemoryPools());
}
private List<BrickDetails> getBrickDetails(int size, int clientListSize, int memPoolSize) {
ArrayList<BrickDetails> list = new ArrayList<BrickDetails>();
for(int i=0; i < size ; i++) {
BrickDetails details = new BrickDetails();
BrickProperties props = new BrickProperties();
props.setBlockSize(14556);
props.setPid(88888);
props.setMntOptions("rw");
details.setBrickProperties(props);
details.setClients(getClientList(clientListSize));
details.setMemoryStatus(getMemoryStatus(memPoolSize));
list.add(details);
}
return list;
}
private MemoryStatus getMemoryStatus(int listSize) {
MemoryStatus memStatus = new MemoryStatus();
memStatus.setMallInfo(new MallInfo());
memStatus.getMallInfo().setArena(RandomUtils.instance().nextInt());
memStatus.getMallInfo().setUordblks(RandomUtils.instance().nextInt());
ArrayList<Mempool> memPoolsList = new ArrayList<Mempool>();
for(int i=0; i < listSize ; i++) {
Mempool pool = new Mempool();
pool.setAllocCount(RandomUtils.instance().nextInt());
pool.setHotCount(0);
pool.setName(RandomUtils.instance().nextString(5));
memPoolsList.add(pool);
}
memStatus.setMemPools(memPoolsList);
return memStatus;
}
private List<GlusterClientInfo> getClientList(int listSize) {
ArrayList<GlusterClientInfo> list = new ArrayList<GlusterClientInfo>();
for(int i=0; i < listSize ; i++) {
GlusterClientInfo clientInfo = new GlusterClientInfo();
clientInfo.setBytesRead(RandomUtils.instance().nextInt());
clientInfo.setBytesWritten(RandomUtils.instance().nextInt());
clientInfo.setClientPort(RandomUtils.instance().nextInt());
clientInfo.setHostname(RandomUtils.instance().nextString(7));
list.add(clientInfo);
}
return list;
}
}
|
//Protocol Buffers - Google's data interchange format
//Copyright 2008 Google Inc.
//http://code.google.com/p/protobuf/
//
//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.apache.activemq.protobuf;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Encodes and writes protocol message fields.
*
* <p>
* This class contains two kinds of methods: methods that write specific
* protocol message constructs and field types (e.g. {@link #writeTag} and
* {@link #writeInt32}) and methods that write low-level values (e.g.
* {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are writing
* encoded protocol messages, you should use the former methods, but if you are
* writing some other format of your own design, use the latter.
*
* <p>
* This class is totally unsynchronized.
*
* @author kneton@google.com Kenton Varda
*/
public final class CodedOutputStream extends FilterOutputStream {
private BufferOutputStream bos;
public CodedOutputStream(OutputStream os) {
super(os);
if( os instanceof BufferOutputStream ) {
bos = (BufferOutputStream)os;
}
}
public CodedOutputStream(byte[] data) {
super(new BufferOutputStream(data));
}
public CodedOutputStream(Buffer data) {
super(new BufferOutputStream(data));
}
// -----------------------------------------------------------------
/** Write a {@code double} field, including tag, to the stream. */
public void writeDouble(int fieldNumber, double value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeRawLittleEndian64(Double.doubleToRawLongBits(value));
}
/** Write a {@code float} field, including tag, to the stream. */
public void writeFloat(int fieldNumber, float value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeRawLittleEndian32(Float.floatToRawIntBits(value));
}
/** Write a {@code uint64} field, including tag, to the stream. */
public void writeUInt64(int fieldNumber, long value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeRawVarint64(value);
}
/** Write an {@code int64} field, including tag, to the stream. */
public void writeInt64(int fieldNumber, long value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeRawVarint64(value);
}
/** Write an {@code int32} field, including tag, to the stream. */
public void writeInt32(int fieldNumber, int value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
if (value >= 0) {
writeRawVarint32(value);
} else {
// Must sign-extend.
writeRawVarint64(value);
}
}
/** Write a {@code fixed64} field, including tag, to the stream. */
public void writeFixed64(int fieldNumber, long value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeRawLittleEndian64(value);
}
/** Write a {@code fixed32} field, including tag, to the stream. */
public void writeFixed32(int fieldNumber, int value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeRawLittleEndian32(value);
}
/** Write a {@code bool} field, including tag, to the stream. */
public void writeBool(int fieldNumber, boolean value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeRawByte(value ? 1 : 0);
}
/** Write a {@code string} field, including tag, to the stream. */
public void writeString(int fieldNumber, String value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
// Unfortunately there does not appear to be any way to tell Java to
// encode
// UTF-8 directly into our buffer, so we have to let it create its own
// byte
// array and then copy.
byte[] bytes = value.getBytes("UTF-8");
writeRawVarint32(bytes.length);
writeRawBytes(bytes);
}
/** Write a {@code bytes} field, including tag, to the stream. */
public void writeBytes(int fieldNumber, Buffer value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
writeRawVarint32(value.length);
writeRawBytes(value.data, value.offset, value.length);
}
/** Write a {@code uint32} field, including tag, to the stream. */
public void writeUInt32(int fieldNumber, int value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeRawVarint32(value);
}
/**
* Write an enum field, including tag, to the stream. Caller is responsible
* for converting the enum value to its numeric value.
*/
public void writeEnum(int fieldNumber, int value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeRawVarint32(value);
}
/** Write an {@code sfixed32} field, including tag, to the stream. */
public void writeSFixed32(int fieldNumber, int value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
writeRawLittleEndian32(value);
}
/** Write an {@code sfixed64} field, including tag, to the stream. */
public void writeSFixed64(int fieldNumber, long value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
writeRawLittleEndian64(value);
}
/** Write an {@code sint32} field, including tag, to the stream. */
public void writeSInt32(int fieldNumber, int value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeRawVarint32(encodeZigZag32(value));
}
/** Write an {@code sint64} field, including tag, to the stream. */
public void writeSInt64(int fieldNumber, long value) throws IOException {
writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
writeRawVarint64(encodeZigZag64(value));
}
// =================================================================
/**
* Compute the number of bytes that would be needed to encode a {@code
* double} field, including tag.
*/
public static int computeDoubleSize(int fieldNumber, double value) {
return computeTagSize(fieldNumber) + LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a {@code
* float} field, including tag.
*/
public static int computeFloatSize(int fieldNumber, float value) {
return computeTagSize(fieldNumber) + LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a {@code
* uint64} field, including tag.
*/
public static int computeUInt64Size(int fieldNumber, long value) {
return computeTagSize(fieldNumber) + computeRawVarint64Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an {@code
* int64} field, including tag.
*/
public static int computeInt64Size(int fieldNumber, long value) {
return computeTagSize(fieldNumber) + computeRawVarint64Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an {@code
* int32} field, including tag.
*/
public static int computeInt32Size(int fieldNumber, int value) {
if (value >= 0) {
return computeTagSize(fieldNumber) + computeRawVarint32Size(value);
} else {
// Must sign-extend.
return computeTagSize(fieldNumber) + 10;
}
}
/**
* Compute the number of bytes that would be needed to encode a {@code
* fixed64} field, including tag.
*/
public static int computeFixed64Size(int fieldNumber, long value) {
return computeTagSize(fieldNumber) + LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a {@code
* fixed32} field, including tag.
*/
public static int computeFixed32Size(int fieldNumber, int value) {
return computeTagSize(fieldNumber) + LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode a {@code bool}
* field, including tag.
*/
public static int computeBoolSize(int fieldNumber, boolean value) {
return computeTagSize(fieldNumber) + 1;
}
/**
* Compute the number of bytes that would be needed to encode a {@code
* string} field, including tag.
*/
public static int computeStringSize(int fieldNumber, String value) {
try {
byte[] bytes = value.getBytes("UTF-8");
return computeTagSize(fieldNumber) + computeRawVarint32Size(bytes.length) + bytes.length;
} catch (java.io.UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 not supported.", e);
}
}
/**
* Compute the number of bytes that would be needed to encode a {@code
* bytes} field, including tag.
*/
public static int computeBytesSize(int fieldNumber, Buffer value) {
return computeTagSize(fieldNumber) + computeRawVarint32Size(value.length) + value.length;
}
/**
* Compute the number of bytes that would be needed to encode a {@code
* uint32} field, including tag.
*/
public static int computeUInt32Size(int fieldNumber, int value) {
return computeTagSize(fieldNumber) + computeRawVarint32Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an enum field,
* including tag. Caller is responsible for converting the enum value to its
* numeric value.
*/
public static int computeEnumSize(int fieldNumber, int value) {
return computeTagSize(fieldNumber) + computeRawVarint32Size(value);
}
/**
* Compute the number of bytes that would be needed to encode an {@code
* sfixed32} field, including tag.
*/
public static int computeSFixed32Size(int fieldNumber, int value) {
return computeTagSize(fieldNumber) + LITTLE_ENDIAN_32_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode an {@code
* sfixed64} field, including tag.
*/
public static int computeSFixed64Size(int fieldNumber, long value) {
return computeTagSize(fieldNumber) + LITTLE_ENDIAN_64_SIZE;
}
/**
* Compute the number of bytes that would be needed to encode an {@code
* sint32} field, including tag.
*/
public static int computeSInt32Size(int fieldNumber, int value) {
return computeTagSize(fieldNumber) + computeRawVarint32Size(encodeZigZag32(value));
}
/**
* Compute the number of bytes that would be needed to encode an {@code
* sint64} field, including tag.
*/
public static int computeSInt64Size(int fieldNumber, long value) {
return computeTagSize(fieldNumber) + computeRawVarint64Size(encodeZigZag64(value));
}
/** Write a single byte. */
public void writeRawByte(byte value) throws IOException {
out.write(value);
}
/** Write a single byte, represented by an integer value. */
public void writeRawByte(int value) throws IOException {
writeRawByte((byte) value);
}
/** Write an array of bytes. */
public void writeRawBytes(byte[] value) throws IOException {
writeRawBytes(value, 0, value.length);
}
/** Write part of an array of bytes. */
public void writeRawBytes(byte[] value, int offset, int length) throws IOException {
out.write(value, offset, length);
}
public void writeRawBytes(Buffer data) throws IOException {
out.write(data.data, data.offset, data.length);
}
/** Encode and write a tag. */
public void writeTag(int fieldNumber, int wireType) throws IOException {
writeRawVarint32(WireFormat.makeTag(fieldNumber, wireType));
}
/** Compute the number of bytes that would be needed to encode a tag. */
public static int computeTagSize(int fieldNumber) {
return computeRawVarint32Size(WireFormat.makeTag(fieldNumber, 0));
}
/**
* Encode and write a varint. {@code value} is treated as unsigned, so it
* won't be sign-extended if negative.
*/
public void writeRawVarint32(int value) throws IOException {
while (true) {
if ((value & ~0x7F) == 0) {
writeRawByte(value);
return;
} else {
writeRawByte((value & 0x7F) | 0x80);
value >>>= 7;
}
}
}
/**
* Compute the number of bytes that would be needed to encode a varint.
* {@code value} is treated as unsigned, so it won't be sign-extended if
* negative.
*/
public static int computeRawVarint32Size(int value) {
if ((value & (0xffffffff << 7)) == 0)
return 1;
if ((value & (0xffffffff << 14)) == 0)
return 2;
if ((value & (0xffffffff << 21)) == 0)
return 3;
if ((value & (0xffffffff << 28)) == 0)
return 4;
return 5;
}
/** Encode and write a varint. */
public void writeRawVarint64(long value) throws IOException {
while (true) {
if ((value & ~0x7FL) == 0) {
writeRawByte((int) value);
return;
} else {
writeRawByte(((int) value & 0x7F) | 0x80);
value >>>= 7;
}
}
}
/** Compute the number of bytes that would be needed to encode a varint. */
public static int computeRawVarint64Size(long value) {
if ((value & (0xffffffffffffffffL << 7)) == 0)
return 1;
if ((value & (0xffffffffffffffffL << 14)) == 0)
return 2;
if ((value & (0xffffffffffffffffL << 21)) == 0)
return 3;
if ((value & (0xffffffffffffffffL << 28)) == 0)
return 4;
if ((value & (0xffffffffffffffffL << 35)) == 0)
return 5;
if ((value & (0xffffffffffffffffL << 42)) == 0)
return 6;
if ((value & (0xffffffffffffffffL << 49)) == 0)
return 7;
if ((value & (0xffffffffffffffffL << 56)) == 0)
return 8;
if ((value & (0xffffffffffffffffL << 63)) == 0)
return 9;
return 10;
}
/** Write a little-endian 32-bit integer. */
public void writeRawLittleEndian32(int value) throws IOException {
writeRawByte((value) & 0xFF);
writeRawByte((value >> 8) & 0xFF);
writeRawByte((value >> 16) & 0xFF);
writeRawByte((value >> 24) & 0xFF);
}
public static final int LITTLE_ENDIAN_32_SIZE = 4;
/** Write a little-endian 64-bit integer. */
public void writeRawLittleEndian64(long value) throws IOException {
writeRawByte((int) (value) & 0xFF);
writeRawByte((int) (value >> 8) & 0xFF);
writeRawByte((int) (value >> 16) & 0xFF);
writeRawByte((int) (value >> 24) & 0xFF);
writeRawByte((int) (value >> 32) & 0xFF);
writeRawByte((int) (value >> 40) & 0xFF);
writeRawByte((int) (value >> 48) & 0xFF);
writeRawByte((int) (value >> 56) & 0xFF);
}
public static final int LITTLE_ENDIAN_64_SIZE = 8;
/**
* Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into
* values that can be efficiently encoded with varint. (Otherwise, negative
* values must be sign-extended to 64 bits to be varint encoded, thus always
* taking 10 bytes on the wire.)
*
* @param n
* A signed 32-bit integer.
* @return An unsigned 32-bit integer, stored in a signed int because Java
* has no explicit unsigned support.
*/
public static int encodeZigZag32(int n) {
// Note: the right-shift must be arithmetic
return (n << 1) ^ (n >> 31);
}
/**
* Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into
* values that can be efficiently encoded with varint. (Otherwise, negative
* values must be sign-extended to 64 bits to be varint encoded, thus always
* taking 10 bytes on the wire.)
*
* @param n
* A signed 64-bit integer.
* @return An unsigned 64-bit integer, stored in a signed int because Java
* has no explicit unsigned support.
*/
public static long encodeZigZag64(long n) {
// Note: the right-shift must be arithmetic
return (n << 1) ^ (n >> 63);
}
public void checkNoSpaceLeft() {
}
public Buffer getNextBuffer(int size) throws IOException {
if( bos==null ) {
return null;
}
return bos.getNextBuffer(size);
}
}
|
package br.com.rfasioli.ContentGenerator.service.processor.pipe.impl;
import static org.junit.Assert.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
import br.com.rfasioli.ContentGenerator.service.processor.pipe.PipeCommander;
public class DatePipeCommanderImplTest {
@Test
public void testExecute() {
Date date = new Date();
PipeCommander pipe = new DatePipeCommanderImpl();
String result = pipe.execute(String.valueOf(date.getTime()));
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String strDate = df.format(date);
assertTrue(result.equals(strDate));
}
}
|
/*
* 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
*
* 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.webauthn4j.data;
import com.webauthn4j.data.client.challenge.Challenge;
import com.webauthn4j.data.client.challenge.DefaultChallenge;
import com.webauthn4j.util.CollectionUtil;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
class PublicKeyCredentialRequestOptionsTest {
@Test
void getter_test() {
String rpId = "example.com";
long timeout = 0;
Challenge challenge = new DefaultChallenge();
byte[] credentialId = new byte[32];
List<PublicKeyCredentialDescriptor> allowCredentials = Collections.singletonList(
new PublicKeyCredentialDescriptor(
PublicKeyCredentialType.PUBLIC_KEY,
credentialId,
CollectionUtil.unmodifiableSet(AuthenticatorTransport.USB, AuthenticatorTransport.NFC, AuthenticatorTransport.BLE)
)
);
PublicKeyCredentialRequestOptions credentialRequestOptions = new PublicKeyCredentialRequestOptions(
challenge,
timeout,
rpId,
allowCredentials,
UserVerificationRequirement.DISCOURAGED,
null
);
assertAll(
() -> assertThat(credentialRequestOptions.getChallenge()).isEqualTo(challenge),
() -> assertThat(credentialRequestOptions.getTimeout()).isEqualTo(timeout),
() -> assertThat(credentialRequestOptions.getRpId()).isEqualTo(rpId),
() -> assertThat(credentialRequestOptions.getAllowCredentials()).isEqualTo(allowCredentials),
() -> assertThat(credentialRequestOptions.getUserVerification()).isEqualTo(UserVerificationRequirement.DISCOURAGED),
() -> assertThat(credentialRequestOptions.getExtensions()).isNull()
);
}
@Test
void equals_hashCode_test() {
String rpId = "example.com";
long timeout = 0;
Challenge challenge = new DefaultChallenge();
byte[] credentialId = new byte[32];
List<PublicKeyCredentialDescriptor> allowCredentials = Collections.singletonList(
new PublicKeyCredentialDescriptor(
PublicKeyCredentialType.PUBLIC_KEY,
credentialId,
CollectionUtil.unmodifiableSet(AuthenticatorTransport.USB, AuthenticatorTransport.NFC, AuthenticatorTransport.BLE)
)
);
PublicKeyCredentialRequestOptions instanceA = new PublicKeyCredentialRequestOptions(
challenge,
timeout,
rpId,
allowCredentials,
UserVerificationRequirement.DISCOURAGED,
null
);
PublicKeyCredentialRequestOptions instanceB = new PublicKeyCredentialRequestOptions(
challenge,
timeout,
rpId,
allowCredentials,
UserVerificationRequirement.DISCOURAGED,
null
);
assertAll(
() -> assertThat(instanceA).isEqualTo(instanceB),
() -> assertThat(instanceA).hasSameHashCodeAs(instanceB)
);
}
}
|
package org.nanotek.beans.sun.editors;
import java.beans.PropertyEditorSupport;
import java.util.UUID;
public class UUIDEditor extends PropertyEditorSupport{
public String getJavaInitializationString() {
Object value = getValue();
if (value == null)
return "null";
else
return value.toString();
}
public void setAsText(String text) {
setValue((text == null) ? null : UUID.fromString(text));
}
@Override
public Object getValue() {
return super.getValue();
}
}
|
package com.cjm721.overloaded.block.tile;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull;
public abstract class AbstractTileEntityFaceable extends TileEntity {
private EnumFacing front;
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
this.front = EnumFacing.byIndex(compound.getInteger("Front"));
}
@Override
@Nonnull
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
compound.setInteger("Front", this.front.getIndex());
return super.writeToNBT(compound);
}
public AbstractTileEntityFaceable setFacing(EnumFacing front) {
this.front = front;
return this;
}
EnumFacing getFacing() {
return front;
}
}
|
package io.smallrye.reactive.messaging.kafka.fault;
import static io.smallrye.reactive.messaging.kafka.i18n.KafkaExceptions.ex;
import java.util.concurrent.CompletionStage;
import org.eclipse.microprofile.reactive.messaging.Metadata;
import io.smallrye.reactive.messaging.kafka.IncomingKafkaRecord;
public interface KafkaFailureHandler {
enum Strategy {
FAIL,
IGNORE,
DEAD_LETTER_QUEUE;
public static Strategy from(String s) {
if (s == null || s.equalsIgnoreCase("fail")) {
return FAIL;
}
if (s.equalsIgnoreCase("ignore")) {
return IGNORE;
}
if (s.equalsIgnoreCase("dead-letter-queue")) {
return DEAD_LETTER_QUEUE;
}
throw ex.illegalArgumentUnknownFailureStrategy(s);
}
}
<K, V> CompletionStage<Void> handle(IncomingKafkaRecord<K, V> record, Throwable reason, Metadata metadata);
default void terminate() {
// do nothing by default
}
}
|
import java.util.*;
@javax.annotation.Generated(value = {"decisionTableRuleOutput.ftl", "testNullComplexTypeAccess"})
public class TestNullComplexTypeAccessRuleOutput extends com.gs.dmn.runtime.RuleOutput {
private String testNullComplexTypeAccess;
public TestNullComplexTypeAccessRuleOutput(boolean matched) {
super(matched);
}
@com.fasterxml.jackson.annotation.JsonGetter("testNullComplexTypeAccess")
public String getTestNullComplexTypeAccess() {
return this.testNullComplexTypeAccess;
}
@com.fasterxml.jackson.annotation.JsonSetter("testNullComplexTypeAccess")
public void setTestNullComplexTypeAccess(String testNullComplexTypeAccess) {
this.testNullComplexTypeAccess = testNullComplexTypeAccess;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestNullComplexTypeAccessRuleOutput other = (TestNullComplexTypeAccessRuleOutput) o;
if (this.getTestNullComplexTypeAccess() != null ? !this.getTestNullComplexTypeAccess().equals(other.getTestNullComplexTypeAccess()) : other.getTestNullComplexTypeAccess() != null) return false;
return true;
}
@Override
public int hashCode() {
int result = 0;
result = 31 * result + (this.getTestNullComplexTypeAccess() != null ? this.getTestNullComplexTypeAccess().hashCode() : 0);
return result;
}
public String toString() {
StringBuilder result_ = new StringBuilder("(matched=" + isMatched());
result_.append(String.format(", testNullComplexTypeAccess='%s'", testNullComplexTypeAccess));
result_.append(")");
return result_.toString();
}
}
|
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.future;
import java.util.Set;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.Iterables;
import com.opengamma.analytics.financial.instrument.future.BondFutureDefinition;
import com.opengamma.analytics.financial.interestrate.future.derivative.BondFuture;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.region.RegionSource;
import com.opengamma.core.security.SecuritySource;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.financial.analytics.conversion.BondFutureSecurityConverter;
import com.opengamma.financial.analytics.conversion.BondSecurityConverter;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.security.FinancialSecurityTypes;
import com.opengamma.financial.security.future.BondFutureSecurity;
/**
*
* @param <T> The type of data that the calculator needs
*/
public abstract class BondFutureFunction<T> extends AbstractFunction.NonCompiledInvoker {
private BondFutureSecurityConverter _visitor;
@Override
public void init(final FunctionCompilationContext context) {
final HolidaySource holidaySource = OpenGammaCompilationContext.getHolidaySource(context);
final ConventionBundleSource conventionSource = OpenGammaCompilationContext.getConventionBundleSource(context);
final RegionSource regionSource = OpenGammaCompilationContext.getRegionSource(context);
final SecuritySource securitySource = OpenGammaCompilationContext.getSecuritySource(context);
final BondSecurityConverter bondConverter = new BondSecurityConverter(holidaySource, conventionSource, regionSource);
_visitor = new BondFutureSecurityConverter(securitySource, bondConverter);
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
final ZonedDateTime date = ZonedDateTime.now(executionContext.getValuationClock());
final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
final BondFutureSecurity security = (BondFutureSecurity) target.getSecurity();
final BondFutureDefinition definition = (BondFutureDefinition) security.accept(_visitor);
final Double referencePrice = 0.0; // TODO Futures Refactor
final String[] curveNames = getCurveNames(desiredValue);
final BondFuture bondFuture = definition.toDerivative(date, referencePrice, curveNames);
return calculate(security, bondFuture, getData(desiredValue, inputs, target), target);
}
protected abstract Set<ComputedValue> calculate(com.opengamma.financial.security.future.BondFutureSecurity security, BondFuture bondFuture, T data, ComputationTarget target);
protected abstract T getData(ValueRequirement desiredValue, FunctionInputs inputs, ComputationTarget target);
protected abstract String[] getCurveNames(ValueRequirement desiredValue);
@Override
public ComputationTargetType getTargetType() {
return FinancialSecurityTypes.BOND_FUTURE_SECURITY;
}
}
|
package com.gardyanakbar.guardianheadpaindiary.datadrivers;
import giantsweetroll.date.Date;
public class GraphSettings
{
//Fields
private Date dateFrom, dateTo;
private String category;
private int categoryIndex;
private boolean showDataValues, showDataVoid, showDataPoints;
//Constructor
public GraphSettings()
{
this.dateFrom = new Date();
this.dateTo = new Date();
this.category = "";
this.categoryIndex = 0;
this.showDataPoints = false;
this.showDataValues = false;
this.showDataVoid = true;
}
//Setters and Getters
public Date getDateFrom() {
return dateFrom;
}
public void setDateFrom(Date dateFrom) {
this.dateFrom = dateFrom;
}
public Date getDateTo() {
return dateTo;
}
public void setDateTo(Date dateTo) {
this.dateTo = dateTo;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getCategoryIndex() {
return categoryIndex;
}
public void setCategoryIndex(int categoryIndex) {
this.categoryIndex = categoryIndex;
}
public boolean isShowDataValues() {
return showDataValues;
}
public void setShowDataValues(boolean showDataValues) {
this.showDataValues = showDataValues;
}
public boolean isShowDataVoid() {
return showDataVoid;
}
public void setShowDataVoid(boolean showDataVoid) {
this.showDataVoid = showDataVoid;
}
public boolean isShowDataPoints() {
return showDataPoints;
}
public void setShowDataPoints(boolean showDataPoints) {
this.showDataPoints = showDataPoints;
}
}
|
/*
* Copyright 2014-2015 Kay Stenschke
*
* 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.kstenschke.copypastestack.Listeners;
import com.kstenschke.copypastestack.ToolWindow;
import com.kstenschke.copypastestack.resources.ui.ToolWindowForm;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class ListSelectionListenerItemsList implements ListSelectionListener {
private final ToolWindow toolWindow;
private final ToolWindowForm toolWindowForm;
public ListSelectionListenerItemsList(ToolWindow toolWindow) {
this.toolWindow = toolWindow;
toolWindowForm = toolWindow.getForm();
}
@Override
public void valueChanged(ListSelectionEvent e) {
String itemText = this.toolWindow.getSelectedItemText();
this.toolWindow.setPreviewText(itemText);
this.toolWindowForm.textPanePreview.setCaretPosition(0);
if( this.toolWindowForm.panelPreviewImage.isVisible() ) {
this.toolWindowForm.listPreview.clearSelection();
this.toolWindowForm.panelPreviewImage.setVisible(false);
this.toolWindowForm.scrollPanePreview.setVisible(true);
}
}
}
|
package org.openrepose.filters.translation.xslt;
public class XsltException extends RuntimeException {
public XsltException(String message) {
super(message);
}
public XsltException(Throwable cause) {
super(cause);
}
public XsltException(String message, Throwable cause) {
super(message, cause);
}
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute.v2019_07_01;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Api error.
*/
public class ApiError {
/**
* The Api error details.
*/
@JsonProperty(value = "details")
private List<ApiErrorBase> details;
/**
* The Api inner error.
*/
@JsonProperty(value = "innererror")
private InnerError innererror;
/**
* The error code.
*/
@JsonProperty(value = "code")
private String code;
/**
* The target of the particular error.
*/
@JsonProperty(value = "target")
private String target;
/**
* The error message.
*/
@JsonProperty(value = "message")
private String message;
/**
* Get the Api error details.
*
* @return the details value
*/
public List<ApiErrorBase> details() {
return this.details;
}
/**
* Set the Api error details.
*
* @param details the details value to set
* @return the ApiError object itself.
*/
public ApiError withDetails(List<ApiErrorBase> details) {
this.details = details;
return this;
}
/**
* Get the Api inner error.
*
* @return the innererror value
*/
public InnerError innererror() {
return this.innererror;
}
/**
* Set the Api inner error.
*
* @param innererror the innererror value to set
* @return the ApiError object itself.
*/
public ApiError withInnererror(InnerError innererror) {
this.innererror = innererror;
return this;
}
/**
* Get the error code.
*
* @return the code value
*/
public String code() {
return this.code;
}
/**
* Set the error code.
*
* @param code the code value to set
* @return the ApiError object itself.
*/
public ApiError withCode(String code) {
this.code = code;
return this;
}
/**
* Get the target of the particular error.
*
* @return the target value
*/
public String target() {
return this.target;
}
/**
* Set the target of the particular error.
*
* @param target the target value to set
* @return the ApiError object itself.
*/
public ApiError withTarget(String target) {
this.target = target;
return this;
}
/**
* Get the error message.
*
* @return the message value
*/
public String message() {
return this.message;
}
/**
* Set the error message.
*
* @param message the message value to set
* @return the ApiError object itself.
*/
public ApiError withMessage(String message) {
this.message = message;
return this;
}
}
|
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.autoconfigure.metrics.export.graphite;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Tags;
import io.micrometer.graphite.GraphiteConfig;
import io.micrometer.graphite.GraphiteMeterRegistry;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link GraphiteMetricsExportAutoConfiguration}.
*
* @author Andy Wilkinson
* @author Stephane Nicoll
*/
public class GraphiteMetricsExportAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(GraphiteMetricsExportAutoConfiguration.class));
@Test
public void backsOffWithoutAClock() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class));
}
@Test
public void autoConfiguresUseTagsAsPrefix() {
this.contextRunner.withUserConfiguration(BaseConfiguration.class)
.withPropertyValues("management.metrics.export.graphite.tags-as-prefix=app").run((context) -> {
assertThat(context).hasSingleBean(GraphiteMeterRegistry.class);
GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class);
registry.counter("test.count", Tags.of("app", "myapp"));
assertThat(registry.getDropwizardRegistry().getMeters()).containsOnlyKeys("myapp.testCount");
});
}
@Test
public void autoConfiguresItsConfigAndMeterRegistry() {
this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> assertThat(context)
.hasSingleBean(GraphiteMeterRegistry.class).hasSingleBean(GraphiteConfig.class));
}
@Test
public void autoConfigurationCanBeDisabled() {
this.contextRunner.withUserConfiguration(BaseConfiguration.class)
.withPropertyValues("management.metrics.export.graphite.enabled=false")
.run((context) -> assertThat(context).doesNotHaveBean(GraphiteMeterRegistry.class)
.doesNotHaveBean(GraphiteConfig.class));
}
@Test
public void allowsCustomConfigToBeUsed() {
this.contextRunner.withUserConfiguration(CustomConfigConfiguration.class)
.run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class)
.hasSingleBean(GraphiteConfig.class).hasBean("customConfig"));
}
@Test
public void allowsCustomRegistryToBeUsed() {
this.contextRunner.withUserConfiguration(CustomRegistryConfiguration.class)
.run((context) -> assertThat(context).hasSingleBean(GraphiteMeterRegistry.class)
.hasBean("customRegistry").hasSingleBean(GraphiteConfig.class));
}
@Test
public void stopsMeterRegistryWhenContextIsClosed() {
this.contextRunner.withUserConfiguration(BaseConfiguration.class).run((context) -> {
GraphiteMeterRegistry registry = context.getBean(GraphiteMeterRegistry.class);
assertThat(registry.isClosed()).isFalse();
context.close();
assertThat(registry.isClosed()).isTrue();
});
}
@Configuration
static class BaseConfiguration {
@Bean
public Clock clock() {
return Clock.SYSTEM;
}
}
@Configuration
@Import(BaseConfiguration.class)
static class CustomConfigConfiguration {
@Bean
public GraphiteConfig customConfig() {
return (key) -> {
if ("Graphite.apiKey".equals(key)) {
return "12345";
}
return null;
};
}
}
@Configuration
@Import(BaseConfiguration.class)
static class CustomRegistryConfiguration {
@Bean
public GraphiteMeterRegistry customRegistry(GraphiteConfig config, Clock clock) {
return new GraphiteMeterRegistry(config, clock);
}
}
}
|
package module1500_public_tests_more.a;
import java.util.zip.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
/**
* Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
* labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
* Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
*
* @see java.awt.datatransfer.DataFlavor
* @see java.beans.beancontext.BeanContext
* @see java.io.File
*/
@SuppressWarnings("all")
public interface IFoo1<V> extends module1500_public_tests_more.a.IFoo0<V> {
java.rmi.Remote f0 = null;
java.nio.file.FileStore f1 = null;
java.sql.Array f2 = null;
String getName();
void setName(String s);
V get();
void set(V e);
}
|
/*****************************************************************
<copyright>
Morozko Java Library org.fugerit.java.core
Copyright (c) 2006 Morozko
All rights reserved. This program and the accompanying materials
are made available under the terms of the Apache License v2.0
which accompanies this distribution, and is available at
http://www.apache.org/licenses/
(txt version : http://www.apache.org/licenses/LICENSE-2.0.txt
html version : http://www.apache.org/licenses/LICENSE-2.0.html)
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
</copyright>
*****************************************************************/
/*
* @(#)FileClassLoader.java
*
* @project : org.fugerit.java.core
* @package : org.fugerit.java.core.lang.cl
* @creation : 14-set-2005 1.04.55
*/
package org.fugerit.java.core.lang.helpers.cl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class FileClassLoader extends URLClassLoader {
private static URL[] resolveURL( File f, File tmpDir ) {
URL[] list= new URL[1];
if (f.isDirectory()) {
try {
list[0] = new URL( "file://"+f.getCanonicalPath()+File.separator );
} catch (MalformedURLException e) {
throw (new RuntimeException( e ));
} catch (IOException e) {
throw (new RuntimeException( e ));
}
} else {
try {
JarInputStream jis = new JarInputStream( new FileInputStream( f ) );
JarEntry entry = jis.getNextJarEntry();
while (entry!=null) {
String name = entry.getName();
long size = entry.getSize();
System.out.println( "NAME : "+name );
System.out.println( "SIZE : "+size );
if ( name.charAt( name.length()-1 )=='/' ) {
File current = new File( tmpDir, name+"/" );
System.out.println( "DIR : "+current.mkdirs() );
} else {
File current = new File( tmpDir, name );
System.out.println( "FILE" );
FileOutputStream fos = new FileOutputStream( current );
while (jis.available()>0) {
fos.write( jis.read() );
}
fos.flush();
fos.close();
}
jis.closeEntry();
entry = jis.getNextJarEntry();
}
jis.close();
list = resolveURL( tmpDir, tmpDir );
} catch (IOException e) {
throw (new RuntimeException( e ));
}
}
return list;
}
public FileClassLoader( File f, File tmpDir ) {
this( f, tmpDir , ClassLoader.getSystemClassLoader());
}
public FileClassLoader(File f , File tmpDir, ClassLoader parent) {
super( resolveURL( f, tmpDir ) );
}
public static void main(String[] args) {
try {
FileClassLoader cl = new FileClassLoader(
new File( "C:\\Programmi\\PostgreSQL\\8.0\\jdbc\\postgresql-8.0-310.jdbc2ee.jar" ),
new File( "C:\\test" )
);
cl.loadClass( "org.postgresql.Driver" );
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.elsewhere_games.lib.logging;
// JUnit
import org.junit.Assert;
import org.junit.Test;
// Logging Mocks
import com.elsewhere_games.lib.logging.mock.MockAppender;
/**
* <p>A test case for the {@link LogManager} class.</p>
*/
public class LogManagerTestCase {
@Test
public void managerIsASingleton() {
LogManager instance1 = LogManager.getInstance();
LogManager instance2 = LogManager.getInstance();
Assert.assertEquals(instance1, instance2);
}
@Test
public void appendersAreAppliedToExistingLogs() {
String name = "new_log";
Log log = LogManager.getInstance().getLog(name);
log.setLevel(Level.DEBUG);
MockAppender appender = new MockAppender();
String message = "Test message";
log.debug(message);
Assert.assertNull(appender.getLastSource());
Assert.assertNotEquals(Level.DEBUG, appender.getLastLevel());
Assert.assertFalse(appender.getLastMessage().equals(message));
LogManager.getInstance().addAppender(appender);
log.debug(message);
Assert.assertEquals(log, appender.getLastSource());
Assert.assertEquals(Level.DEBUG, appender.getLastLevel());
Assert.assertTrue(appender.getLastMessage().equals(message));
}
@Test
public void appendersAreAppliedToNewLogs() {
MockAppender appender = new MockAppender();
LogManager.getInstance().addAppender(appender);
String name = "new_log";
Log log = LogManager.getInstance().getLog(name);
log.setLevel(Level.DEBUG);
String message = "Test message";
log.debug(message);
Assert.assertEquals(log, appender.getLastSource());
Assert.assertEquals(Level.DEBUG, appender.getLastLevel());
Assert.assertTrue(appender.getLastMessage().equals(message));
}
@Test
public void multipleAppendersAreAppliedToNewLogs() {
MockAppender appender1 = new MockAppender();
LogManager.getInstance().addAppender(appender1);
MockAppender appender2 = new MockAppender();
LogManager.getInstance().addAppender(appender2);
String name = "new_log";
Log log = LogManager.getInstance().getLog(name);
log.setLevel(Level.DEBUG);
String message = "Test message";
log.debug(message);
Assert.assertEquals(log, appender1.getLastSource());
Assert.assertEquals(Level.DEBUG, appender1.getLastLevel());
Assert.assertTrue(appender1.getLastMessage().equals(message));
Assert.assertEquals(log, appender2.getLastSource());
Assert.assertEquals(Level.DEBUG, appender2.getLastLevel());
Assert.assertTrue(appender2.getLastMessage().equals(message));
}
@Test
public void levelsAreAppliedToExistingLogs() {
String logName = "new_log";
Log log = LogManager.getInstance().getLog(logName);
MockAppender appender = new MockAppender();
log.addAppender(appender);
log.setLevel(Level.ERROR);
String message = "Test message";
log.debug(message); // Sanity Check
Assert.assertNull(appender.getLastSource());
Assert.assertNotEquals(Level.DEBUG, appender.getLastLevel());
Assert.assertFalse(appender.getLastMessage().equals(message));
LogManager.getInstance().setLevel(Level.DEBUG);
log.debug(message);
Assert.assertEquals(log, appender.getLastSource());
Assert.assertEquals(Level.DEBUG, appender.getLastLevel());
Assert.assertTrue(appender.getLastMessage().equals(message));
}
@Test
public void levelsAreAppliedToNewLogs() {
LogManager.getInstance().setLevel(Level.DEBUG);
String logName = "new_log";
Log log = LogManager.getInstance().getLog(logName);
MockAppender appender = new MockAppender();
log.addAppender(appender);
String message = "Test message";
log.debug(message);
Assert.assertEquals(log, appender.getLastSource());
Assert.assertEquals(Level.DEBUG, appender.getLastLevel());
Assert.assertTrue(appender.getLastMessage().equals(message));
}
}
|
package animals.felines;
import java.util.Random;
public class Cat extends Feline{
// Constructor with Delegation of roam
public Cat(String name, int age) {
super(name, age);
}
public Cat(String name, int age, FelineRoam roamBehavior) {
super(name, age, roamBehavior);
}
// Methods
@Override
public void makeNoise() {
System.out.println(this.getName() + ", the " + this.getClass().getSimpleName().toLowerCase() + ", meowed.");
}
@Override
public void sleep(){
Random rand = new Random();
int num = rand.nextInt(100);
if (num <= 29){
System.out.println(this.getName() + ", the " + this.getClass().getSimpleName().toLowerCase() + ", meowed.");
} else if(num <=59){
System.out.println(this.getName() + ", the " + this.getClass().getSimpleName().toLowerCase() + ", prowled around.");
} else{
System.out.println(this.getName() + ", the " + this.getClass().getSimpleName().toLowerCase() + ", went to sleep.");
}
}
}
|
/*
* Copyright 2013-2018 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.kms.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Contains information about an entry in a list of grants.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GrantListEntry" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GrantListEntry implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The unique identifier for the customer master key (CMK) to which the grant applies.
* </p>
*/
private String keyId;
/**
* <p>
* The unique identifier for the grant.
* </p>
*/
private String grantId;
/**
* <p>
* The friendly name that identifies the grant. If a name was provided in the <a>CreateGrant</a> request, that name
* is returned. Otherwise this value is null.
* </p>
*/
private String name;
/**
* <p>
* The date and time when the grant was created.
* </p>
*/
private java.util.Date creationDate;
/**
* <p>
* The principal that receives the grant's permissions.
* </p>
*/
private String granteePrincipal;
/**
* <p>
* The principal that can retire the grant.
* </p>
*/
private String retiringPrincipal;
/**
* <p>
* The AWS account under which the grant was issued.
* </p>
*/
private String issuingAccount;
/**
* <p>
* The list of operations permitted by the grant.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> operations;
/**
* <p>
* A list of key-value pairs that must be present in the encryption context of certain subsequent operations that
* the grant allows.
* </p>
*/
private GrantConstraints constraints;
/**
* <p>
* The unique identifier for the customer master key (CMK) to which the grant applies.
* </p>
*
* @param keyId
* The unique identifier for the customer master key (CMK) to which the grant applies.
*/
public void setKeyId(String keyId) {
this.keyId = keyId;
}
/**
* <p>
* The unique identifier for the customer master key (CMK) to which the grant applies.
* </p>
*
* @return The unique identifier for the customer master key (CMK) to which the grant applies.
*/
public String getKeyId() {
return this.keyId;
}
/**
* <p>
* The unique identifier for the customer master key (CMK) to which the grant applies.
* </p>
*
* @param keyId
* The unique identifier for the customer master key (CMK) to which the grant applies.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GrantListEntry withKeyId(String keyId) {
setKeyId(keyId);
return this;
}
/**
* <p>
* The unique identifier for the grant.
* </p>
*
* @param grantId
* The unique identifier for the grant.
*/
public void setGrantId(String grantId) {
this.grantId = grantId;
}
/**
* <p>
* The unique identifier for the grant.
* </p>
*
* @return The unique identifier for the grant.
*/
public String getGrantId() {
return this.grantId;
}
/**
* <p>
* The unique identifier for the grant.
* </p>
*
* @param grantId
* The unique identifier for the grant.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GrantListEntry withGrantId(String grantId) {
setGrantId(grantId);
return this;
}
/**
* <p>
* The friendly name that identifies the grant. If a name was provided in the <a>CreateGrant</a> request, that name
* is returned. Otherwise this value is null.
* </p>
*
* @param name
* The friendly name that identifies the grant. If a name was provided in the <a>CreateGrant</a> request,
* that name is returned. Otherwise this value is null.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The friendly name that identifies the grant. If a name was provided in the <a>CreateGrant</a> request, that name
* is returned. Otherwise this value is null.
* </p>
*
* @return The friendly name that identifies the grant. If a name was provided in the <a>CreateGrant</a> request,
* that name is returned. Otherwise this value is null.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The friendly name that identifies the grant. If a name was provided in the <a>CreateGrant</a> request, that name
* is returned. Otherwise this value is null.
* </p>
*
* @param name
* The friendly name that identifies the grant. If a name was provided in the <a>CreateGrant</a> request,
* that name is returned. Otherwise this value is null.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GrantListEntry withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The date and time when the grant was created.
* </p>
*
* @param creationDate
* The date and time when the grant was created.
*/
public void setCreationDate(java.util.Date creationDate) {
this.creationDate = creationDate;
}
/**
* <p>
* The date and time when the grant was created.
* </p>
*
* @return The date and time when the grant was created.
*/
public java.util.Date getCreationDate() {
return this.creationDate;
}
/**
* <p>
* The date and time when the grant was created.
* </p>
*
* @param creationDate
* The date and time when the grant was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GrantListEntry withCreationDate(java.util.Date creationDate) {
setCreationDate(creationDate);
return this;
}
/**
* <p>
* The principal that receives the grant's permissions.
* </p>
*
* @param granteePrincipal
* The principal that receives the grant's permissions.
*/
public void setGranteePrincipal(String granteePrincipal) {
this.granteePrincipal = granteePrincipal;
}
/**
* <p>
* The principal that receives the grant's permissions.
* </p>
*
* @return The principal that receives the grant's permissions.
*/
public String getGranteePrincipal() {
return this.granteePrincipal;
}
/**
* <p>
* The principal that receives the grant's permissions.
* </p>
*
* @param granteePrincipal
* The principal that receives the grant's permissions.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GrantListEntry withGranteePrincipal(String granteePrincipal) {
setGranteePrincipal(granteePrincipal);
return this;
}
/**
* <p>
* The principal that can retire the grant.
* </p>
*
* @param retiringPrincipal
* The principal that can retire the grant.
*/
public void setRetiringPrincipal(String retiringPrincipal) {
this.retiringPrincipal = retiringPrincipal;
}
/**
* <p>
* The principal that can retire the grant.
* </p>
*
* @return The principal that can retire the grant.
*/
public String getRetiringPrincipal() {
return this.retiringPrincipal;
}
/**
* <p>
* The principal that can retire the grant.
* </p>
*
* @param retiringPrincipal
* The principal that can retire the grant.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GrantListEntry withRetiringPrincipal(String retiringPrincipal) {
setRetiringPrincipal(retiringPrincipal);
return this;
}
/**
* <p>
* The AWS account under which the grant was issued.
* </p>
*
* @param issuingAccount
* The AWS account under which the grant was issued.
*/
public void setIssuingAccount(String issuingAccount) {
this.issuingAccount = issuingAccount;
}
/**
* <p>
* The AWS account under which the grant was issued.
* </p>
*
* @return The AWS account under which the grant was issued.
*/
public String getIssuingAccount() {
return this.issuingAccount;
}
/**
* <p>
* The AWS account under which the grant was issued.
* </p>
*
* @param issuingAccount
* The AWS account under which the grant was issued.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GrantListEntry withIssuingAccount(String issuingAccount) {
setIssuingAccount(issuingAccount);
return this;
}
/**
* <p>
* The list of operations permitted by the grant.
* </p>
*
* @return The list of operations permitted by the grant.
* @see GrantOperation
*/
public java.util.List<String> getOperations() {
if (operations == null) {
operations = new com.amazonaws.internal.SdkInternalList<String>();
}
return operations;
}
/**
* <p>
* The list of operations permitted by the grant.
* </p>
*
* @param operations
* The list of operations permitted by the grant.
* @see GrantOperation
*/
public void setOperations(java.util.Collection<String> operations) {
if (operations == null) {
this.operations = null;
return;
}
this.operations = new com.amazonaws.internal.SdkInternalList<String>(operations);
}
/**
* <p>
* The list of operations permitted by the grant.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setOperations(java.util.Collection)} or {@link #withOperations(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param operations
* The list of operations permitted by the grant.
* @return Returns a reference to this object so that method calls can be chained together.
* @see GrantOperation
*/
public GrantListEntry withOperations(String... operations) {
if (this.operations == null) {
setOperations(new com.amazonaws.internal.SdkInternalList<String>(operations.length));
}
for (String ele : operations) {
this.operations.add(ele);
}
return this;
}
/**
* <p>
* The list of operations permitted by the grant.
* </p>
*
* @param operations
* The list of operations permitted by the grant.
* @return Returns a reference to this object so that method calls can be chained together.
* @see GrantOperation
*/
public GrantListEntry withOperations(java.util.Collection<String> operations) {
setOperations(operations);
return this;
}
/**
* <p>
* The list of operations permitted by the grant.
* </p>
*
* @param operations
* The list of operations permitted by the grant.
* @return Returns a reference to this object so that method calls can be chained together.
* @see GrantOperation
*/
public GrantListEntry withOperations(GrantOperation... operations) {
com.amazonaws.internal.SdkInternalList<String> operationsCopy = new com.amazonaws.internal.SdkInternalList<String>(operations.length);
for (GrantOperation value : operations) {
operationsCopy.add(value.toString());
}
if (getOperations() == null) {
setOperations(operationsCopy);
} else {
getOperations().addAll(operationsCopy);
}
return this;
}
/**
* <p>
* A list of key-value pairs that must be present in the encryption context of certain subsequent operations that
* the grant allows.
* </p>
*
* @param constraints
* A list of key-value pairs that must be present in the encryption context of certain subsequent operations
* that the grant allows.
*/
public void setConstraints(GrantConstraints constraints) {
this.constraints = constraints;
}
/**
* <p>
* A list of key-value pairs that must be present in the encryption context of certain subsequent operations that
* the grant allows.
* </p>
*
* @return A list of key-value pairs that must be present in the encryption context of certain subsequent operations
* that the grant allows.
*/
public GrantConstraints getConstraints() {
return this.constraints;
}
/**
* <p>
* A list of key-value pairs that must be present in the encryption context of certain subsequent operations that
* the grant allows.
* </p>
*
* @param constraints
* A list of key-value pairs that must be present in the encryption context of certain subsequent operations
* that the grant allows.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GrantListEntry withConstraints(GrantConstraints constraints) {
setConstraints(constraints);
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 (getKeyId() != null)
sb.append("KeyId: ").append(getKeyId()).append(",");
if (getGrantId() != null)
sb.append("GrantId: ").append(getGrantId()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getCreationDate() != null)
sb.append("CreationDate: ").append(getCreationDate()).append(",");
if (getGranteePrincipal() != null)
sb.append("GranteePrincipal: ").append(getGranteePrincipal()).append(",");
if (getRetiringPrincipal() != null)
sb.append("RetiringPrincipal: ").append(getRetiringPrincipal()).append(",");
if (getIssuingAccount() != null)
sb.append("IssuingAccount: ").append(getIssuingAccount()).append(",");
if (getOperations() != null)
sb.append("Operations: ").append(getOperations()).append(",");
if (getConstraints() != null)
sb.append("Constraints: ").append(getConstraints());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GrantListEntry == false)
return false;
GrantListEntry other = (GrantListEntry) obj;
if (other.getKeyId() == null ^ this.getKeyId() == null)
return false;
if (other.getKeyId() != null && other.getKeyId().equals(this.getKeyId()) == false)
return false;
if (other.getGrantId() == null ^ this.getGrantId() == null)
return false;
if (other.getGrantId() != null && other.getGrantId().equals(this.getGrantId()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getCreationDate() == null ^ this.getCreationDate() == null)
return false;
if (other.getCreationDate() != null && other.getCreationDate().equals(this.getCreationDate()) == false)
return false;
if (other.getGranteePrincipal() == null ^ this.getGranteePrincipal() == null)
return false;
if (other.getGranteePrincipal() != null && other.getGranteePrincipal().equals(this.getGranteePrincipal()) == false)
return false;
if (other.getRetiringPrincipal() == null ^ this.getRetiringPrincipal() == null)
return false;
if (other.getRetiringPrincipal() != null && other.getRetiringPrincipal().equals(this.getRetiringPrincipal()) == false)
return false;
if (other.getIssuingAccount() == null ^ this.getIssuingAccount() == null)
return false;
if (other.getIssuingAccount() != null && other.getIssuingAccount().equals(this.getIssuingAccount()) == false)
return false;
if (other.getOperations() == null ^ this.getOperations() == null)
return false;
if (other.getOperations() != null && other.getOperations().equals(this.getOperations()) == false)
return false;
if (other.getConstraints() == null ^ this.getConstraints() == null)
return false;
if (other.getConstraints() != null && other.getConstraints().equals(this.getConstraints()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getKeyId() == null) ? 0 : getKeyId().hashCode());
hashCode = prime * hashCode + ((getGrantId() == null) ? 0 : getGrantId().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getCreationDate() == null) ? 0 : getCreationDate().hashCode());
hashCode = prime * hashCode + ((getGranteePrincipal() == null) ? 0 : getGranteePrincipal().hashCode());
hashCode = prime * hashCode + ((getRetiringPrincipal() == null) ? 0 : getRetiringPrincipal().hashCode());
hashCode = prime * hashCode + ((getIssuingAccount() == null) ? 0 : getIssuingAccount().hashCode());
hashCode = prime * hashCode + ((getOperations() == null) ? 0 : getOperations().hashCode());
hashCode = prime * hashCode + ((getConstraints() == null) ? 0 : getConstraints().hashCode());
return hashCode;
}
@Override
public GrantListEntry clone() {
try {
return (GrantListEntry) 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.kms.model.transform.GrantListEntryMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opentelemetry.instrumentation.auto.awssdk.v2_2;
import static io.opentelemetry.javaagent.tooling.ClassLoaderMatcher.hasClassesNamed;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static net.bytebuddy.matcher.ElementMatchers.isStatic;
import static net.bytebuddy.matcher.ElementMatchers.named;
import com.google.auto.service.AutoService;
import io.opentelemetry.javaagent.tooling.Instrumenter;
import java.util.Collections;
import java.util.Map;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
/**
* Separate instrumentation to inject into user configuration overrides. Overrides aren't merged so
* we need to either inject into their override or create our own, but not both.
*/
@AutoService(Instrumenter.class)
public final class AwsClientOverrideInstrumentation extends AbstractAwsClientInstrumentation {
@Override
public ElementMatcher<ClassLoader> classLoaderMatcher() {
// Optimization for expensive typeMatcher.
return hasClassesNamed("software.amazon.awssdk.core.client.config.ClientOverrideConfiguration");
}
@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return named("software.amazon.awssdk.core.client.config.ClientOverrideConfiguration");
}
@Override
public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() {
return Collections.singletonMap(
isMethod().and(isPublic()).and(isStatic()).and(named("builder")),
AwsClientOverrideInstrumentation.class.getName() + "$AwsSdkClientOverrideAdvice");
}
public static class AwsSdkClientOverrideAdvice {
@Advice.OnMethodExit(suppress = Throwable.class)
public static void methodEnter(@Advice.Return ClientOverrideConfiguration.Builder builder) {
TracingExecutionInterceptor.overrideConfiguration(builder);
}
}
}
|
open module datavec.data.image {
requires commons.io;
requires guava;
requires imageio.bmp;
requires imageio.core;
requires imageio.jpeg;
requires imageio.psd;
requires jai.imageio.core;
requires org.bytedeco.ffmpeg;
requires org.bytedeco.hdf5;
requires org.bytedeco.javacpp;
requires org.bytedeco.leptonica;
requires resources;
requires slf4j.api;
requires static android;
requires datavec.api;
requires jackson;
requires java.desktop;
requires nd4j.api;
requires nd4j.common;
requires org.bytedeco.javacv;
requires org.bytedeco.opencv;
exports org.datavec.image.data;
exports org.datavec.image.format;
exports org.datavec.image.loader;
exports org.datavec.image.recordreader;
exports org.datavec.image.recordreader.objdetect;
exports org.datavec.image.recordreader.objdetect.impl;
exports org.datavec.image.transform;
exports org.datavec.image.util;
}
|
/*
* Copyright (C) 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 it.jaschke.alexandria.helpers;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import com.google.android.gms.vision.barcode.Barcode;
/**
* Factory for creating a tracker and associated graphic to be associated with a new barcode. The
* multi-processor uses this factory to create barcode trackers as needed -- one for each barcode.
*/
public class BarcodeTrackerFactory implements MultiProcessor.Factory<Barcode> {
private GraphicOverlay<BarcodeGraphic> mGraphicOverlay;
public BarcodeTrackerFactory(GraphicOverlay<BarcodeGraphic> barcodeGraphicOverlay) {
mGraphicOverlay = barcodeGraphicOverlay;
}
@Override
public Tracker<Barcode> create(Barcode barcode) {
BarcodeGraphic graphic = new BarcodeGraphic(mGraphicOverlay);
return new BarcodeGraphicTracker(mGraphicOverlay, graphic);
}
}
|
/*
* 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.mse.transform.v20190531;
import com.aliyuncs.mse.model.v20190531.DeleteNacosServiceResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class DeleteNacosServiceResponseUnmarshaller {
public static DeleteNacosServiceResponse unmarshall(DeleteNacosServiceResponse deleteNacosServiceResponse, UnmarshallerContext _ctx) {
deleteNacosServiceResponse.setRequestId(_ctx.stringValue("DeleteNacosServiceResponse.RequestId"));
deleteNacosServiceResponse.setHttpStatusCode(_ctx.integerValue("DeleteNacosServiceResponse.HttpStatusCode"));
deleteNacosServiceResponse.setMessage(_ctx.stringValue("DeleteNacosServiceResponse.Message"));
deleteNacosServiceResponse.setCode(_ctx.integerValue("DeleteNacosServiceResponse.Code"));
deleteNacosServiceResponse.setSuccess(_ctx.booleanValue("DeleteNacosServiceResponse.Success"));
deleteNacosServiceResponse.setData(_ctx.stringValue("DeleteNacosServiceResponse.Data"));
return deleteNacosServiceResponse;
}
}
|
package net.swisstech.swissarmyknife.util;
import java.util.Map;
/**
* utilities to work with maps
*
* @since 1.1.4
*/
public final class Maps {
/** private constructor for utility class */
private Maps() {
}
/** @since 2.1.0 */
public static <K, V> Map<K, V> empty(Map<K, V> map) {
if (isNotEmpty(map)) {
throw new IllegalArgumentException("Expected map to be empty but it isn't");
}
return map;
}
/** @since 2.1.0 */
public static <K, V> Map<K, V> notEmpty(Map<K, V> map) {
if (isEmpty(map)) {
throw new IllegalArgumentException("Expected map to not be empty but it is");
}
return map;
}
/** @since 2.1.0 */
public static <K, V> boolean isNotEmpty(Map<K, V> map) {
return !isEmpty(map);
}
public static <K, V> boolean isEmpty(Map<K, V> map) {
return map == null || map.isEmpty();
}
}
|
/*
* Copyright 2015-2020 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.comprehend.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.comprehend.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DocumentClassifierInputDataConfig JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DocumentClassifierInputDataConfigJsonUnmarshaller implements Unmarshaller<DocumentClassifierInputDataConfig, JsonUnmarshallerContext> {
public DocumentClassifierInputDataConfig unmarshall(JsonUnmarshallerContext context) throws Exception {
DocumentClassifierInputDataConfig documentClassifierInputDataConfig = new DocumentClassifierInputDataConfig();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("DataFormat", targetDepth)) {
context.nextToken();
documentClassifierInputDataConfig.setDataFormat(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("S3Uri", targetDepth)) {
context.nextToken();
documentClassifierInputDataConfig.setS3Uri(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("LabelDelimiter", targetDepth)) {
context.nextToken();
documentClassifierInputDataConfig.setLabelDelimiter(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("AugmentedManifests", targetDepth)) {
context.nextToken();
documentClassifierInputDataConfig.setAugmentedManifests(new ListUnmarshaller<AugmentedManifestsListItem>(
AugmentedManifestsListItemJsonUnmarshaller.getInstance())
.unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return documentClassifierInputDataConfig;
}
private static DocumentClassifierInputDataConfigJsonUnmarshaller instance;
public static DocumentClassifierInputDataConfigJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DocumentClassifierInputDataConfigJsonUnmarshaller();
return instance;
}
}
|
package org.mybatis.generator.codegen.mybatis3.xmlmapper;
import static org.mybatis.generator.internal.util.messages.Messages.getString;
import org.mybatis.generator.api.FullyQualifiedTable;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.AbstractXmlGenerator;
import org.mybatis.generator.codegen.XmlConstants;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.BaseColumnListElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.BlobColumnListElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.CountByExampleElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.DeleteByExampleElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.DeleteByPrimaryKeyElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.ExampleWhereClauseElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.InsertElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.InsertSelectiveElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.ResultMapWithBLOBsElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.ResultMapWithoutBLOBsElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.SelectByExampleWithBLOBsElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.SelectByExampleWithoutBLOBsElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.SelectByPrimaryKeyElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.UpdateByExampleSelectiveElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.UpdateByExampleWithBLOBsElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.UpdateByExampleWithoutBLOBsElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.UpdateByPrimaryKeySelectiveElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.UpdateByPrimaryKeyWithBLOBsElementGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.UpdateByPrimaryKeyWithoutBLOBsElementGenerator;
public class XMLMapperGenerator extends AbstractXmlGenerator {
public XMLMapperGenerator() {
super();
}
protected XmlElement getSqlMapElement() {
FullyQualifiedTable table = introspectedTable.getFullyQualifiedTable();
progressCallback.startTask(getString(
"Progress.12", table.toString())); //$NON-NLS-1$
XmlElement answer = new XmlElement("mapper"); //$NON-NLS-1$
String namespace = introspectedTable.getMyBatis3SqlMapNamespace();
answer.addAttribute(new Attribute("namespace", //$NON-NLS-1$
namespace));
context.getCommentGenerator().addRootComment(answer);
addResultMapWithoutBLOBsElement(answer);
addResultMapWithBLOBsElement(answer);
addExampleWhereClauseElement(answer);
addMyBatis3UpdateByExampleWhereClauseElement(answer);
addBaseColumnListElement(answer);
addBlobColumnListElement(answer);
addSelectByExampleWithBLOBsElement(answer);
addSelectByExampleWithoutBLOBsElement(answer);
addSelectByPrimaryKeyElement(answer);
addDeleteByPrimaryKeyElement(answer);
addDeleteByExampleElement(answer);
addInsertElement(answer);
addInsertSelectiveElement(answer);
addCountByExampleElement(answer);
addUpdateByExampleSelectiveElement(answer);
addUpdateByExampleWithBLOBsElement(answer);
addUpdateByExampleWithoutBLOBsElement(answer);
addUpdateByPrimaryKeySelectiveElement(answer);
addUpdateByPrimaryKeyWithBLOBsElement(answer);
addUpdateByPrimaryKeyWithoutBLOBsElement(answer);
return answer;
}
protected void addResultMapWithoutBLOBsElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateBaseResultMap()) {
AbstractXmlElementGenerator elementGenerator = new ResultMapWithoutBLOBsElementGenerator(false);
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addResultMapWithBLOBsElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateResultMapWithBLOBs()) {
AbstractXmlElementGenerator elementGenerator = new ResultMapWithBLOBsElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addExampleWhereClauseElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateSQLExampleWhereClause()) {
AbstractXmlElementGenerator elementGenerator = new ExampleWhereClauseElementGenerator(
false);
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addMyBatis3UpdateByExampleWhereClauseElement(
XmlElement parentElement) {
if (introspectedTable.getRules()
.generateMyBatis3UpdateByExampleWhereClause()) {
AbstractXmlElementGenerator elementGenerator = new ExampleWhereClauseElementGenerator(
true);
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addBaseColumnListElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateBaseColumnList()) {
AbstractXmlElementGenerator elementGenerator = new BaseColumnListElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addBlobColumnListElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateBlobColumnList()) {
AbstractXmlElementGenerator elementGenerator = new BlobColumnListElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addSelectByExampleWithoutBLOBsElement(
XmlElement parentElement) {
if (introspectedTable.getRules().generateSelectByExampleWithoutBLOBs()) {
AbstractXmlElementGenerator elementGenerator = new SelectByExampleWithoutBLOBsElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addSelectByExampleWithBLOBsElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateSelectByExampleWithBLOBs()) {
AbstractXmlElementGenerator elementGenerator = new SelectByExampleWithBLOBsElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addSelectByPrimaryKeyElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateSelectByPrimaryKey()) {
AbstractXmlElementGenerator elementGenerator = new SelectByPrimaryKeyElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addDeleteByExampleElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateDeleteByExample()) {
AbstractXmlElementGenerator elementGenerator = new DeleteByExampleElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addDeleteByPrimaryKeyElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateDeleteByPrimaryKey()) {
AbstractXmlElementGenerator elementGenerator = new DeleteByPrimaryKeyElementGenerator(false);
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addInsertElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateInsert()) {
AbstractXmlElementGenerator elementGenerator = new InsertElementGenerator(false);
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addInsertSelectiveElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateInsertSelective()) {
AbstractXmlElementGenerator elementGenerator = new InsertSelectiveElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addCountByExampleElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateCountByExample()) {
AbstractXmlElementGenerator elementGenerator = new CountByExampleElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addUpdateByExampleSelectiveElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateUpdateByExampleSelective()) {
AbstractXmlElementGenerator elementGenerator = new UpdateByExampleSelectiveElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addUpdateByExampleWithBLOBsElement(XmlElement parentElement) {
if (introspectedTable.getRules().generateUpdateByExampleWithBLOBs()) {
AbstractXmlElementGenerator elementGenerator = new UpdateByExampleWithBLOBsElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addUpdateByExampleWithoutBLOBsElement(
XmlElement parentElement) {
if (introspectedTable.getRules().generateUpdateByExampleWithoutBLOBs()) {
AbstractXmlElementGenerator elementGenerator = new UpdateByExampleWithoutBLOBsElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addUpdateByPrimaryKeySelectiveElement(
XmlElement parentElement) {
if (introspectedTable.getRules().generateUpdateByPrimaryKeySelective()) {
AbstractXmlElementGenerator elementGenerator = new UpdateByPrimaryKeySelectiveElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addUpdateByPrimaryKeyWithBLOBsElement(
XmlElement parentElement) {
if (introspectedTable.getRules().generateUpdateByPrimaryKeyWithBLOBs()) {
AbstractXmlElementGenerator elementGenerator = new UpdateByPrimaryKeyWithBLOBsElementGenerator();
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void addUpdateByPrimaryKeyWithoutBLOBsElement(
XmlElement parentElement) {
if (introspectedTable.getRules()
.generateUpdateByPrimaryKeyWithoutBLOBs()) {
AbstractXmlElementGenerator elementGenerator = new UpdateByPrimaryKeyWithoutBLOBsElementGenerator(false);
initializeAndExecuteGenerator(elementGenerator, parentElement);
}
}
protected void initializeAndExecuteGenerator(
AbstractXmlElementGenerator elementGenerator,
XmlElement parentElement) {
elementGenerator.setContext(context);
elementGenerator.setIntrospectedTable(introspectedTable);
elementGenerator.setProgressCallback(progressCallback);
elementGenerator.setWarnings(warnings);
elementGenerator.addElements(parentElement);
}
@Override
public Document getDocument() {
Document document = new Document(
XmlConstants.MYBATIS3_MAPPER_PUBLIC_ID,
XmlConstants.MYBATIS3_MAPPER_SYSTEM_ID);
document.setRootElement(getSqlMapElement());
if (!context.getPlugins().sqlMapDocumentGenerated(document,
introspectedTable)) {
document = null;
}
return document;
}
}
|
package com.pinktwins.elephant.data;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import org.apache.commons.io.FilenameUtils;
import com.pinktwins.elephant.Elephant;
import com.pinktwins.elephant.data.Note.Meta;
import com.pinktwins.elephant.eventbus.NotebookEvent;
import com.pinktwins.elephant.util.Factory;
import com.pinktwins.elephant.util.IOUtil;
public class Notebook implements Comparable<Notebook> {
private static final Logger LOG = Logger.getLogger(Notebook.class.getName());
private static final String[] POPULATE_EXTENSIONS = { "txt", "rtf", "md", "html", "htm" };
public static final String NAME_ALLNOTES = "All Notes";
public static final String NAME_SEARCH = "Search";
private final long objectCreationTs = System.currentTimeMillis();
private String name = "";
private File folder;
private boolean isSearch, isTagSearch;
private boolean isPreviewDisabled = false;
public List<Note> notes = Factory.newArrayList();
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o instanceof File) {
return folder != null && folder.equals(o);
}
if (o instanceof Notebook) {
Notebook onb = (Notebook) o;
if (folder != null && onb.folder != null) {
return folder.equals(onb.folder);
} else {
return name.equals(onb.name);
}
}
return false;
}
@Override
public int hashCode() {
if (folder == null) {
return new Long(objectCreationTs).hashCode();
}
return folder.hashCode();
}
@Override
public int compareTo(Notebook nb) {
return name().toLowerCase().compareTo(nb.name().toLowerCase());
}
public File folder() {
return folder;
}
public Notebook() {
}
public void populateFromNotebook(Notebook nb) {
notes.addAll(nb.notes);
}
public Notebook(File folder) {
name = folder.getName();
this.folder = folder;
File f = new File(Vault.getInstance().getHome() + File.separator + name + File.separator + ".disablePreview");
isPreviewDisabled = f.exists();
populate();
}
public void setToSearchResultNotebook() {
isSearch = true;
}
public void setToTagResultNotebook() {
isTagSearch = true;
}
public static Notebook createNotebook() throws IOException {
String baseName = Vault.getInstance().getHome() + File.separator + "New notebook";
File f = new File(baseName);
int n = 2;
while (f.exists()) {
f = new File(baseName + " " + n);
n++;
}
if (!f.mkdirs()) {
throw new IOException();
}
return new Notebook(f);
}
public static Notebook getNotebookWithAllNotes() {
Notebook all = new Notebook();
all.name = NAME_ALLNOTES;
for (Notebook nb : Vault.getInstance().getNotebooks()) {
if (!nb.isTrash()) {
all.populateFromNotebook(nb);
}
}
all.sortNotes();
return all;
}
public static Notebook getNotebookWithTag(String tagId, String tagName) {
Notebook nb = new Notebook();
nb.setToTagResultNotebook();
nb.name = "Tag " + tagName;
Set<Note> notes = Search.ssi.notesByTag(tagId);
nb.notes.addAll(notes);
return nb;
}
private boolean isNoteExtension(String ext) {
for (String s : POPULATE_EXTENSIONS) {
if (s.equalsIgnoreCase(ext)) {
return true;
}
}
return false;
}
private void populate() {
boolean didDigest = false;
if (folder != null) {
notes.clear();
for (File f : folder.listFiles()) {
String name = f.getName();
String ext = FilenameUtils.getExtension(f.getName()).toLowerCase();
if (name.charAt(0) != '.' && !name.endsWith("~") && isNoteExtension(ext)) {
try {
if (f.isFile()) {
Note note = new Note(f);
note.setPreviewDisabled(isPreviewDisabled);
notes.add(note);
// Re-digest possibly modified notes.
// Only for when all notes have been indexed already,
// and notes have been modified externally, by sync.
if (Search.ssi.ready()) {
long digestTime = Search.ssi.getDigestTime(f);
if (f.lastModified() != digestTime) {
Search.ssi.digestNote(note, this);
didDigest = true;
}
}
}
} catch (SecurityException e) {
LOG.severe("Fail: " + e);
}
}
}
}
sortNotes();
if (didDigest) {
Search.ssi.commit();
}
}
public void addNote(Note n) {
notes.add(n);
}
public void sortNotes() {
Collections.sort(notes);
if (Elephant.settings.getSortRecentFirst() == false) {
Collections.reverse(notes);
}
}
public void truncNotes(int limit) {
if (notes.size() > limit) {
notes = notes.subList(0, limit);
}
}
public List<Note> getNotes() {
return notes;
}
public String name() {
return name;
}
public void setName(String s) {
name = s;
}
public int count() {
return notes.size();
}
public boolean isTrash() {
return "Trash".equals(name);
}
public boolean isAllNotes() {
return NAME_ALLNOTES.equals(name);
}
public boolean isSearch() {
return isSearch;
}
public boolean isTagSearch() {
return isTagSearch;
}
public boolean isDynamicallyCreatedNotebook() {
return isAllNotes() || isTrash() || isSearch() || isTagSearch();
}
public Note newNote() throws IOException {
if (folder == null) {
throw new IllegalStateException();
}
String defaultFiletype = Elephant.settings.getDefaultFiletype();
if (!defaultFiletype.contains(".")) {
defaultFiletype = "." + defaultFiletype;
}
String fullPath = this.folder.getAbsolutePath() + File.separator + Long.toString(System.currentTimeMillis(), 36) + defaultFiletype;
File f = new File(fullPath);
f.createNewFile();
Note n = new Note(f);
Meta m = n.getMeta();
m.title("Untitled");
m.setCreatedTime();
notes.add(0, n);
new NotebookEvent(NotebookEvent.Kind.noteCreated, f, f).post();
return n;
}
public void deleteNote(Note note) {
if (isTrash()) {
notes.remove(note);
note.delete();
return;
}
File trash = Vault.getInstance().getTrash();
if (folder != null && folder.equals(trash)) {
notes.remove(note);
note.delete();
return;
}
notes.remove(note);
note.moveTo(trash);
}
@SuppressWarnings("unlikely-arg-type")
public Note find(String name) {
File note = new File(folder + File.separator + name);
for (Note n : notes) {
if (n.equals(note)) {
return n;
}
}
return null;
}
public void refresh() {
synchronized (notes) {
populate();
}
}
public boolean rename(String s) {
if (folder == null) {
throw new IllegalStateException();
}
File newFile = new File(folder.getParentFile() + File.separator + s);
try {
if (folder.renameTo(newFile)) {
folder = newFile;
return true;
}
} catch (Exception e) {
LOG.severe("Fail: " + e);
}
return false;
}
public void markNoteSavedTimestamp() {
// write current timestamp to note folder, in file ".lastSaveTs"
File f = new File(folder + File.separator + ".lastSaveTs");
try {
IOUtil.writeFile(f, String.valueOf(System.currentTimeMillis()));
} catch (IOException e) {
LOG.severe("Fail: " + e);
}
}
}
|
/**
*
*/
package com.gap.plan.hystrix.poc.service.impl;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.gap.plan.hystrix.poc.model.DataItem;
import com.gap.plan.hystrix.poc.repository.DataDao;
import com.gap.plan.hystrix.poc.service.DataService;
import lombok.extern.slf4j.Slf4j;
/**
* @author pglebow
*
*/
@Service
@Slf4j
public class DataServiceImpl implements DataService {
@Value("${failureFrequency}")
private Integer failureFrequency;
private int count;
@Autowired
private DataDao dao;
public DataServiceImpl() {
this.count = 0;
log.info("Failure frequency = " + failureFrequency);
}
/*
* (non-Javadoc)
*
* @see com.gap.plan.hystrix.poc.service.DataService#getData()
*/
@Override
public Set<DataItem> getData() {
if (++count % failureFrequency == 0) {
throw new RuntimeException("Fail: Count = " + count);
}
return dao.getData();
}
}
|
package es.upm.miw.spring_zest_backend.business_controllers;
import es.upm.miw.spring_zest_backend.documents.Session;
import es.upm.miw.spring_zest_backend.documents.SessionExercise;
import es.upm.miw.spring_zest_backend.dtos.SessionCreationDto;
import es.upm.miw.spring_zest_backend.dtos.SessionDto;
import es.upm.miw.spring_zest_backend.exceptions.BadRequestException;
import es.upm.miw.spring_zest_backend.exceptions.NotFoundException;
import es.upm.miw.spring_zest_backend.repositories.SessionExerciseReactRepository;
import es.upm.miw.spring_zest_backend.repositories.SessionReactRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
@Controller
public class SessionController {
private static final String SESSION_EXERCISES_NOT_FOUND = "Session exercises: ";
private SessionReactRepository sessionReactRepository;
private SessionExerciseReactRepository sessionExerciseReactRepository;
@Autowired
public SessionController(
SessionReactRepository sessionReactRepository,
SessionExerciseReactRepository sessionExerciseReactRepository) {
this.sessionReactRepository = sessionReactRepository;
this.sessionExerciseReactRepository = sessionExerciseReactRepository;
}
public Mono<SessionDto> readSession(String id) {
return this.sessionReactRepository.findById(id)
.switchIfEmpty(Mono.error(new NotFoundException("Session code (" + id + ")")))
.map(SessionDto::new);
}
public Flux<SessionDto> readAllSessions() {
return this.sessionReactRepository.findAll()
.switchIfEmpty(Flux.error(new BadRequestException("Bad Request")))
.map(SessionDto::new);
}
public Mono<SessionDto> createSession(SessionCreationDto sessionCreationDto) {
Mono<Void> sessionExercises;
Session session = Session.builder()
.title(sessionCreationDto.getTitle())
.start(sessionCreationDto.getStart())
.build();
if (sessionCreationDto.getSessionExerciseIds() == null) {
sessionExercises = Mono.error(new BadRequestException("Session exercise list can't be null"));
} else {
sessionExercises = this.sessionExerciseReactRepository
.findAllById(sessionCreationDto.getSessionExerciseIds())
.switchIfEmpty(Mono.error(
new NotFoundException(SESSION_EXERCISES_NOT_FOUND + sessionCreationDto.getSessionExerciseIds())))
.collectList()
.doOnNext(session::setSessionExercises)
.then();
}
return Mono.when(sessionExercises)
.then(this.sessionReactRepository.save(session).map(SessionDto::new));
}
public Mono<SessionDto> updateSession(String id, SessionCreationDto sessionCreationDto) {
List<SessionExercise> sessionExercises = this.sessionExerciseReactRepository
.findAllById(sessionCreationDto.getSessionExerciseIds())
.switchIfEmpty(Mono.error(
new NotFoundException(SESSION_EXERCISES_NOT_FOUND + sessionCreationDto.getSessionExerciseIds())))
.collectList()
.block();
Mono<Session> session = this.sessionReactRepository.findById(id)
.switchIfEmpty(Mono.error(new NotFoundException("Session id" + id)))
.map(session1 -> {
session1.setTitle(sessionCreationDto.getTitle());
session1.setStart(sessionCreationDto.getStart());
session1.setSessionExercises(sessionExercises);
return session1;
});
return Mono.when(session)
.then(this.sessionReactRepository.saveAll(session).next().map(SessionDto::new));
}
public Mono<Void> deleteSession(String id) {
Mono<Session> session = this.sessionReactRepository.findById(id)
.switchIfEmpty(Mono.error(new NotFoundException(("Session id" + id))));
return Mono.when(session)
.then(this.sessionReactRepository.deleteById(id));
}
}
|
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.microsoft.identity.client;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Base64;
import org.json.JSONException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mockito;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Tests for {@link MsalUtils}.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public final class MsalUtilTest {
static final int EXPECTED_SINGLE_SCOPE_SIZE = 1;
static final int EXPECTED_MULTI_SCOPE_SIZE = 3;
static final int EXPECTED_SET_SIZE = 3;
@Test
public void testNullMessage() {
Assert.assertTrue(MsalUtils.isEmpty(null));
}
@Test
public void testEmptyMessage() {
Assert.assertTrue(MsalUtils.isEmpty(""));
}
@Test
public void testBlankMessage() {
Assert.assertTrue(MsalUtils.isEmpty(" "));
}
@Test
public void testNonEmptyMessage() {
Assert.assertFalse(MsalUtils.isEmpty("Test"));
}
@Test
public void testEmptyEncodeDecodeString() throws UnsupportedEncodingException {
Assert.assertTrue(MsalUtils.urlFormEncode("").equals(""));
Assert.assertTrue(MsalUtils.urlFormDecode("").equals(""));
}
@Test
public void testEncodeDecodeString() throws UnsupportedEncodingException {
Assert.assertTrue(MsalUtils.urlFormEncode("1 $%&=").equals("1+%24%25%26%3D"));
Assert.assertTrue(MsalUtils.urlFormDecode("+%24%25%26%3D").equals(" $%&="));
}
@Test
public void testExtractJsonObjectIntoMapNullJsonFormat() {
try {
MsalUtils.extractJsonObjectIntoMap("test");
Assert.fail("Expect Json exception");
//CHECKSTYLE:OFF: checkstyle:EmptyBlock
} catch (final JSONException e) {
//CHECKSTYLE:ON: checkstyle:EmptyBlock
}
}
@Test
public void testExtractJsonObjectIntoMapHappyPath() {
try {
final Map<String, String> result = MsalUtils.extractJsonObjectIntoMap("{\"JsonKey\":\"JsonValue\"}");
Assert.assertNotNull(result);
Assert.assertTrue(result.get("JsonKey").equals("JsonValue"));
} catch (JSONException e) {
Assert.fail("Unexpected exception.");
}
}
@Test
public void testCalculateExpiresOnNullAndEmptyExpiresIn() {
final Date expiresOnWithNullExpiresIn = MsalUtils.calculateExpiresOn(null);
final Date expiresOnWithEmptyExpiresIn = MsalUtils.calculateExpiresOn("");
final Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.SECOND, MsalUtils.DEFAULT_EXPIRATION_TIME_SEC);
Assert.assertNotNull(expiresOnWithNullExpiresIn);
Assert.assertFalse(expiresOnWithNullExpiresIn.after(calendar.getTime()));
Assert.assertNotNull(expiresOnWithEmptyExpiresIn);
Assert.assertFalse(expiresOnWithEmptyExpiresIn.after(calendar.getTime()));
}
@Test
public void testCalculateExpiresOnWithExpiresIn() {
final String expiresIn = "1000";
final Date expiresOn = MsalUtils.calculateExpiresOn(expiresIn);
final Calendar expectedDate = new GregorianCalendar();
expectedDate.add(Calendar.SECOND, Integer.parseInt(expiresIn));
Assert.assertNotNull(expiresOn);
Assert.assertFalse(expiresOn.after(expectedDate.getTime()));
}
@Test
public void testGetScopeAsSetEmptyAndNullScopes() {
Assert.assertNotNull(MsalUtils.getScopesAsSet("").isEmpty());
Assert.assertTrue(MsalUtils.getScopesAsSet(null).isEmpty());
}
@Test
public void testGetScopesAsSet() {
// Verify that if the input scope array only contains one scope, it's correctly converted into the set.
final String singleScope = "scope";
final Set<String> singleScopeSet = MsalUtils.getScopesAsSet(singleScope);
Assert.assertNotNull(singleScopeSet);
Assert.assertTrue(singleScopeSet.size() == EXPECTED_SINGLE_SCOPE_SIZE);
Assert.assertTrue(singleScopeSet.contains(singleScope));
// Verify if the scopes array has multiple space in the input string, it's corretly converted into the set.
final String singleScopeWithTrailingSpace = singleScope + " ";
final Set<String> singleScopeSetWithTrailingSpace = MsalUtils.getScopesAsSet(singleScopeWithTrailingSpace);
Assert.assertNotNull(singleScopeSetWithTrailingSpace);
Assert.assertTrue(singleScopeSetWithTrailingSpace.size() == EXPECTED_SINGLE_SCOPE_SIZE);
Assert.assertTrue(singleScopeSetWithTrailingSpace.contains(singleScope));
final String multipleScopesInput = "scope1 scope2 scope3 ";
final Set<String> multipleScopesSet = MsalUtils.getScopesAsSet(multipleScopesInput);
Assert.assertNotNull(multipleScopesSet);
Assert.assertTrue(multipleScopesSet.size() == EXPECTED_MULTI_SCOPE_SIZE);
Assert.assertTrue(multipleScopesSet.contains("scope1"));
Assert.assertTrue(multipleScopesSet.contains("scope2"));
Assert.assertTrue(multipleScopesSet.contains("scope3"));
}
@Test
public void testHasCustomTabRedirectActivity() {
final Context mockedContext = Mockito.mock(Context.class);
final String url = "https://login.microsoftonline.com";
// If package manager is null
Mockito.when(mockedContext.getPackageManager()).thenReturn(null);
Assert.assertFalse(MsalUtils.hasCustomTabRedirectActivity(mockedContext, url));
// resolveInfo list is empty
final PackageManager mockedPackageManager = Mockito.mock(PackageManager.class);
Mockito.when(mockedContext.getPackageManager()).thenReturn(mockedPackageManager);
Mockito.when(mockedPackageManager.queryIntentActivities(Matchers.any(Intent.class),
Matchers.eq(PackageManager.GET_RESOLVED_FILTER))).thenReturn(Collections.<ResolveInfo>emptyList());
Assert.assertFalse(MsalUtils.hasCustomTabRedirectActivity(mockedContext, url));
// resolve info list contains single item, and the activity name is BrowserTabActivity class name.
final List<ResolveInfo> resolveInfos = new ArrayList<>();
Mockito.when(mockedPackageManager.queryIntentActivities(Matchers.any(Intent.class),
Matchers.eq(PackageManager.GET_RESOLVED_FILTER))).thenReturn(resolveInfos);
final ResolveInfo mockedResolveInfo1 = Mockito.mock(ResolveInfo.class);
final ActivityInfo mockedActivityInfo1 = Mockito.mock(ActivityInfo.class);
mockedActivityInfo1.name = BrowserTabActivity.class.getName();
mockedResolveInfo1.activityInfo = mockedActivityInfo1;
resolveInfos.add(mockedResolveInfo1);
Assert.assertTrue(MsalUtils.hasCustomTabRedirectActivity(mockedContext, url));
// resolve info list contains multiple items
final ResolveInfo mockedResolveInfo2 = Mockito.mock(ResolveInfo.class);
final ActivityInfo mockedActivityInfo2 = Mockito.mock(ActivityInfo.class);
mockedActivityInfo2.name = "some other class";
mockedResolveInfo2.activityInfo = mockedActivityInfo2;
resolveInfos.add(mockedResolveInfo2);
Assert.assertFalse(MsalUtils.hasCustomTabRedirectActivity(mockedContext, url));
}
@Test
public void getChromePackageWithCustomTabSupport() {
final Context mockedContext = Mockito.mock(Context.class);
// If package manager is null
Mockito.when(mockedContext.getPackageManager()).thenReturn(null);
Assert.assertNull(MsalUtils.getChromePackageWithCustomTabSupport(mockedContext));
final PackageManager mockedPackageManager = Mockito.mock(PackageManager.class);
// if not custom tab service exists
Mockito.when(mockedPackageManager.queryIntentServices(Matchers.any(Intent.class),
Matchers.eq(0))).thenReturn(null);
Assert.assertNull(MsalUtils.getChromePackageWithCustomTabSupport(mockedContext));
final List<ResolveInfo> resolvedInfos = new ArrayList<>();
Mockito.when(mockedContext.getPackageManager()).thenReturn(mockedPackageManager);
Mockito.when(mockedPackageManager.queryIntentServices(Matchers.any(Intent.class),
Matchers.eq(0))).thenReturn(resolvedInfos);
// If custom tab service exists, but it's not belonging to chrome package
final ResolveInfo mockedResolveInfo = Mockito.mock(ResolveInfo.class);
final ServiceInfo mockedServiceInfo = Mockito.mock(ServiceInfo.class);
mockedServiceInfo.packageName = "some package but not chrome";
mockedResolveInfo.serviceInfo = mockedServiceInfo;
resolvedInfos.add(mockedResolveInfo);
Assert.assertNull(MsalUtils.getChromePackageWithCustomTabSupport(mockedContext));
// If multiple packages have custom tab support, and chrome package also has the support
final ResolveInfo mockedResolveInfoForChrome = Mockito.mock(ResolveInfo.class);
final ServiceInfo mockedServiceInfoForChrome = Mockito.mock(ServiceInfo.class);
mockedServiceInfoForChrome.packageName = MsalUtils.CHROME_PACKAGE;
mockedResolveInfoForChrome.serviceInfo = mockedServiceInfoForChrome;
resolvedInfos.add(mockedResolveInfoForChrome);
final String chromePackageNameWithCustomTabSupport = MsalUtils.getChromePackageWithCustomTabSupport(mockedContext);
Assert.assertNotNull(chromePackageNameWithCustomTabSupport);
Assert.assertTrue(chromePackageNameWithCustomTabSupport.equals(MsalUtils.CHROME_PACKAGE));
}
@Test
public void testGetChromePackage() throws PackageManager.NameNotFoundException {
final Context mockedContext = Mockito.mock(Context.class);
// package manager is null
Mockito.when(mockedContext.getPackageManager()).thenReturn(null);
Assert.assertNull(MsalUtils.getChromePackageWithCustomTabSupport(mockedContext));
// no chrome package exists
final PackageManager mockedPackageManager = Mockito.mock(PackageManager.class);
Mockito.when(mockedContext.getPackageManager()).thenReturn(mockedPackageManager);
Mockito.when(mockedPackageManager.getPackageInfo(Matchers.refEq(MsalUtils.CHROME_PACKAGE),
Matchers.eq(PackageManager.GET_ACTIVITIES))).thenThrow(PackageManager.NameNotFoundException.class);
Assert.assertNull(MsalUtils.getChromePackage(mockedContext));
//Chrome package exists in the device but is disabled
final PackageInfo mockedPackageInfo = Mockito.mock(PackageInfo.class);
final ApplicationInfo mockedApplicationInfo = Mockito.mock(ApplicationInfo.class);
Mockito.when(mockedPackageManager.getPackageInfo(Matchers.refEq(MsalUtils.CHROME_PACKAGE),
Matchers.eq(PackageManager.GET_ACTIVITIES))).thenReturn(mockedPackageInfo);
mockedPackageInfo.applicationInfo = mockedApplicationInfo;
mockedApplicationInfo.enabled = false;
Assert.assertNull(MsalUtils.getChromePackage(mockedContext));
// The three chrome package all exists on the device, return the stable chrome package name.
mockedApplicationInfo.enabled = true;
Assert.assertTrue(MsalUtils.getChromePackage(mockedContext).equals(MsalUtils.CHROME_PACKAGE));
}
@Test
public void testDecodeUrlToMap() {
// url is null or empty
Assert.assertTrue(MsalUtils.decodeUrlToMap(null, " ").isEmpty());
Assert.assertTrue(MsalUtils.decodeUrlToMap("", "").isEmpty());
// delimiter is null
Assert.assertTrue(MsalUtils.decodeUrlToMap("some url", null).isEmpty());
final String urlToDecode = "a=b&c=d";
final Map<String, String> result = MsalUtils.decodeUrlToMap(urlToDecode, "&");
Assert.assertNotNull(result);
Assert.assertTrue(result.size() == 2);
Assert.assertTrue(result.get("a").equals("b"));
Assert.assertTrue(result.get("c").equals("d"));
}
@Test
public void testConvertSetToStringEmptyOrNullSetOrDelimiter() {
Assert.assertTrue(MsalUtils.convertSetToString(null, " ").equals(""));
Assert.assertTrue(MsalUtils.convertSetToString(Collections.EMPTY_SET, " ").equals(""));
final Set<String> set = new HashSet<>();
set.add("some string");
Assert.assertTrue(MsalUtils.convertSetToString(set, null).equals(""));
}
@Test
public void testConvertSetToStringHappyPath() {
final List<String> input = new ArrayList<>();
input.add("scope1");
input.add("scope2");
final String result = MsalUtils.convertSetToString(new HashSet<>(input), " ");
Assert.assertTrue(result.equals("scope1 scope2"));
}
@Test
public void testConvertStringToSet() {
final String scope1 = "scope1";
final String[] scopes = new String[]{" ", scope1, " "};
final Set<String> convertedScope = MsalUtils.convertArrayToSet(scopes);
Assert.assertNotNull(convertedScope);
Assert.assertTrue(convertedScope.size() == 1);
Assert.assertTrue(convertedScope.iterator().next().equalsIgnoreCase(scope1));
final String scope2 = "scope2";
final String scope3 = "scope3";
final String[] scopesTest2 = new String[]{scope1, scope2, scope3};
final Set<String> convertedScope2 = MsalUtils.convertArrayToSet(scopesTest2);
Assert.assertNotNull(convertedScope2);
Assert.assertTrue(convertedScope2.size() == EXPECTED_SET_SIZE);
Assert.assertTrue(convertedScope2.contains(scope1));
Assert.assertTrue(convertedScope2.contains(scope2));
Assert.assertTrue(convertedScope2.contains(scope3));
}
@Test
public void testBase64Encode() {
String stringToEncode = "a+b@c.com";
Assert.assertTrue(base64Decode(MsalUtils.base64UrlEncodeToString(stringToEncode)).equals(stringToEncode));
stringToEncode = "a$c@b.com";
Assert.assertTrue(base64Decode(MsalUtils.base64UrlEncodeToString(stringToEncode)).equals(stringToEncode));
}
@Test
public void testAppendQueryParam() throws UnsupportedEncodingException {
final String authorityUrl = "https://login.microsoftonline.com/common/v2/authorize?p=testpolicy";
final Map<String, String> queryParamteters = new HashMap<>();
queryParamteters.put("qp1", "someqp1");
final String appendedAuthority = MsalUtils.appendQueryParameterToUrl(authorityUrl, queryParamteters);
Assert.assertTrue(appendedAuthority.equals(
"https://login.microsoftonline.com/common/v2/authorize?p=testpolicy&qp1=someqp1"));
}
@Test
public void testAppendQueryParamWithQueryStringDelimiter() throws UnsupportedEncodingException {
final String authorityUrl = "https://login.microsoftonline.com/common/v2/authorize?p=testpolicy&";
final Map<String, String> queryParamteters = new HashMap<>();
queryParamteters.put("qp1", "someqp1");
final String appendedAuthority = MsalUtils.appendQueryParameterToUrl(authorityUrl, queryParamteters);
Assert.assertTrue(appendedAuthority.equals(
"https://login.microsoftonline.com/common/v2/authorize?p=testpolicy&qp1=someqp1"));
}
private String base64Decode(final String encodedString) {
return new String(Base64.decode(encodedString.getBytes(Charset.forName(MsalUtils.ENCODING_UTF8)), Base64.NO_PADDING | Base64.URL_SAFE));
}
}
|
package org.labkey.wnprc_ehr.dataentry.forms.ResearchUltrasounds;
import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection;
import org.labkey.api.ehr.dataentry.DataEntryFormContext;
import org.labkey.api.ehr.dataentry.FormSection;
import org.labkey.api.ehr.dataentry.TaskFormSection;
import org.labkey.api.module.Module;
import org.labkey.api.view.template.ClientDependency;
import org.labkey.wnprc_ehr.WNPRCConstants;
import org.labkey.wnprc_ehr.dataentry.forms.ResearchUltrasounds.FormSections.ResearchUltrasoundsFormSection;
import org.labkey.wnprc_ehr.dataentry.forms.ResearchUltrasounds.FormSections.ResearchUltrasoundsInstructionsFormSection;
import org.labkey.wnprc_ehr.dataentry.forms.ResearchUltrasounds.FormSections.ResearchUltrasoundsRestraintsFormSection;
import org.labkey.wnprc_ehr.dataentry.forms.ResearchUltrasounds.FormSections.UltrasoundReviewFormSection;
import org.labkey.wnprc_ehr.dataentry.generics.forms.SimpleTaskForm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ResearchUltrasoundsReviewForm extends SimpleTaskForm
{
public static final String NAME = "Research Ultrasounds Review";
public ResearchUltrasoundsReviewForm(DataEntryFormContext ctx, Module owner) {
super(ctx, owner, NAME, NAME, WNPRCConstants.DataEntrySections.CLINICAL_SPI, Arrays.asList(
new TaskFormSection(),
new AnimalDetailsFormSection(),
new ResearchUltrasoundsInstructionsFormSection(),
new ResearchUltrasoundsFormSection(),
new ResearchUltrasoundsRestraintsFormSection(),
new UltrasoundReviewFormSection()
));
for (FormSection section: getFormSections()) {
section.addConfigSource("ResearchUltrasounds");
}
setStoreCollectionClass("WNPRC.ext.data.ResearchUltrasoundsStoreCollection");
addClientDependency(ClientDependency.supplierFromPath("wnprc_ehr/model/sources/ResearchUltrasounds.js"));
addClientDependency(ClientDependency.supplierFromPath("wnprc_ehr/ext4/data/SingleAnimal/ResearchUltrasoundsServerStore.js"));
addClientDependency(ClientDependency.supplierFromPath("wnprc_ehr/ext4/data/SingleAnimal/ResearchUltrasoundsStoreCollection.js"));
addClientDependency(ClientDependency.supplierFromPath("wnprc_ehr/ext4/components/fields/PregnancyIdField.js"));
}
@Override
protected List<String> getButtonConfigs()
{
List<String> defaultButtons = new ArrayList<>();
defaultButtons.add("WNPRC_CANCEL");
defaultButtons.add("WNPRC_SAVE_AND_EXIT");
defaultButtons.add("WNPRC_SUBMIT_FINAL");
return defaultButtons;
}
@Override
protected List<String> getMoreActionButtonConfigs() {
List<String> defaultButtons = new ArrayList<>();
//defaultButtons.add("WNPRC_FIX_QCSTATE");
//defaultButtons.add("DISCARD");
defaultButtons.add("VALIDATEALL");
return defaultButtons;
}
}
|
package wannabit.io.cosmostaion.fragment.chains.osmosis;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import java.math.BigDecimal;
import wannabit.io.cosmostaion.R;
import wannabit.io.cosmostaion.activities.chains.osmosis.SwapActivity;
import wannabit.io.cosmostaion.base.BaseFragment;
import wannabit.io.cosmostaion.base.IRefreshTabListener;
import wannabit.io.cosmostaion.utils.WDp;
import wannabit.io.cosmostaion.utils.WUtil;
public class CoinSwapStep3Fragment extends BaseFragment implements View.OnClickListener, IRefreshTabListener {
private TextView mFeeAmount;
private TextView mFeeAmountSymbol;
private TextView mSwapFee;
private TextView mSwapInAmount, mSwapInAmountSymbol;
private TextView mSwapOutAmount, mSwapOutAmountSymbol;
private RelativeLayout mSlippageLayer;
private TextView mMemo;
private int mDpDecimal = 6, mInputCoinDecimal = 6, mOutputCoinDecimal = 6;
private Button mBeforeBtn, mConfirmBtn;
public static CoinSwapStep3Fragment newInstance(Bundle bundle) {
CoinSwapStep3Fragment fragment = new CoinSwapStep3Fragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_swap_step3, container, false);
mFeeAmount = rootView.findViewById(R.id.swap_fee_amount);
mFeeAmountSymbol = rootView.findViewById(R.id.swap_fee_amount_symbol);
mSwapFee = rootView.findViewById(R.id.swap_fee);
mSwapInAmount = rootView.findViewById(R.id.swap_in_amount);
mSwapInAmountSymbol = rootView.findViewById(R.id.swap_in_amount_symbol);
mSwapOutAmount = rootView.findViewById(R.id.swap_out_amount);
mSwapOutAmountSymbol = rootView.findViewById(R.id.swap_out_amount_symbol);
mSlippageLayer = rootView.findViewById(R.id.slippage_layer);
mMemo = rootView.findViewById(R.id.memo);
mBeforeBtn = rootView.findViewById(R.id.btn_before);
mConfirmBtn = rootView.findViewById(R.id.confirmButton);
WDp.DpMainDenom(getSActivity().getAccount().baseChain, mFeeAmountSymbol);
mBeforeBtn.setOnClickListener(this);
mConfirmBtn.setOnClickListener(this);
return rootView;
}
@Override
public void onRefreshTab() {
mSlippageLayer.setVisibility(View.VISIBLE);
mDpDecimal = getSActivity().getBaseChain().getDivideDecimal();
mInputCoinDecimal = WUtil.getOsmosisCoinDecimal(getBaseDao(), getSActivity().mInputDenom);
mOutputCoinDecimal = WUtil.getOsmosisCoinDecimal(getBaseDao(), getSActivity().mOutputDenom);
BigDecimal feeAmount = new BigDecimal(getSActivity().mTxFee.amount.get(0).amount);
BigDecimal swapFee = new BigDecimal(getSActivity().mOsmosisPool.getPoolParams().getSwapFee());
mFeeAmount.setText(WDp.getDpAmount2(feeAmount, mDpDecimal, mDpDecimal));
mSwapFee.setText(WDp.getPercentDp(swapFee.movePointLeft(16)));
WDp.showCoinDp(getBaseDao(), getSActivity().mSwapInCoin, mSwapInAmountSymbol, mSwapInAmount, getSActivity().getBaseChain());
WDp.showCoinDp(getBaseDao(), getSActivity().mSwapOutCoin, mSwapOutAmountSymbol, mSwapOutAmount, getSActivity().getBaseChain());
mMemo.setText(getSActivity().mTxMemo);
}
@Override
public void onClick(View v) {
if (v.equals(mBeforeBtn)) {
getSActivity().onBeforeStep();
} else if (v.equals(mConfirmBtn)) {
getSActivity().onStartSwap();
}
}
private SwapActivity getSActivity() {
return (SwapActivity) getBaseActivity();
}
}
|
/**
* Copyright 2016 Nikita Koksharov
*
* 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.redisson;
import static org.redisson.client.protocol.RedisCommands.EVAL_OBJECT;
import static org.redisson.client.protocol.RedisCommands.LPOP;
import static org.redisson.client.protocol.RedisCommands.LPUSH_BOOLEAN;
import static org.redisson.client.protocol.RedisCommands.RPUSH_BOOLEAN;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Set;
import org.redisson.client.codec.Codec;
import org.redisson.client.protocol.RedisCommand;
import org.redisson.client.protocol.RedisCommand.ValueType;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.convertor.BooleanNumberReplayConvertor;
import org.redisson.client.protocol.convertor.BooleanReplayConvertor;
import org.redisson.client.protocol.convertor.Convertor;
import org.redisson.client.protocol.convertor.IntegerReplayConvertor;
import org.redisson.client.protocol.decoder.ObjectSetReplayDecoder;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.core.RList;
import io.netty.util.concurrent.Future;
/**
* List based Multimap Cache values holder
*
* @author Nikita Koksharov
*
* @param <V> the type of elements held in this collection
*/
public class RedissonListMultimapValues<V> extends RedissonExpirable implements RList<V> {
private static final RedisCommand<Integer> LAST_INDEX = new RedisCommand<Integer>("EVAL", new IntegerReplayConvertor(), 4, Arrays.asList(ValueType.MAP_KEY, ValueType.MAP_VALUE));
private static final RedisCommand<Integer> EVAL_SIZE = new RedisCommand<Integer>("EVAL", new IntegerReplayConvertor(), 6, ValueType.MAP_KEY);
private static final RedisCommand<Integer> EVAL_GET = new RedisCommand<Integer>("EVAL", 7, ValueType.MAP_KEY);
private static final RedisCommand<Set<Object>> EVAL_READALL = new RedisCommand<Set<Object>>("EVAL", new ObjectSetReplayDecoder<Object>(), 6, ValueType.MAP_KEY);
private static final RedisCommand<Boolean> EVAL_CONTAINS_VALUE = new RedisCommand<Boolean>("EVAL", new BooleanReplayConvertor(), 7, Arrays.asList(ValueType.MAP_KEY, ValueType.MAP_VALUE));
private static final RedisCommand<Boolean> EVAL_CONTAINS_ALL_WITH_VALUES = new RedisCommand<Boolean>("EVAL", new BooleanReplayConvertor(), 7, ValueType.OBJECTS);
public static final RedisCommand<Boolean> EVAL_BOOLEAN_ARGS2 = new RedisCommand<Boolean>("EVAL", new BooleanReplayConvertor(), 5, ValueType.OBJECTS);
private final Object key;
private final String timeoutSetName;
public RedissonListMultimapValues(Codec codec, CommandAsyncExecutor commandExecutor, String name, String timeoutSetName, Object key) {
super(codec, commandExecutor, name);
this.timeoutSetName = timeoutSetName;
this.key = key;
}
@Override
public int size() {
return get(sizeAsync());
}
public Future<Integer> sizeAsync() {
return commandExecutor.evalReadAsync(getName(), codec, EVAL_SIZE,
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[2]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore) "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return 0;"
+ "end; "
+ "return redis.call('llen', KEYS[2]);",
Arrays.<Object>asList(timeoutSetName, getName()), System.currentTimeMillis(), key);
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean contains(Object o) {
return get(containsAsync(o));
}
@Override
public Iterator<V> iterator() {
return listIterator();
}
@Override
public Object[] toArray() {
List<V> list = readAll();
return list.toArray();
}
@Override
public List<V> readAll() {
return get(readAllAsync());
}
@Override
public Future<List<V>> readAllAsync() {
return commandExecutor.evalReadAsync(getName(), codec, EVAL_READALL,
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[2]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore) "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return {};"
+ "end; "
+ "return redis.call('lrange', KEYS[2], 0, -1);",
Arrays.<Object>asList(timeoutSetName, getName()), System.currentTimeMillis(), key);
}
@Override
public <T> T[] toArray(T[] a) {
List<V> list = readAll();
return list.toArray(a);
}
@Override
public boolean add(V e) {
return get(addAsync(e));
}
@Override
public Future<Boolean> addAsync(V e) {
return commandExecutor.writeAsync(getName(), codec, RPUSH_BOOLEAN, getName(), e);
}
@Override
public boolean remove(Object o) {
return get(removeAsync(o));
}
@Override
public Future<Boolean> removeAsync(Object o) {
return removeAsync(o, 1);
}
protected Future<Boolean> removeAsync(Object o, int count) {
return commandExecutor.evalWriteAsync(getName(), codec, EVAL_CONTAINS_VALUE,
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[3]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore) "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return 0;"
+ "end; "
+ "return redis.call('lrem', KEYS[2], ARGV[2], ARGV[4]) > 0 and 1 or 0;",
Arrays.<Object>asList(timeoutSetName, getName()), System.currentTimeMillis(), count, key, o);
}
protected boolean remove(Object o, int count) {
return get(removeAsync(o, count));
}
@Override
public Future<Boolean> containsAllAsync(Collection<?> c) {
List<Object> args = new ArrayList<Object>(c.size() + 2);
try {
byte[] keyState = codec.getMapKeyEncoder().encode(key);
args.add(System.currentTimeMillis());
args.add(keyState);
args.addAll(c);
} catch (IOException e) {
throw new RuntimeException(e);
}
return commandExecutor.evalReadAsync(getName(), codec, EVAL_CONTAINS_ALL_WITH_VALUES,
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[2]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore) "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return 0;"
+ "end; " +
"local items = redis.call('lrange', KEYS[2], 0, -1);" +
"for i = 1, #items, 1 do " +
"for j = 2, #ARGV, 1 do "
+ "if ARGV[j] == items[i] "
+ "then table.remove(ARGV, j) end "
+ "end; "
+ "end;"
+ "return #ARGV == 2 and 1 or 0; ",
Arrays.<Object>asList(timeoutSetName, getName()), args.toArray());
}
@Override
public boolean containsAll(Collection<?> c) {
return get(containsAllAsync(c));
}
@Override
public boolean addAll(Collection<? extends V> c) {
return get(addAllAsync(c));
}
@Override
public Future<Boolean> addAllAsync(final Collection<? extends V> c) {
if (c.isEmpty()) {
return newSucceededFuture(false);
}
List<Object> args = new ArrayList<Object>(c.size() + 1);
args.add(getName());
args.addAll(c);
return commandExecutor.writeAsync(getName(), codec, RPUSH_BOOLEAN, args.toArray());
}
public Future<Boolean> addAllAsync(int index, Collection<? extends V> coll) {
if (index < 0) {
throw new IndexOutOfBoundsException("index: " + index);
}
if (coll.isEmpty()) {
return newSucceededFuture(false);
}
if (index == 0) { // prepend elements to list
List<Object> elements = new ArrayList<Object>(coll);
Collections.reverse(elements);
elements.add(0, getName());
return commandExecutor.writeAsync(getName(), codec, LPUSH_BOOLEAN, elements.toArray());
}
List<Object> args = new ArrayList<Object>(coll.size() + 1);
args.add(index);
args.addAll(coll);
return commandExecutor.evalWriteAsync(getName(), codec, EVAL_BOOLEAN_ARGS2,
"local ind = table.remove(ARGV, 1); " + // index is the first parameter
"local size = redis.call('llen', KEYS[1]); " +
"assert(tonumber(ind) <= size, 'index: ' .. ind .. ' but current size: ' .. size); " +
"local tail = redis.call('lrange', KEYS[1], ind, -1); " +
"redis.call('ltrim', KEYS[1], 0, ind - 1); " +
"for i=1, #ARGV, 5000 do "
+ "redis.call('rpush', KEYS[1], unpack(ARGV, i, math.min(i+4999, #ARGV))); "
+ "end " +
"if #tail > 0 then " +
"for i=1, #tail, 5000 do "
+ "redis.call('rpush', KEYS[1], unpack(tail, i, math.min(i+4999, #tail))); "
+ "end "
+ "end;" +
"return 1;",
Collections.<Object>singletonList(getName()), args.toArray());
}
@Override
public boolean addAll(int index, Collection<? extends V> coll) {
return get(addAllAsync(index, coll));
}
@Override
public Future<Boolean> removeAllAsync(Collection<?> c) {
List<Object> args = new ArrayList<Object>(c.size() + 2);
try {
byte[] keyState = codec.getMapKeyEncoder().encode(key);
args.add(System.currentTimeMillis());
args.add(keyState);
args.addAll(c);
} catch (IOException e) {
throw new RuntimeException(e);
}
return commandExecutor.evalWriteAsync(getName(), codec, EVAL_CONTAINS_ALL_WITH_VALUES,
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[2]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore) "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return 0;"
+ "end; " +
"local v = 0 " +
"for i = 2, #ARGV, 1 do "
+ "if redis.call('lrem', KEYS[2], 0, ARGV[i]) == 1 "
+ "then v = 1 end "
+"end "
+ "return v ",
Arrays.<Object>asList(timeoutSetName, getName()), args.toArray());
}
@Override
public boolean removeAll(Collection<?> c) {
return get(removeAllAsync(c));
}
@Override
public boolean retainAll(Collection<?> c) {
return get(retainAllAsync(c));
}
@Override
public Future<Boolean> retainAllAsync(Collection<?> c) {
List<Object> args = new ArrayList<Object>(c.size() + 2);
try {
byte[] keyState = codec.getMapKeyEncoder().encode(key);
args.add(System.currentTimeMillis());
args.add(keyState);
args.addAll(c);
} catch (IOException e) {
throw new RuntimeException(e);
}
return commandExecutor.evalWriteAsync(getName(), codec, EVAL_CONTAINS_ALL_WITH_VALUES,
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[2]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore) "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return 0;"
+ "end; " +
"local changed = 0; " +
"local s = redis.call('lrange', KEYS[2], 0, -1); "
+ "local i = 1; "
+ "while i <= #s do "
+ "local element = s[i]; "
+ "local isInAgrs = false; "
+ "for j = 2, #ARGV, 1 do "
+ "if ARGV[j] == element then "
+ "isInAgrs = true; "
+ "break; "
+ "end; "
+ "end; "
+ "if isInAgrs == false then "
+ "redis.call('lrem', KEYS[2], 0, element); "
+ "changed = 1; "
+ "end; "
+ "i = i + 1; "
+ "end; "
+ "return changed; ",
Arrays.<Object>asList(timeoutSetName, getName()), args.toArray());
}
@Override
public void clear() {
delete();
}
@Override
public Future<V> getAsync(int index) {
return commandExecutor.evalReadAsync(getName(), codec, EVAL_GET,
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[3]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore); "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return nil;"
+ "end; "
+ "return redis.call('lindex', KEYS[2], ARGV[2]);",
Arrays.<Object>asList(timeoutSetName, getName()), System.currentTimeMillis(), index, key);
}
@Override
public V get(int index) {
checkIndex(index);
return getValue(index);
}
V getValue(int index) {
return get(getAsync(index));
}
private void checkIndex(int index) {
int size = size();
if (!isInRange(index, size))
throw new IndexOutOfBoundsException("index: " + index + " but current size: "+ size);
}
private boolean isInRange(int index, int size) {
return index >= 0 && index < size;
}
@Override
public V set(int index, V element) {
checkIndex(index);
return get(setAsync(index, element));
}
@Override
public Future<V> setAsync(int index, V element) {
return commandExecutor.evalWriteAsync(getName(), codec, new RedisCommand<Object>("EVAL", 5),
"local v = redis.call('lindex', KEYS[1], ARGV[1]); " +
"redis.call('lset', KEYS[1], ARGV[1], ARGV[2]); " +
"return v",
Collections.<Object>singletonList(getName()), index, element);
}
@Override
public void fastSet(int index, V element) {
get(fastSetAsync(index, element));
}
@Override
public Future<Void> fastSetAsync(int index, V element) {
return commandExecutor.writeAsync(getName(), codec, RedisCommands.LSET, getName(), index, element);
}
@Override
public void add(int index, V element) {
addAll(index, Collections.singleton(element));
}
@Override
public V remove(int index) {
if (index == 0) {
Future<V> f = commandExecutor.writeAsync(getName(), codec, LPOP, getName());
return get(f);
}
Future<V> f = commandExecutor.evalWriteAsync(getName(), codec, EVAL_OBJECT,
"local v = redis.call('lindex', KEYS[1], ARGV[1]); " +
"redis.call('lset', KEYS[1], ARGV[1], 'DELETED_BY_REDISSON');" +
"redis.call('lrem', KEYS[1], 1, 'DELETED_BY_REDISSON');" +
"return v",
Collections.<Object>singletonList(getName()), index);
return get(f);
}
@Override
public void fastRemove(int index) {
get(fastRemoveAsync(index));
}
@Override
public Future<Void> fastRemoveAsync(int index) {
return commandExecutor.evalWriteAsync(getName(), codec, RedisCommands.EVAL_VOID,
"redis.call('lset', KEYS[1], ARGV[1], 'DELETED_BY_REDISSON');" +
"redis.call('lrem', KEYS[1], 1, 'DELETED_BY_REDISSON');",
Collections.<Object>singletonList(getName()), index);
}
@Override
public int indexOf(Object o) {
return get(indexOfAsync(o));
}
@Override
public Future<Boolean> containsAsync(Object o) {
return indexOfAsync(o, new BooleanNumberReplayConvertor(-1L));
}
private <R> Future<R> indexOfAsync(Object o, Convertor<R> convertor) {
return commandExecutor.evalReadAsync(getName(), codec, new RedisCommand<R>("EVAL", convertor, 6, Arrays.asList(ValueType.MAP_KEY, ValueType.MAP_VALUE)),
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[2]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore); "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return -1;"
+ "end; " +
"local items = redis.call('lrange', KEYS[2], 0, -1); " +
"for i=1,#items do " +
"if items[i] == ARGV[3] then " +
"return i - 1; " +
"end; " +
"end; " +
"return -1;",
Arrays.<Object>asList(timeoutSetName, getName()), System.currentTimeMillis(), key, o);
}
@Override
public Future<Integer> indexOfAsync(Object o) {
return indexOfAsync(o, new IntegerReplayConvertor());
}
@Override
public int lastIndexOf(Object o) {
return get(lastIndexOfAsync(o));
}
@Override
public Future<Integer> lastIndexOfAsync(Object o) {
return commandExecutor.evalReadAsync(getName(), codec, LAST_INDEX,
"local expireDate = 92233720368547758; " +
"local expireDateScore = redis.call('zscore', KEYS[1], ARGV[2]); "
+ "if expireDateScore ~= false then "
+ "expireDate = tonumber(expireDateScore); "
+ "end; "
+ "if expireDate <= tonumber(ARGV[1]) then "
+ "return -1;"
+ "end; " +
"local items = redis.call('lrange', KEYS[1], 0, -1) " +
"for i = #items, 1, -1 do " +
"if items[i] == ARGV[1] then " +
"return i - 1 " +
"end " +
"end " +
"return -1",
Arrays.<Object>asList(timeoutSetName, getName()), System.currentTimeMillis(), key, o);
}
@Override
public void trim(int fromIndex, int toIndex) {
get(trimAsync(fromIndex, toIndex));
}
@Override
public Future<Void> trimAsync(int fromIndex, int toIndex) {
return commandExecutor.writeAsync(getName(), codec, RedisCommands.LTRIM, getName(), fromIndex, toIndex);
}
@Override
public ListIterator<V> listIterator() {
return listIterator(0);
}
@Override
public ListIterator<V> listIterator(final int ind) {
return new ListIterator<V>() {
private V prevCurrentValue;
private V nextCurrentValue;
private V currentValueHasRead;
private int currentIndex = ind - 1;
private boolean hasBeenModified = true;
@Override
public boolean hasNext() {
V val = RedissonListMultimapValues.this.getValue(currentIndex+1);
if (val != null) {
nextCurrentValue = val;
}
return val != null;
}
@Override
public V next() {
if (nextCurrentValue == null && !hasNext()) {
throw new NoSuchElementException("No such element at index " + currentIndex);
}
currentIndex++;
currentValueHasRead = nextCurrentValue;
nextCurrentValue = null;
hasBeenModified = false;
return currentValueHasRead;
}
@Override
public void remove() {
if (currentValueHasRead == null) {
throw new IllegalStateException("Neither next nor previous have been called");
}
if (hasBeenModified) {
throw new IllegalStateException("Element been already deleted");
}
RedissonListMultimapValues.this.remove(currentIndex);
currentIndex--;
hasBeenModified = true;
currentValueHasRead = null;
}
@Override
public boolean hasPrevious() {
if (currentIndex < 0) {
return false;
}
V val = RedissonListMultimapValues.this.getValue(currentIndex);
if (val != null) {
prevCurrentValue = val;
}
return val != null;
}
@Override
public V previous() {
if (prevCurrentValue == null && !hasPrevious()) {
throw new NoSuchElementException("No such element at index " + currentIndex);
}
currentIndex--;
hasBeenModified = false;
currentValueHasRead = prevCurrentValue;
prevCurrentValue = null;
return currentValueHasRead;
}
@Override
public int nextIndex() {
return currentIndex + 1;
}
@Override
public int previousIndex() {
return currentIndex;
}
@Override
public void set(V e) {
if (hasBeenModified) {
throw new IllegalStateException();
}
RedissonListMultimapValues.this.fastSet(currentIndex, e);
}
@Override
public void add(V e) {
RedissonListMultimapValues.this.add(currentIndex+1, e);
currentIndex++;
hasBeenModified = true;
}
};
}
@Override
public RList<V> subList(int fromIndex, int toIndex) {
int size = size();
if (fromIndex < 0 || toIndex > size) {
throw new IndexOutOfBoundsException("fromIndex: " + fromIndex + " toIndex: " + toIndex + " size: " + size);
}
if (fromIndex > toIndex) {
throw new IllegalArgumentException("fromIndex: " + fromIndex + " toIndex: " + toIndex);
}
return new RedissonSubList<V>(codec, commandExecutor, getName(), fromIndex, toIndex);
}
public String toString() {
Iterator<V> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
V e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
Iterator<V> e1 = iterator();
Iterator<?> e2 = ((List<?>) o).iterator();
while (e1.hasNext() && e2.hasNext()) {
V o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
@Override
public int hashCode() {
int hashCode = 1;
for (V e : this) {
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
}
return hashCode;
}
@Override
public Future<Integer> addAfterAsync(V elementToFind, V element) {
return commandExecutor.writeAsync(getName(), codec, RedisCommands.LINSERT, getName(), "AFTER", elementToFind, element);
}
@Override
public Future<Integer> addBeforeAsync(V elementToFind, V element) {
return commandExecutor.writeAsync(getName(), codec, RedisCommands.LINSERT, getName(), "BEFORE", elementToFind, element);
}
@Override
public Integer addAfter(V elementToFind, V element) {
return get(addAfterAsync(elementToFind, element));
}
@Override
public Integer addBefore(V elementToFind, V element) {
return get(addBeforeAsync(elementToFind, element));
}
}
|
package liquibase.sqlgenerator.core;
import liquibase.database.Database;
import liquibase.database.core.OracleDatabase;
import liquibase.exception.ValidationErrors;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGenerator;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.SelectFromDatabaseChangeLogLockStatement;
import liquibase.util.StringUtils;
public class SelectFromDatabaseChangeLogLockGenerator extends AbstractSqlGenerator<SelectFromDatabaseChangeLogLockStatement> {
public ValidationErrors validate(SelectFromDatabaseChangeLogLockStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
ValidationErrors errors = new ValidationErrors();
errors.checkRequiredField("columnToSelect", statement.getColumnsToSelect());
return errors;
}
public Sql[] generateSql(SelectFromDatabaseChangeLogLockStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
String liquibaseSchema;
liquibaseSchema = database.getLiquibaseSchemaName();
String[] columns = statement.getColumnsToSelect();
int numberOfColumns = columns.length;
String[] escapedColumns = new String[numberOfColumns];
for (int i=0; i<numberOfColumns; i++) {
escapedColumns[i] = database.escapeColumnName(database.getLiquibaseCatalogName(), liquibaseSchema, database.getDatabaseChangeLogLockTableName(), columns[i]);
}
String sql = "SELECT " + StringUtils.join(escapedColumns, ",") + " FROM " +
database.escapeTableName(database.getLiquibaseCatalogName(), liquibaseSchema, database.getDatabaseChangeLogLockTableName()) +
" WHERE " + database.escapeColumnName(database.getLiquibaseCatalogName(), liquibaseSchema, database.getDatabaseChangeLogLockTableName(), "ID") + "=1";
if (database instanceof OracleDatabase) {
sql += " FOR UPDATE";
}
return new Sql[] {
new UnparsedSql(sql)
};
}
}
|
package com.github.wugenshui.spring.security;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author : chenbo
* @date : 2020-04-19
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class BCryptTest {
@Test
public void EncodeTest() {
String password = "admin";
// 加密密码
String hashpw = BCrypt.hashpw(password, BCrypt.gensalt());
System.out.println("加密后密码:" + hashpw);
boolean checkpw = BCrypt.checkpw(password, hashpw);
Assert.assertTrue(checkpw);
hashpw = "$2a$10$vS.o5BJVfBJU47D7lGl/SukvAOnkJ2wDF8bMuUujfCmvjcWxr2uF6";
checkpw = BCrypt.checkpw(password, hashpw);
Assert.assertTrue(checkpw);
}
}
|
package assignments.programming_assignment_2;
// Grade 11, Computer Science, Assignment 2
// Packages to import
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class assignment_2 {
JFrame frame;
JTable table;
assignment_2() {
frame = new JFrame(); // Frame initialization
frame.setTitle("Student Semester Time Table"); // Frame Title
// Data to be displayed in the JTable
String[][] data = {
{ "Period 1", "co-op" },
{ "Period 2", "co-op" },
{ "Period 3", "computer science" },
{ "Period 4", "auto/transportation" }
};
String[] columnNames = { "Period", "Class Name" }; // Column Names
// Creating the JTable
table = new JTable(data, columnNames);
// Adding to JScrollPane
JScrollPane sp = new JScrollPane(table);
frame.add(sp);
frame.setSize(400, 150); // frame size X,Y
frame.setVisible(true);
}
// Runs the function
public static void main(String[] args) {
new assignment_2();
}
}
// Made by MBlais with ♥
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.aws.greengrass.util;
import com.aws.greengrass.logging.api.Logger;
import com.aws.greengrass.logging.impl.LogManager;
import com.aws.greengrass.util.platforms.Platform;
import com.aws.greengrass.util.platforms.ShellDecorator;
import com.aws.greengrass.util.platforms.UserDecorator;
import lombok.Getter;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import javax.annotation.Nullable;
/**
* Vaguely like ProcessBuilder, but more flexible and lambda-friendly.
* <pre>
* // set wd to current working directory
* String wd = Exec.sh("pwd");
*
* // run a shell in the background, and print "Yahoo!"
* // when "wifi" appears in the system log
* Platform.getInstance().createNewProcessRunner()
* .withShell("tail -F /var/log/system.log")
* .withOut(str->{
* if(str.toString().contains("wifi"))
* System.out.println("Yahoo!");
* })
* .background(exc -> System.out.println("exit "+exc));
* </pre>
*/
public abstract class Exec implements Closeable {
private static final char PATH_SEP = File.pathSeparatorChar;
private static final String PATH_ENVVAR = "PATH";
private static final Logger staticLogger = LogManager.getLogger(Exec.class);
protected Logger logger = staticLogger;
private static final Consumer<CharSequence> NOP = s -> {
};
// default directory relative paths are resolved against (i.e. current working directory)
private static final File userdir = new File(System.getProperty("user.dir"));
protected static final ConcurrentLinkedDeque<Path> paths = new ConcurrentLinkedDeque<>();
protected static final Map<String, String> defaultEnvironment = new ConcurrentHashMap<>();
protected Map<String, String> environment;
static {
addPathEntries(System.getenv(PATH_ENVVAR));
computeDefaultPathString();
defaultEnvironment.put("JAVA_HOME", System.getProperty("java.home"));
defaultEnvironment.put("HOME", System.getProperty("user.home"));
}
protected final AtomicBoolean isClosed = new AtomicBoolean(false);
protected Process process;
private IntConsumer whenDone;
private Consumer<CharSequence> stdout = NOP;
private Consumer<CharSequence> stderr = NOP;
private AtomicInteger numberOfCopiers;
protected String[] cmds;
protected ShellDecorator shellDecorator;
protected UserDecorator userDecorator;
protected File dir = userdir;
private long timeout = -1;
private TimeUnit timeunit = TimeUnit.SECONDS;
private Copier stderrc;
private Copier stdoutc;
protected Duration gracefulShutdownTimeout = Duration.ofSeconds(5);
public static void setDefaultEnv(String key, String value) {
defaultEnvironment.put(key, value);
}
public Exec setenv(String key, CharSequence value) {
environment.put(key, value instanceof String ? (String) value : Coerce.toString(value));
return this;
}
public Exec logger(Logger logger) {
this.logger = logger;
return this;
}
// TODO Cleanup convenient methods. These are more than necessary
public String cmd(String... command) throws InterruptedException, IOException {
return withExec(command).execAndGetStringOutput();
}
public String sh(String command) throws InterruptedException, IOException {
return sh((File) null, command);
}
public String sh(File dir, String command) throws InterruptedException, IOException {
return cd(dir).withShell(command).execAndGetStringOutput();
}
public String sh(Path dir, String command) throws InterruptedException, IOException {
return sh(dir.toFile(), command);
}
public boolean successful(boolean ignoreStderr, String command) throws InterruptedException, IOException {
return withShell(command).successful(ignoreStderr);
}
public boolean successful(boolean ignoreStderr) throws InterruptedException, IOException {
exec();
return (ignoreStderr || stderrc.getNlines() == 0) && process.exitValue() == 0;
}
/**
* Find the path of a given command.
*
* @param fn command to lookup.
* @return the Path of the command, or null if not found.
*/
@Nullable
public abstract Path which(String fn); // mirrors shell command
protected static String deTilde(String s) {
if (s.startsWith("~/")) {
s = Utils.HOME_PATH.resolve(s.substring(2)).toString();
}
return s;
}
protected static void addPathEntries(String path) {
if (path != null && path.length() > 0) {
for (String f : path.split("[" + PATH_SEP + ",] *")) {
Path p = Paths.get(deTilde(f));
if (!paths.contains(p)) {
paths.add(p);
}
}
}
}
protected static void computeDefaultPathString() {
StringBuilder sb = new StringBuilder();
paths.forEach(p -> {
if (sb.length() > 5) {
sb.append(PATH_SEP);
}
sb.append(p.toString());
});
setDefaultEnv(PATH_ENVVAR, sb.toString());
}
/**
* Set working directory to the given file.
*
* @param f directory to switch into.
* @return this.
*/
public Exec cd(File f) {
if (f != null) {
dir = f;
}
return this;
}
public Exec cd(String d) {
return cd(dir.toPath().toAbsolutePath().resolve(Paths.get(d)).toAbsolutePath().toFile());
}
/**
* Get the working directory which is configured for the Exec.
*
* @return current working directory.
*/
public File cwd() {
return dir;
}
/**
* Set the command to execute.
* @param c a command.
* @return this.
*/
public Exec withExec(String... c) {
cmds = c;
return this;
}
/**
* Decorate a command so that it executes in a default shell.
*
* @param command a command to execute.
* @return this.
*/
public Exec withShell(String... command) {
withShell();
return withExec(command);
}
/**
* Execute the command in a default shell.
*
* @return this.
*/
public Exec withShell() {
shellDecorator = Platform.getInstance().getShellDecorator();
return this;
}
/**
* Execute the command using the specified shell.
*
* @param shell the shell to use.
* @return this.
*/
public Exec usingShell(String shell) {
shellDecorator = Platform.getInstance().getShellDecorator().withShell(shell);
return this;
}
/**
* Execute the command with the specified user.
*
* @param user a user name or identifier.
* @return this.
*/
public Exec withUser(String user) {
if (userDecorator == null) {
userDecorator = Platform.getInstance().getUserDecorator();
}
userDecorator.withUser(user);
return this;
}
/**
* Execute the command with the specified group.
*
* @param group a group name or identifier.
* @return this.
*/
public Exec withGroup(String group) {
if (userDecorator == null) {
userDecorator = Platform.getInstance().getUserDecorator();
}
userDecorator.withGroup(group);
return this;
}
/**
* Set the command to run with a given timeout.
*
* @param t timeout.
* @param u units.
* @return this.
*/
public Exec withTimeout(long t, TimeUnit u) {
timeout = t;
timeunit = u;
return this;
}
@SuppressWarnings("PMD.SystemPrintln")
public Exec withDumpOut() {
return withOut(l -> System.out.println("stderr: " + l)).withErr(l -> System.out.println("stdout: " + l));
}
public Exec withOut(Consumer<CharSequence> o) {
stdout = o;
return this;
}
public Exec withErr(Consumer<CharSequence> o) {
stderr = o;
return this;
}
/**
* Get the command to execute. This will be decorated if shell and user/group have been provided.
*
* @return the command.
*/
public abstract String[] getCommand();
/**
* Execute a command.
*
* @return the process exit code if it is not a background process.
* @throws InterruptedException if the command is interrupted while running.
* @throws IOException if an error occurs while executing.
*/
@SuppressWarnings("PMD.AvoidRethrowingException")
public Optional<Integer> exec() throws InterruptedException, IOException {
// Don't run anything if the current thread is currently interrupted
if (Thread.currentThread().isInterrupted()) {
logger.atWarn().kv("command", this).log("Refusing to execute because the active thread is interrupted");
throw new InterruptedException();
}
process = createProcess();
logger.debug("Created process with pid {}", getPid());
stderrc = new Copier(process.getErrorStream(), stderr);
stdoutc = new Copier(process.getInputStream(), stdout);
stderrc.start();
stdoutc.start();
if (whenDone == null) {
try {
if (timeout < 0) {
process.waitFor();
} else {
if (!process.waitFor(timeout, timeunit)) {
(stderr == null ? stdout : stderr).accept("\n[TIMEOUT]\n");
process.destroy();
}
}
} catch (InterruptedException ie) {
// We just got interrupted by something like the cancel(true) in setBackingTask
// Give the process a touch more time to exit cleanly
if (!process.waitFor(5, TimeUnit.SECONDS)) {
(stderr == null ? stdout : stderr).accept("\n[TIMEOUT after InterruptedException]\n");
process.destroyForcibly();
}
throw ie;
}
stderrc.join(5000);
stdoutc.join(5000);
return Optional.of(process.exitValue());
}
return Optional.empty();
}
/**
* Create and start the child process in platform-specific ways.
*
* @return child process
* @throws IOException if IO error occurs
*/
protected abstract Process createProcess() throws IOException;
/**
* Get the stdout and stderr output as a string.
*
* @return String of output.
* @throws InterruptedException if thread is interrupted while executing
* @throws IOException if execution of the process fails to start
*/
public String execAndGetStringOutput() throws InterruptedException, IOException {
StringBuilder sb = new StringBuilder();
Consumer<CharSequence> f = sb::append;
withOut(f).withErr(f).exec();
return sb.toString().trim();
}
public void background(IntConsumer cb) throws InterruptedException, IOException {
whenDone = cb;
exec();
}
@SuppressWarnings("PMD.NullAssignment")
void setClosed() {
if (!isClosed.get()) {
final IntConsumer wd = whenDone;
final int exit = process == null ? -1 : process.exitValue();
isClosed.set(true);
if (wd != null) {
wd.accept(exit);
}
}
}
public boolean isRunning() {
return process == null ? !isClosed.get() : process.isAlive();
}
/**
* Get associated process instance representing underlying OS process.
*
* @return process object.
*/
public Process getProcess() {
return process;
}
/**
* Get the process ID of the underlying process.
*
* @return the process PID.
*/
public abstract int getPid();
@Override
public abstract void close() throws IOException;
@Override
public String toString() {
return Utils.deepToString(cmds, 90).toString();
}
/**
* Sends the lines of an InputStream to a consumer in the background.
*/
@SuppressWarnings("PMD.AvoidCatchingThrowable")
private class Copier extends Thread {
private final Consumer<CharSequence> out;
private final InputStream in;
@Getter
private int nlines = 0;
Copier(InputStream i, Consumer<CharSequence> s) {
super("Copier");
in = i;
out = s;
// Set as a daemon thread so that it dies when the main thread exits
setDaemon(true);
if (whenDone != null) {
if (numberOfCopiers == null) {
numberOfCopiers = new AtomicInteger(1);
} else {
numberOfCopiers.incrementAndGet();
}
}
}
@Override
public void run() {
try (BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8), 200)) {
StringBuilder sb = new StringBuilder();
boolean cr = false;
while (true) {
int c;
for (c = br.read(); c >= 0 && c != '\n' && c != '\r'; c = br.read()) {
sb.append((char) c);
cr = false;
}
// Append a newline to our builder if we get \n or if we are seeing \r for the first time.
// This prevents \r\n from causing 2 lines to be logged.
// If cr is true and we see another \r, we will append a newline (\r\r is 2 lines).
if (c >= 0 && !cr || c == '\r') {
// Split on cr too, this protects us from having crazy long lines from a console application
// which is using \r to rewrite the last line, ex updating download status.
if (c == '\r') {
cr = true;
}
sb.append('\n');
nlines++;
}
if (out != null && sb.length() > 0) {
out.accept(sb);
}
sb.setLength(0);
if (c < 0) {
break;
}
}
} catch (Throwable ignore) {
// nothing that can go wrong here worries us, they're
// all EOFs
}
if (whenDone != null && numberOfCopiers.decrementAndGet() <= 0) {
try {
process.waitFor();
setClosed();
} catch (InterruptedException ignore) {
// Ignore as this thread is done running anyway and will exit
}
}
}
}
}
|
/*
* Copyright (c) 1997, 2010, 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.
*/
package com.sun.codemodel.internal;
/**
* A cast operation.
*/
final class JCast extends JExpressionImpl {
/**
* JType to which the expression is to be cast.
*/
private final JType type;
/**
* JExpression to be cast.
*/
private final JExpression object;
/**
* JCast constructor
*
* @param type
* JType to which the expression is cast
*
* @param object
* JExpression for the object upon which
* the cast is applied
*/
JCast(JType type, JExpression object) {
this.type = type;
this.object = object;
}
public void generate(JFormatter f) {
f.p("((").g(type).p(')').g(object).p(')');
}
}
|
package com.xw.springbootstudy.runlistener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class MyRunListener implements SpringApplicationRunListener {
public MyRunListener(SpringApplication application, String[] args) {
}
@Override
public void starting() {
System.out.println("MyRunListener " + "starting");
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
System.out.println("MyRunListener " + "environmentPrepared");
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
System.out.println("MyRunListener " + "contextPrepared");
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
System.out.println("MyRunListener " + "contextLoaded");
}
@Override
public void finished(ConfigurableApplicationContext context, Throwable exception) {
System.out.println("MyRunListener " + "finished");
}
}
|
package com.smt.kata.distance.bean;
// JDK 11.x
import java.io.Serializable;
import com.siliconmtn.core.HashCodeUtil;
// Spacelibs 1.x
import com.siliconmtn.data.text.StringUtil;
/****************************************************************************
* <b>Title:</b> Location.java
* <b>Project:</b> SMT-Kata
* <b>Description:</b> Data structure to hold a geocoded location
* <b>Company:</b> Silicon Mountain Technologies
*
* @author James Camire
* @version 3.0
* @since Apr 21, 2021
* <b>updates:</b>
*
****************************************************************************/
public class Location implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7171033548379700133L;
// Members
protected String address;
protected String address2;
protected String city;
protected String county;
protected String zipCode;
protected String zipSuffixCode;
protected String state;
protected String country;
protected String countryName;
protected double latitude = 0.0;
protected double longitude = 0.0;
protected MatchCode matchCode = MatchCode.NO_MATCH;
/**
* Default constructor
*/
public Location() {
super();
}
/*
* (non-javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return StringUtil.getToString(this);
}
@Override
public int hashCode() {
return HashCodeUtil.hash(this) ;
}
public boolean equals(Location loc) {
return this.hashCode() == loc.hashCode();
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @return the address2
*/
public String getAddress2() {
return address2;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @return the county
*/
public String getCounty() {
return county;
}
/**
* @return the zipCode
*/
public String getZipCode() {
return zipCode;
}
/**
* @return the zipSuffixCode
*/
public String getZipSuffixCode() {
return zipSuffixCode;
}
/**
* @return the state
*/
public String getState() {
return state;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @return the countryName
*/
public String getCountryName() {
return countryName;
}
/**
* @return the latitude
*/
public double getLatitude() {
return latitude;
}
/**
* @return the longitude
*/
public double getLongitude() {
return longitude;
}
/**
* @return the matchCode
*/
public MatchCode getMatchCode() {
return matchCode;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @param address2 the address2 to set
*/
public void setAddress2(String address2) {
this.address2 = address2;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @param county the county to set
*/
public void setCounty(String county) {
this.county = county;
}
/**
* @param zipCode the zipCode to set
*/
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
/**
* @param zipSuffixCode the zipSuffixCode to set
*/
public void setZipSuffixCode(String zipSuffixCode) {
this.zipSuffixCode = zipSuffixCode;
}
/**
* @param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* @param country the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @param countryName the countryName to set
*/
public void setCountryName(String countryName) {
this.countryName = countryName;
}
/**
* @param latitude the latitude to set
*/
public void setLatitude(double latitude) {
this.latitude = latitude;
}
/**
* @param longitude the longitude to set
*/
public void setLongitude(double longitude) {
this.longitude = longitude;
}
/**
* @param matchCode the matchCode to set
*/
public void setMatchCode(MatchCode matchCode) {
this.matchCode = matchCode;
}
}
|
package ru.job4j.array;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class MatrixTest {
@Test
public void when3x3() {
Matrix mrx = new Matrix();
int[][] result = mrx.multiple(3);
int[][] expect = {
{1, 2, 3},
{2, 4, 6},
{3, 6, 9}
};
assertThat(result, is(expect));
}
}
|
/*
*
* * ============LICENSE_START=======================================================
* * org.onap.dcae
* * ================================================================================
* * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved.
* * ================================================================================
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* * ============LICENSE_END=========================================================
*
*/
package org.onap.dcaegen2.platform.mod.models;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Set;
/**
* @author
* @date 09/08/2020
* To validate User enter Details
*/
@Data
public class SignupRequest {
@NotBlank(message = "username must not be blank")
@Size(min = 5, max = 10, message = "username must be between 5 and 10 characters.")
private String username;
@NotNull(message = "username must not be null")
@Size(min = 1, message = "At least 1 role must be passed")
private Set<String> roles;
@NotBlank(message = "password must not be blank")
private String password;
@NotBlank(message = "Full name must not be blank")
private String fullName;
}
|
package com.thomsonreuters.ema.examples.training.iprovider.series400.example460__MarketPrice__RTT;
import com.thomsonreuters.ema.access.*;
import com.thomsonreuters.ema.rdm.EmaRdm;
import com.thomsonreuters.upa.codec.DataTypes;
import com.thomsonreuters.upa.rdm.DomainTypes;
import java.util.*;
import java.util.Map;
class AppClient implements OmmProviderClient
{
private boolean enableRTT;
/*
holds the last latency value for each client that supports RTT requests
clientLatencyMap.keySet() holds handles to all consumers that can receive RTT requests
*/
public Map<Long, Long> clientLatencyMap = new HashMap<>();
//holds all item requests for each client
public Map<Long, List<Long>> clientItemHandlesMap = new HashMap<>();
public AppClient(boolean rtt) {
enableRTT = rtt;
}
public void onReqMsg(ReqMsg reqMsg, OmmProviderEvent event)
{
switch (reqMsg.domainType())
{
case EmaRdm.MMT_LOGIN :
processLoginRequest(reqMsg, event);
break;
case EmaRdm.MMT_MARKET_PRICE :
processMarketPriceRequest(reqMsg, event);
break;
default :
break;
}
}
public void onRefreshMsg(RefreshMsg refreshMsg, OmmProviderEvent event){}
public void onStatusMsg(StatusMsg statusMsg, OmmProviderEvent event){}
public void onGenericMsg(GenericMsg genericMsg, OmmProviderEvent event){
switch (genericMsg.domainType()) {
case EmaRdm.MMT_LOGIN:
processRTT(genericMsg, event);
break;
default:
}
}
public void onPostMsg(PostMsg postMsg, OmmProviderEvent event){}
public void onReissue(ReqMsg reqMsg, OmmProviderEvent event){}
public void onClose(ReqMsg reqMsg, OmmProviderEvent event){
switch (reqMsg.domainType())
{
case EmaRdm.MMT_LOGIN :
clientLatencyMap.remove(event.handle());
clientItemHandlesMap.remove(event.clientHandle());
break;
case EmaRdm.MMT_MARKET_PRICE :
List<Long> list = clientItemHandlesMap.get(event.clientHandle());
list.remove(event.handle());
if (list.isEmpty()) {
clientItemHandlesMap.remove(event.clientHandle());
}
break;
default :
break;
}
}
public void onAllMsg(Msg msg, OmmProviderEvent event){}
void processRTT(GenericMsg genericMsg, OmmProviderEvent event) {
if (clientLatencyMap.containsKey(event.handle())) {
if (genericMsg.payload().dataType() == DataTypes.ELEMENT_LIST && genericMsg.domainType() == DomainTypes.LOGIN) {
System.out.println("Received login RTT message from Consumer " + event.handle());
ElementList data = genericMsg.payload().elementList();
for ( ElementEntry elem : data) {
if (elem.name().equals(EmaRdm.ENAME_TICKS)) {
System.out.println(" RTT Tick value is: " + elem.uintValue());
long latency = System.nanoTime() - elem.uintValue();
clientLatencyMap.put(event.handle(), latency);
System.out.println(" Last RTT message latency is: " + latency);
}
}
}
}
}
void processLoginRequest(ReqMsg reqMsg, OmmProviderEvent event)
{
if (enableRTT) {
if (reqMsg.attrib().dataType() == DataTypes.ELEMENT_LIST) {
ElementList reqAttributes = reqMsg.attrib().elementList();
for ( ElementEntry reqAttrib : reqAttributes ) {
if (reqAttrib.name().equals(EmaRdm.ENAME_LATENCY)) {
clientLatencyMap.put(event.handle(), 0L);
System.out.println("Consumer with handle " + event.handle() + " supports gathering RTT statistics");
}
}
}
ElementList elementList = EmaFactory.createElementList();
elementList.add(EmaFactory.createElementEntry().uintValue(EmaRdm.ENAME_LATENCY, EmaRdm.LOGIN_RTT_ELEMENT));
event.provider().submit( EmaFactory.createRefreshMsg().domainType(EmaRdm.MMT_LOGIN).name(reqMsg.name()).
nameType(EmaRdm.USER_NAME).complete(true).solicited(true).
state(OmmState.StreamState.OPEN, OmmState.DataState.OK, OmmState.StatusCode.NONE, "Login accepted").
attrib(elementList),
event.handle() );
} else {
event.provider().submit( EmaFactory.createRefreshMsg().domainType(EmaRdm.MMT_LOGIN).name(reqMsg.name()).
nameType(EmaRdm.USER_NAME).complete(true).solicited(true).
state(OmmState.StreamState.OPEN, OmmState.DataState.OK, OmmState.StatusCode.NONE, "Login accepted"),
event.handle() );
}
}
void processMarketPriceRequest(ReqMsg reqMsg, OmmProviderEvent event)
{
FieldList fieldList = EmaFactory.createFieldList();
fieldList.add( EmaFactory.createFieldEntry().real(22, 3990, OmmReal.MagnitudeType.EXPONENT_NEG_2));
fieldList.add( EmaFactory.createFieldEntry().real(25, 3994, OmmReal.MagnitudeType.EXPONENT_NEG_2));
fieldList.add( EmaFactory.createFieldEntry().real(30, 9, OmmReal.MagnitudeType.EXPONENT_0));
fieldList.add( EmaFactory.createFieldEntry().real(31, 19, OmmReal.MagnitudeType.EXPONENT_0));
event.provider().submit( EmaFactory.createRefreshMsg().name(reqMsg.name()).serviceId(reqMsg.serviceId()).solicited(true).
state(OmmState.StreamState.OPEN, OmmState.DataState.OK, OmmState.StatusCode.NONE, "Refresh Completed").
payload(fieldList).complete(true),
event.handle() );
if (clientItemHandlesMap.containsKey(event.clientHandle())) {
clientItemHandlesMap.get(event.clientHandle()).add(event.handle());
} else {
LinkedList<Long> list = new LinkedList<>();
list.add(event.handle());
clientItemHandlesMap.put(event.clientHandle(), list);
}
}
public void sendRTTRequests(OmmProvider provider) {
if (!enableRTT) {
System.out.println("This provider does not support RTT");
} else {
ElementList elementList = EmaFactory.createElementList();
for (Long handle : clientLatencyMap.keySet()) {
elementList.clear();
Long latency = clientLatencyMap.get(handle);
if (latency != 0) {
elementList.add(EmaFactory.createElementEntry().uintValue(EmaRdm.ENAME_LATENCY, latency));
}
elementList.add(EmaFactory.createElementEntry().uintValue(EmaRdm.ENAME_TICKS, System.nanoTime()));
provider.submit(EmaFactory.createGenericMsg().payload(elementList).domainType(DomainTypes.LOGIN).providerDriven(true).complete(true), handle);
}
}
}
public void sendUpdates(OmmProvider provider, FieldList fieldList) {
for (Long cl_h : clientItemHandlesMap.keySet()) {
List<Long> list = clientItemHandlesMap.get(cl_h);
for (Long ih : list) {
provider.submit( EmaFactory.createUpdateMsg().payload( fieldList ), ih );
}
}
}
public boolean standBy() {
return clientItemHandlesMap.size() == 0;
}
}
public class IProvider
{
static long DELTA = 1000;
public static void main(String[] args)
{
long nextRequestTime = System.currentTimeMillis() + DELTA;
OmmProvider provider = null;
try
{
OmmIProviderConfig config = EmaFactory.createOmmIProviderConfig();
AppClient appClient = new AppClient(true);
provider = EmaFactory.createOmmProvider(config.operationModel(OmmIProviderConfig.OperationModel.USER_DISPATCH).port("14002"), appClient);
FieldList fieldList = EmaFactory.createFieldList();
Random rnd = new Random();
while (appClient.standBy()) {
provider.dispatch(500);
Thread.sleep(500);
}
for (int i = 0; i < 6000; i++)
{
provider.dispatch(50);
if (System.currentTimeMillis() >= nextRequestTime) {
appClient.sendRTTRequests(provider);
fieldList.clear();
fieldList.add(EmaFactory.createFieldEntry().real(22, 3991 + rnd.nextInt(50), OmmReal.MagnitudeType.EXPONENT_NEG_2));
fieldList.add(EmaFactory.createFieldEntry().real(30, 10 + rnd.nextInt(50), OmmReal.MagnitudeType.EXPONENT_0));
appClient.sendUpdates(provider, fieldList);
nextRequestTime = System.currentTimeMillis() + DELTA;
}
Thread.sleep(50);
}
}
catch (InterruptedException | OmmException excp)
{
System.out.println(excp.getMessage());
}
finally
{
if (provider != null) provider.uninitialize();
}
}
}
|
/*
* Copyright (c) 2012, 2022, 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-2012 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) the above copyright notice(s) and this permission notice
* appear with all copies of the Data Files or Software, (b) both the above
* copyright notice(s) and this 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.text.resources.cldr.lag;
import java.util.ListResourceBundle;
public class FormatData_lag extends ListResourceBundle {
@Override
protected final Object[][] getContents() {
final Object[][] data = new Object[][] {
{ "MonthNames",
new String[] {
"K\u0289f\u00fangat\u0268",
"K\u0289naan\u0268",
"K\u0289keenda",
"Kwiikumi",
"Kwiinyamb\u00e1la",
"Kwiidwaata",
"K\u0289m\u0289\u0289nch\u0268",
"K\u0289v\u0268\u0268r\u0268",
"K\u0289saat\u0289",
"Kwiinyi",
"K\u0289saano",
"K\u0289sasat\u0289",
"",
}
},
{ "MonthAbbreviations",
new String[] {
"F\u00fangat\u0268",
"Naan\u0268",
"Keenda",
"Ik\u00fami",
"Inyambala",
"Idwaata",
"M\u0289\u0289nch\u0268",
"V\u0268\u0268r\u0268",
"Saat\u0289",
"Inyi",
"Saano",
"Sasat\u0289",
"",
}
},
{ "MonthNarrows",
new String[] {
"F",
"N",
"K",
"I",
"I",
"I",
"M",
"V",
"S",
"I",
"S",
"S",
"",
}
},
{ "DayNames",
new String[] {
"Jumap\u00ediri",
"Jumat\u00e1tu",
"Juma\u00edne",
"Jumat\u00e1ano",
"Alam\u00edisi",
"Ijum\u00e1a",
"Jumam\u00f3osi",
}
},
{ "DayAbbreviations",
new String[] {
"P\u00edili",
"T\u00e1atu",
"\u00cdne",
"T\u00e1ano",
"Alh",
"Ijm",
"M\u00f3osi",
}
},
{ "DayNarrows",
new String[] {
"P",
"T",
"E",
"O",
"A",
"I",
"M",
}
},
{ "QuarterNames",
new String[] {
"Ncholo ya 1",
"Ncholo ya 2",
"Ncholo ya 3",
"Ncholo ya 4",
}
},
{ "QuarterAbbreviations",
new String[] {
"Ncho 1",
"Ncho 2",
"Ncho 3",
"Ncho 4",
}
},
{ "AmPmMarkers",
new String[] {
"TOO",
"MUU",
}
},
{ "long.Eras",
new String[] {
"K\u0268r\u0268sit\u0289 s\u0268 anavyaal",
"K\u0268r\u0268sit\u0289 akavyaalwe",
}
},
{ "Eras",
new String[] {
"KSA",
"KA",
}
},
{ "field.era", "Mp\u0268\u0268nd\u0268" },
{ "field.year", "Mwa\u00e1ka" },
{ "field.month", "Mwe\u00e9ri" },
{ "field.week", "W\u00ediki" },
{ "field.weekday", "Sik\u0289 ya j\u00fama" },
{ "field.dayperiod", "Mp\u0268\u0268nd\u0268 ja sik\u0289" },
{ "field.hour", "S\u00e1a" },
{ "field.minute", "Dak\u00edka" },
{ "field.second", "Sek\u00faunde" },
{ "field.zone", "Mp\u0268\u0268nd\u0268 ja m\u0268\u0268t\u0289" },
{ "TimePatterns",
new String[] {
"h:mm:ss a zzzz",
"h:mm:ss a z",
"h:mm:ss a",
"h:mm a",
}
},
{ "DatePatterns",
new String[] {
"EEEE, d MMMM y",
"d MMMM y",
"d MMM y",
"dd/MM/yyyy",
}
},
};
return data;
}
}
|
package com.proschedule.core.persistence.view.operation;
import com.proschedule.core.persistence.exceptions.OperationPersistenceException;
import com.proschedule.core.persistence.exceptions.OperationTypePersistenceException;
import com.proschedule.core.persistence.model.OperationType;
import com.proschedule.util.forms.MouseAdapterBalloonTip;
import com.proschedule.util.messages.MessageDialog;
import com.proschedule.validator.util.ValidatorException;
import java.awt.Color;
import java.util.Set;
import javax.validation.ConstraintViolation;
import net.java.balloontip.BalloonTip;
/**
* Tela para adição/modificação de operações
*
* @author Maycon Bordin
* @version 1.0
* @created 04-out-2010 13:24:50
*/
public class NewOperationDialog extends javax.swing.JDialog {
private OperationPresenter presenter;
private java.awt.Frame parent;
private OperationPanel panel;
private OperationTypeComboBoxModel operationTypeComboBoxModel;
private MouseAdapterBalloonTip descriptionBalloonTip;
private MouseAdapterBalloonTip leadTimeValueBalloonTip;
private MouseAdapterBalloonTip typeBalloonTip;
/**
* Construtor da Classe - Dependente da aba principal
*
* @param parent Frame principal
* @param panel Painel de operações
*/
public NewOperationDialog(java.awt.Frame parent, OperationPanel panel) {
super(parent, true);
this.parent = parent;
this.presenter = panel.getPresenter();
this.panel = panel;
startUp();
}
/**
* Inicializa as configurações, componentes
*/
public void startUp() {
initComponents();
//Centraliza o diálogo
setLocationRelativeTo(null);
if ( presenter.isEdit() ) {
modelToView();
setTitle("Modificar Operação");
} else {
loadOperationTypeComboBox(null);
setTitle("Adicionar Operação");
}
}
/**
* Construtor da Classe - Independente de abas
*
* @param parent Frame principal
*/
public NewOperationDialog(java.awt.Frame parent) {
super(parent, true);
this.parent = parent;
this.presenter = new OperationPresenter();
this.panel = null;
initComponents();
//Centraliza o diálogo
setLocationRelativeTo(null);
loadOperationTypeComboBox(null);
setTitle("Adicionar Operação");
}
/**
* Pega a operação em edição do presenter e passa seus valores para os
* componentes visuais, para edição
*/
public void modelToView() {
jtfDescription.setText( presenter.getOperation().getDescription() );
jtfLeadTimeValue.setText( String.valueOf( presenter.getOperation().getLeadTime().getValue() ) );
jcbLeadTimeType.setSelectedItem( presenter.getOperation().getLeadTime().getType() );
loadOperationTypeComboBox( presenter.getOperation().getType() );
}
/**
* Carrega o combobox com a lista de tipos de operações
*
* @param type O objeto que será selecionado na lista, se não houver use null
*/
public void loadOperationTypeComboBox( OperationType type ) {
try {
operationTypeComboBoxModel = new OperationTypeComboBoxModel(presenter.listTypes());
if ( type != null ) {
operationTypeComboBoxModel.setSelectedItem( type );
}
jcbType.setModel(operationTypeComboBoxModel);
} catch (OperationTypePersistenceException ex) {
MessageDialog.error(ex, parent);
}
}
/**
* Limpa os erros de validação do formulário
*/
public void clearObjectErrors() {
jtfDescription.setBackground(Color.white);
jtfDescription.removeMouseListener(descriptionBalloonTip);
jtfLeadTimeValue.setBackground(Color.white);
jtfLeadTimeValue.removeMouseListener(leadTimeValueBalloonTip);
jcbType.setBackground(Color.white);
jcbType.removeMouseListener(typeBalloonTip);
}
/**
* Exibe no formulário os erros de validação colocando os componentes com
* dados inválidos em amarelo e exibindo um balão com o erro.
*
* @param ve A exceção que contém os erros de validação
*/
public void setObjectErrors(ValidatorException ve) {
Set<ConstraintViolation> constraints = (Set<ConstraintViolation>) ve.getConstraintViolations();
for ( ConstraintViolation cv : constraints ) {
String fieldName = cv.getPropertyPath().toString();
setObjectError(fieldName, cv.getMessage());
}
}
/**
* Exibe no formulário o erro de validação no componente indicado.
*
* @param fieldName O nome do campo que receberá o erro
* @param message A mensagem a ser exibida no balão
*/
public void setObjectError(String fieldName, String message) {
if ( fieldName.equals("description") ) {
jtfDescription.setBackground(Color.yellow);
descriptionBalloonTip = new MouseAdapterBalloonTip(jtfDescription, message);
jtfDescription.addMouseListener(descriptionBalloonTip);
} else if ( fieldName.equals("leadTimeValue") ) {
jtfLeadTimeValue.setBackground(Color.yellow);
leadTimeValueBalloonTip = new MouseAdapterBalloonTip(jtfLeadTimeValue, message);
jtfLeadTimeValue.addMouseListener(leadTimeValueBalloonTip);
} else if ( fieldName.equals("type") ) {
jcbType.setBackground(Color.yellow);
typeBalloonTip = new MouseAdapterBalloonTip(jcbType, message);
jcbType.addMouseListener(typeBalloonTip);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jpDescription = new javax.swing.JPanel();
jtfDescription = new javax.swing.JTextField();
jpLeadTime = new javax.swing.JPanel();
jtfLeadTimeValue = new javax.swing.JTextField();
jcbLeadTimeType = new javax.swing.JComboBox();
jpType = new javax.swing.JPanel();
jcbType = new javax.swing.JComboBox();
jbSave = new javax.swing.JButton();
jbCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jpDescription.setBorder(javax.swing.BorderFactory.createTitledBorder("Descrição"));
javax.swing.GroupLayout jpDescriptionLayout = new javax.swing.GroupLayout(jpDescription);
jpDescription.setLayout(jpDescriptionLayout);
jpDescriptionLayout.setHorizontalGroup(
jpDescriptionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpDescriptionLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jtfDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
.addContainerGap())
);
jpDescriptionLayout.setVerticalGroup(
jpDescriptionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpDescriptionLayout.createSequentialGroup()
.addComponent(jtfDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jpLeadTime.setBorder(javax.swing.BorderFactory.createTitledBorder("Lead Time Padrão"));
jcbLeadTimeType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "horas" }));
javax.swing.GroupLayout jpLeadTimeLayout = new javax.swing.GroupLayout(jpLeadTime);
jpLeadTime.setLayout(jpLeadTimeLayout);
jpLeadTimeLayout.setHorizontalGroup(
jpLeadTimeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpLeadTimeLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jtfLeadTimeValue, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcbLeadTimeType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jpLeadTimeLayout.setVerticalGroup(
jpLeadTimeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpLeadTimeLayout.createSequentialGroup()
.addGroup(jpLeadTimeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jtfLeadTimeValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcbLeadTimeType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jpType.setBorder(javax.swing.BorderFactory.createTitledBorder("Tipo de Operação"));
javax.swing.GroupLayout jpTypeLayout = new javax.swing.GroupLayout(jpType);
jpType.setLayout(jpTypeLayout);
jpTypeLayout.setHorizontalGroup(
jpTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpTypeLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jcbType, 0, 209, Short.MAX_VALUE)
.addContainerGap())
);
jpTypeLayout.setVerticalGroup(
jpTypeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpTypeLayout.createSequentialGroup()
.addComponent(jcbType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jbSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/proschedule/resources/images/forms/save_16.png"))); // NOI18N
jbSave.setText("Salvar");
jbSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbSaveActionPerformed(evt);
}
});
jbCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/proschedule/resources/images/forms/close_16.png"))); // NOI18N
jbCancel.setText("Cancelar");
jbCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jpType, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jbSave, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jpLeadTime, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jpDescription, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jpDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jpLeadTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jpType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbCancel)
.addComponent(jbSave))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Fecha o diálogo - botão cancelar
*
* @param evt
*/
private void jbCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelActionPerformed
dispose();
}//GEN-LAST:event_jbCancelActionPerformed
/**
* Salva a nova/modificada operação no banco de dados através do presenter
*
* @param evt
*/
private void jbSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSaveActionPerformed
try {
clearObjectErrors();
String description = "";
Double leadTimeValue = 0.0;
String leadTimeType = "";
OperationType type = null;
boolean validLeadTimeValue = false;
description = jtfDescription.getText();
leadTimeType = (String) jcbLeadTimeType.getSelectedItem();
type = (OperationType) jcbType.getSelectedItem();
try {
leadTimeValue = Double.parseDouble( jtfLeadTimeValue.getText() );
validLeadTimeValue = true;
} catch (NumberFormatException ex) {
setObjectError("leadTimeValue", "O valor do lead time deve ser numérico.");
}
if ( validLeadTimeValue ) {
try {
presenter.save(description, leadTimeValue, leadTimeType, type);
setVisible(false);
if ( presenter.isEdit() ) {
//Exibe mensagem de sucesso
MessageDialog.sucess("Operação " + presenter.getOperation()
.getDescription() + " modificada com sucesso!", parent);
} else {
//Exibe mensagem de sucesso
MessageDialog.sucess("Operação" + presenter.getOperation()
.getDescription() + " adicionada com sucesso!", parent);
}
if ( panel != null ) {
panel.reloadOperationTableModel();
}
dispose();
} catch (OperationPersistenceException ex) {
MessageDialog.error(ex, parent);
}
} else {
throw new ValidatorException();
}
} catch (ValidatorException ex) {
MessageDialog.warning(ex, parent);
setObjectErrors(ex);
}
}//GEN-LAST:event_jbSaveActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jbCancel;
private javax.swing.JButton jbSave;
private javax.swing.JComboBox jcbLeadTimeType;
private javax.swing.JComboBox jcbType;
private javax.swing.JPanel jpDescription;
private javax.swing.JPanel jpLeadTime;
private javax.swing.JPanel jpType;
private javax.swing.JTextField jtfDescription;
private javax.swing.JTextField jtfLeadTimeValue;
// End of variables declaration//GEN-END:variables
}
|
package jbm.framework.spring.config;
import com.jbm.util.MapUtils;
import com.jbm.util.StringUtils;
import jodd.io.FileNameUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public abstract class ApplicationEnvironmentDefaultListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected ResourceLoader resourceLoader = null;
protected ApplicationEnvironmentPreparedEvent event;
public ClassLoader getClassLoader() {
if (this.resourceLoader != null) {
return this.resourceLoader.getClassLoader();
}
return ClassUtils.getDefaultClassLoader();
}
public abstract List<String> loadPropertiesPath();
public abstract Map<String, Object> loadMapConfigs();
private static HashSet<String> configsMap = new HashSet<>();
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
this.event = event;
this.resourceLoader = event.getSpringApplication().getResourceLoader();
try {
this.resourceLoader = this.resourceLoader != null ? this.resourceLoader : new DefaultResourceLoader(getClassLoader());
this.importProperties(event, resourceLoader);
this.importProperties(event);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void importProperties(ApplicationEnvironmentPreparedEvent event, ResourceLoader resourceLoader) throws IOException {
List<String> pps = this.loadPropertiesPath();
if (CollectionUtils.isEmpty(pps))
return;
for (String ss : pps) {
String path = ss;
if (!StringUtils.contains(path, "classpath:configs/")) {
path = "classpath:configs/" + ss;
}
// Properties defaultProperties = new Properties();
// Resource resource = resourceLoader.getResource(path);
// defaultProperties.load(resource.getInputStream());
// PropertiesPropertySource propertySource = new PropertiesPropertySource(resource.getFilename(), defaultProperties);
if ("yml".equalsIgnoreCase(FileNameUtil.getExtension(path))) {
this.loadYaml(path);
} else {
ResourcePropertySource resourcePropertySource = new ResourcePropertySource(path);
// resourcePropertySource.getSource();
this.addLast(resourcePropertySource);
}
}
}
private void loadYaml(String path) throws IOException {
Resource resource = resourceLoader.getResource(path);
YamlPropertySourceLoader yamlloader = new YamlPropertySourceLoader();
List<PropertySource<?>> pss = yamlloader.load(getNameForResource(resource), resource);
for (PropertySource propertySource : pss) {
this.addLast(propertySource);
}
}
private String getNameForResource(Resource resource) {
String name = resource.getDescription();
if (!org.springframework.util.StringUtils.hasText(name)) {
name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource);
}
return name;
}
private synchronized void addLast(PropertySource propertySource) {
if (configsMap.contains(propertySource.getName()))
return;
event.getEnvironment().getPropertySources().addLast(propertySource);
configsMap.add(propertySource.getName());
logger.info("jbm load properties:{}", propertySource.getName());
}
protected void importProperties(ApplicationEnvironmentPreparedEvent event) {
final Map<String, Object> map = this.loadMapConfigs();
if (MapUtils.isEmpty(map))
return;
MapPropertySource propertySource = new MapPropertySource(this.getClass().getName(), map);
this.addLast(propertySource);
}
}
|
/**
* Copyright 2012 NetDigital Sweden AB
*
* 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.nginious.http.cmd;
import junit.framework.Test;
import junit.framework.TestSuite;
public class Suite extends TestSuite {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(new CmdTestCase("testShortNameCmd"));
suite.addTest(new CmdTestCase("testLongNameCmd"));
suite.addTest(new CmdTestCase("testInvalidCmd"));
suite.addTest(new CmdTestCase("testHelp"));
return suite;
}
public static void main(String[] argv) {
junit.textui.TestRunner.run(suite());
}
}
|
/*
* Copyright (C) 2021-2021 Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huawei.sermant.core.service.dynamicconfig.common;
import java.util.EventObject;
import java.util.Objects;
/**
* An event raised when the config changed, immutable.
*
* @see DynamicConfigEventType
*/
public class DynamicConfigEvent extends EventObject {
private final String key;
private final String group;
private final String content;
private final DynamicConfigEventType eventType;
private DynamicConfigEvent(String key, String group, String content, DynamicConfigEventType eventType) {
super(key + "," + group);
this.key = key;
this.group = group;
this.content = content;
this.eventType = eventType;
}
public String getKey() {
return key;
}
public String getGroup() {
return group;
}
public String getContent() {
return content;
}
public DynamicConfigEventType getEventType() {
return eventType;
}
@Override
public String toString() {
return "DynamicConfigEvent{" +
"key='" + key + '\'' +
", group='" + group + '\'' +
", content='" + content + '\'' +
", eventType=" + eventType +
"} " + super.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DynamicConfigEvent)) {
return false;
}
DynamicConfigEvent that = (DynamicConfigEvent) o;
return Objects.equals(getKey(), that.getKey()) &&
Objects.equals(getGroup(), that.getGroup()) &&
Objects.equals(getContent(), that.getContent()) &&
getEventType() == that.getEventType();
}
@Override
public int hashCode() {
return Objects.hash(getKey(), getGroup(), getContent(), getEventType());
}
/**
* 构建初始化动态配置事件
*
* @param key 配置键
* @param group 分组
* @param content 配置信息
* @return 初始化动态配置事件
*/
public static DynamicConfigEvent initEvent(String key, String group, String content) {
return new DynamicConfigEvent(key, group, content, DynamicConfigEventType.INIT);
}
/**
* 构建创建配置事件
*
* @param key 配置键
* @param group 分组
* @param content 配置信息
* @return 创建配置事件
*/
public static DynamicConfigEvent createEvent(String key, String group, String content) {
return new DynamicConfigEvent(key, group, content, DynamicConfigEventType.CREATE);
}
/**
* 构建修改配置事件
*
* @param key 配置键
* @param group 分组
* @param content 配置信息
* @return 修改配置事件
*/
public static DynamicConfigEvent modifyEvent(String key, String group, String content) {
return new DynamicConfigEvent(key, group, content, DynamicConfigEventType.MODIFY);
}
/**
* 构建删除配置事件
*
* @param key 配置键
* @param group 分组
* @param content 配置信息
* @return 删除配置事件
*/
public static DynamicConfigEvent deleteEvent(String key, String group, String content) {
return new DynamicConfigEvent(key, group, content, DynamicConfigEventType.DELETE);
}
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.componentmodel.design.serialization;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.codedom.CodeExpression;
/**
* The base .NET class managing System.ComponentModel.Design.Serialization.RootContext, System.Windows.Forms.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. Extends {@link NetObject}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.ComponentModel.Design.Serialization.RootContext" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.ComponentModel.Design.Serialization.RootContext</a>
*/
public class RootContext extends NetObject {
/**
* Fully assembly qualified name: System.Windows.Forms.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
*/
public static final String assemblyFullName = "System.Windows.Forms.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
/**
* Assembly name: System.Windows.Forms.Design
*/
public static final String assemblyShortName = "System.Windows.Forms.Design";
/**
* Qualified class name: System.ComponentModel.Design.Serialization.RootContext
*/
public static final String className = "System.ComponentModel.Design.Serialization.RootContext";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public RootContext(Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link RootContext}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link RootContext} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static RootContext cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new RootContext(from.getJCOInstance());
}
// Constructors section
public RootContext() throws Throwable {
}
public RootContext(CodeExpression expression, NetObject value) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException {
try {
// add reference to assemblyName.dll file
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
setJCOInstance((JCObject)classType.NewObject(expression == null ? null : expression.getJCOInstance(), value == null ? null : value.getJCOInstance()));
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Methods section
// Properties section
public CodeExpression getExpression() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("Expression");
return new CodeExpression(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public NetObject getValue() throws Throwable {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject val = (JCObject)classInstance.Get("Value");
return new NetObject(val);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
}
|
package Citas;
import java.util.Calendar;
import Utilidades.AjustarVentana;
import java.awt.Component;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class VistaCitas extends javax.swing.JInternalFrame {
private String[] meses;
private final Calendar calendario;
public VistaCitas() {
initComponents();
AjustarVentana.ajustar(this, 3, 4);
calendario = Calendar.getInstance();
meses = new String[]{"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"};
agregarAnios();
agregarMeses();
agregarDias();
}
private void agregarAnios() {
int anio = calendario.get(Calendar.YEAR);
for (int i = anio; i < anio + 100; i++) {
this.cbAnio.addItem(Integer.toString(i));
}
}
private void agregarMeses() {
int mes = 0;
if (calendario.get(Calendar.YEAR) == (Integer.parseInt(this.cbAnio.getItemAt(this.cbAnio.getSelectedIndex())))) {
mes = calendario.get(Calendar.MONTH);
}
cbMes.removeAllItems();
for (int i = mes; i < 12; i++) {
cbMes.addItem(this.meses[i]);
}
}
private void agregarDias() {
int anio = Integer.valueOf(this.cbAnio.getItemAt(cbAnio.getSelectedIndex()));
int dias = 0;
String mes;
if (cbMes.getSelectedItem() == null) {
mes = "Enero";
} else {
mes = cbMes.getSelectedItem().toString();
}
if (mes.equals("Enero") || mes.equals("Marzo") || mes.equals("Mayo") || mes.equals("Julio") || mes.equals("Agosto") || mes.equals("Octubre") || mes.equals("Diciembre")) {
dias = 31;
} else if (mes.equals("Abril") || mes.equals("Junio") || mes.equals("Septiembre") || mes.equals("Noviembre")) {
dias = 30;
} else if ((anio % 4 == 0 && anio % 100 != 0) || anio % 400 == 0) {
dias = 29;
} else {
dias = 28;
}
this.definirDias(dias);
}
private void definirDias(int dias) {
int dia = 1;
if (meses[calendario.get(Calendar.MONTH)].equals(cbMes.getItemAt(cbMes.getSelectedIndex()))) {
if (calendario.get(Calendar.YEAR) == (Integer.parseInt(this.cbAnio.getItemAt(cbAnio.getSelectedIndex())))) {
dia = calendario.get(Calendar.DAY_OF_MONTH);
}
}
for (int i = dia; i <= dias; i++) {
this.cbDia.addItem(String.valueOf(i));
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblCedula = new javax.swing.JLabel();
lblNombre = new javax.swing.JLabel();
txtCedula = new javax.swing.JTextField();
txtNombre = new javax.swing.JTextField();
btnGuardar = new javax.swing.JButton();
cbDia = new javax.swing.JComboBox<>();
cbMes = new javax.swing.JComboBox<>();
cbAnio = new javax.swing.JComboBox<>();
lblDia = new javax.swing.JLabel();
lblMes = new javax.swing.JLabel();
lblAnio = new javax.swing.JLabel();
lblFecha = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox<>();
setClosable(true);
setTitle("Registro de Citas");
lblCedula.setText("N° de Cedula");
lblNombre.setText("Nombre completo");
txtCedula.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtCedulaKeyTyped(evt);
}
});
txtNombre.setEditable(false);
btnGuardar.setText("Guardar");
cbMes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbMesActionPerforme(evt);
}
});
cbAnio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbAnioActionPerformed(evt);
}
});
lblDia.setText("Dia");
lblMes.setText("Mes");
lblAnio.setText("Año");
lblFecha.setText("Fecha");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblCedula, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblNombre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(lblFecha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(54, 54, 54)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(157, 157, 157))
.addGroup(layout.createSequentialGroup()
.addComponent(lblDia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbDia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblMes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbMes, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblAnio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbAnio, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtNombre, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtCedula, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lblCedula, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtCedula))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(lblNombre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtNombre))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(cbAnio)
.addComponent(lblDia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblMes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblAnio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblFecha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbDia)
.addComponent(cbMes))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtCedulaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCedulaKeyTyped
if (!Character.isDigit(evt.getKeyChar()) || this.txtCedula.getText().length() == 9) {
evt.consume();
}
}//GEN-LAST:event_txtCedulaKeyTyped
private void cbAnioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbAnioActionPerformed
agregarMeses();
}//GEN-LAST:event_cbAnioActionPerformed
private void cbMesActionPerforme(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbMesActionPerforme
agregarDias();
}//GEN-LAST:event_cbMesActionPerforme
private void cbMesActionPerformed(java.awt.event.ActionEvent evt) {
agregarDias();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnGuardar;
private javax.swing.JComboBox<String> cbAnio;
private javax.swing.JComboBox<String> cbDia;
private javax.swing.JComboBox<String> cbMes;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel lblAnio;
private javax.swing.JLabel lblCedula;
private javax.swing.JLabel lblDia;
private javax.swing.JLabel lblFecha;
private javax.swing.JLabel lblMes;
private javax.swing.JLabel lblNombre;
private javax.swing.JTextField txtCedula;
private javax.swing.JTextField txtNombre;
// End of variables declaration//GEN-END:variables
public String getFecha() {
if (this.cbMes.getSelectedIndex() + 1 < 10) {
return this.cbDia.getSelectedItem().toString() + "/0" + (this.cbMes.getSelectedIndex() + 1) + "/" + this.cbAnio.getSelectedItem().toString();
}
return this.cbDia.getSelectedItem().toString() + "/" + (this.cbMes.getSelectedIndex() + 1) + "/" + this.cbAnio.getSelectedItem().toString();
}
public void setFecha(String fecha) {
String fec[] = fecha.split("/");
this.cbDia.addItem(fec[0]);
this.cbMes.setSelectedIndex(Integer.parseInt(fec[1]) - 1);
this.cbAnio.addItem(fec[2]);
}
public Object getAnio() {
return cbAnio.getSelectedItem();
}
public void setAnio(Component anio) {
this.cbAnio.add(anio);
}
public Object getDias() {
return cbDia.getSelectedItem();
}
public void setDias(Component dias) {
this.cbDia.add(dias);
}
public Object getMes() {
return cbMes.getSelectedItem();
}
public void setMes(Component mes) {
this.cbMes.add(mes);
}
public String getCedula() {
return txtCedula.getText();
}
public void setCedula(String cedula) {
this.txtCedula.setText(cedula);
}
public String getNombre() {
return txtNombre.getText();
}
public void setNombre(String nombre) {
this.txtNombre.setText(nombre);
}
@Override
public String toString() {
return "N° de cedula: " + this.getCedula() + " Nombre: " + this.getNombre()
+ " Fecha: " + this.getFecha();
}
}
|
package com.ppdai.infrastructure.mq.biz.dto.request;
public class BaseUiRequst{
private String page;
private String limit;
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getLimit() {
return limit;
}
public void setLimit(String limit) {
this.limit = limit;
}
}
|
/*
* Copyright 2014 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.kythe.extractors.java.standalone;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.hash.Hashing;
import com.google.devtools.kythe.extractors.java.JavaCompilationUnitExtractor;
import com.google.devtools.kythe.extractors.shared.CompilationDescription;
import com.google.devtools.kythe.extractors.shared.FileVNames;
import com.google.devtools.kythe.extractors.shared.IndexInfoUtils;
import com.google.devtools.kythe.platform.indexpack.Archive;
import com.google.devtools.kythe.proto.Analysis.CompilationUnit;
import com.google.devtools.kythe.proto.Analysis.FileData;
import com.google.devtools.kythe.util.JsonUtil;
import com.sun.tools.javac.main.CommandLine;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* General logic for a javac-based {@link CompilationUnit} extractor.
*
* <p>Environment Variables Used (note that these can also be set as JVM system properties):
*
* <p>KYTHE_VNAMES: optional path to a JSON configuration file for {@link FileVNames} to populate
* the {@link CompilationUnit}'s required input {@link VName}s
*
* <p>KYTHE_CORPUS: if KYTHE_VNAMES is not given, all {@link VName}s will be populated with this
* corpus (default {@link DEFAULT_CORPUS})
*
* <p>KYTHE_ROOT_DIRECTORY: required root path for file inputs; the {@link FileData} paths stored in
* the {@link CompilationUnit} will be made to be relative to this directory
*
* <p>KYTHE_OUTPUT_FILE: if set to a non-empty value, write the resulting .kindex file to this path
* instead of using KYTHE_OUTPUT_DIRECTORY
*
* <p>KYTHE_OUTPUT_DIRECTORY: required directory path to store the resulting .kindex file
*
* <p>KYTHE_INDEX_PACK: if set to a non-empty value, interpret KYTHE_OUTPUT_DIRECTORY as the root of
* an indexpack instead of a collection of .kindex files
*/
public abstract class AbstractJavacWrapper {
public static final String DEFAULT_CORPUS = "kythe";
protected abstract CompilationDescription processCompilation(
String[] arguments, JavaCompilationUnitExtractor javaCompilationUnitExtractor)
throws Exception;
protected abstract void passThrough(String[] args) throws Exception;
/**
* Given the command-line arguments to javac, construct a {@link CompilationUnit} and write it to
* a .kindex file or indexpack. Parameters to the extraction logic are passed by environment
* variables (see class comment).
*/
public void process(String[] args) {
JsonUtil.usingTypeRegistry(JavaCompilationUnitExtractor.JSON_TYPE_REGISTRY);
try {
if (!passThroughIfAnalysisOnly(args)) {
String vnamesConfig = System.getenv("KYTHE_VNAMES");
JavaCompilationUnitExtractor extractor;
if (Strings.isNullOrEmpty(vnamesConfig)) {
String corpus = readEnvironmentVariable("KYTHE_CORPUS", DEFAULT_CORPUS);
extractor =
new JavaCompilationUnitExtractor(
corpus, readEnvironmentVariable("KYTHE_ROOT_DIRECTORY"));
} else {
extractor =
new JavaCompilationUnitExtractor(
FileVNames.fromFile(vnamesConfig),
readEnvironmentVariable("KYTHE_ROOT_DIRECTORY"));
}
CompilationDescription indexInfo =
processCompilation(getCleanedUpArguments(args), extractor);
outputIndexInfo(indexInfo);
CompilationUnit compilationUnit = indexInfo.getCompilationUnit();
if (compilationUnit.getHasCompileErrors()) {
System.err.println("Errors encountered during compilation");
System.exit(1);
}
}
} catch (IOException e) {
System.err.printf(
"Unexpected IO error (probably while writing to index file): %s%n", e.toString());
System.err.println(Throwables.getStackTraceAsString(e));
System.exit(2);
} catch (Exception e) {
System.err.printf(
"Unexpected error compiling and indexing java compilation: %s%n", e.toString());
System.err.println(Throwables.getStackTraceAsString(e));
System.exit(2);
}
}
private static void outputIndexInfo(CompilationDescription indexInfo) throws IOException {
String outputFile = System.getenv("KYTHE_OUTPUT_FILE");
if (!Strings.isNullOrEmpty(outputFile)) {
if (outputFile.endsWith(IndexInfoUtils.KZIP_FILE_EXT)) {
IndexInfoUtils.writeKzipToFile(indexInfo, outputFile);
} else {
IndexInfoUtils.writeKindexToFile(indexInfo, outputFile);
}
return;
}
String outputDir = readEnvironmentVariable("KYTHE_OUTPUT_DIRECTORY");
if (Strings.isNullOrEmpty(System.getenv("KYTHE_INDEX_PACK"))) {
writeIndexInfoToFile(outputDir, indexInfo);
return;
}
new Archive(outputDir).writeDescription(indexInfo);
}
private static String[] getCleanedUpArguments(String[] args) throws IOException {
// Expand all @file arguments
List<String> expandedArgs = Lists.newArrayList(CommandLine.parse(args));
// We skip some arguments that would normally be passed to javac:
// -J, these are flags to the java environment running javac.
// -XD, these are internal flags used for special debug information
// when compiling javac itself.
// -Werror, we do not want to treat any warnings as errors.
// -target, we do not care about the compiler outputs
boolean skipArg = false;
List<String> cleanedUpArgs = new ArrayList<>();
for (String arg : expandedArgs) {
if (arg.equals("-target")) {
skipArg = true;
continue;
} else if (!(skipArg
|| arg.startsWith("-J")
|| arg.startsWith("-XD")
|| arg.startsWith("-Werror"))) {
cleanedUpArgs.add(arg);
}
skipArg = false;
}
String[] cleanedUpArgsArray = new String[cleanedUpArgs.size()];
return cleanedUpArgs.toArray(cleanedUpArgsArray);
}
private static void writeIndexInfoToFile(String rootDirectory, CompilationDescription indexInfo)
throws IOException {
String name =
indexInfo
.getCompilationUnit()
.getVName()
.getSignature()
.trim()
.replaceAll("^/+|/+$", "")
.replace('/', '_');
String path = IndexInfoUtils.getKindexPath(rootDirectory, name).toString();
IndexInfoUtils.writeKindexToFile(indexInfo, path);
}
private boolean passThroughIfAnalysisOnly(String[] args) throws Exception {
// If '-proc:only' is passed as an argument, this is not a source file compilation, but an
// analysis. We will let the real java compiler do its work.
boolean hasProcOnly = false;
for (String arg : args) {
if (arg.equals("-proc:only")) {
hasProcOnly = true;
break;
}
}
if (hasProcOnly) {
passThrough(args);
return true;
}
return false;
}
protected static String createTargetFromSourceFiles(List<String> sourceFiles) {
List<String> sortedSourceFiles = Ordering.natural().sortedCopy(sourceFiles);
String joinedSourceFiles = Joiner.on(":").join(sortedSourceFiles);
return "#" + Hashing.sha256().hashUnencodedChars(joinedSourceFiles);
}
protected static List<String> splitPaths(String path) {
return path == null ? Collections.<String>emptyList() : Splitter.on(':').splitToList(path);
}
protected static List<String> splitCSV(String lst) {
return lst == null ? Collections.<String>emptyList() : Splitter.on(',').splitToList(lst);
}
static String readEnvironmentVariable(String variableName) {
return readEnvironmentVariable(variableName, null);
}
static String readEnvironmentVariable(String variableName, String defaultValue) {
// First see if we have a system property.
String result = System.getProperty(variableName);
if (Strings.isNullOrEmpty(result)) {
// Fall back to the environment variable.
result = System.getenv(variableName);
}
if (Strings.isNullOrEmpty(result)) {
if (Strings.isNullOrEmpty(defaultValue)) {
System.err.printf("Missing environment variable: %s%n", variableName);
System.exit(1);
}
result = defaultValue;
}
return result;
}
protected static List<String> getSourceList(Collection<File> files) {
List<String> sources = new ArrayList<>();
for (File file : files) {
sources.add(file.getPath());
}
return sources;
}
}
|
package it.unipd.dei.bding.database;
import it.unipd.dei.bding.resource.IsAbout;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Creates a new type of the exam that is about a disease into the database.
*
* @author leoforfriendsDB
* @version 1.00
*/
public class CreateIsAboutDatabase
{
/**
* The SQL statement to be executed
*/
private static final String STATEMENT = "INSERT INTO treatit.is_about (disease, exam_type) VALUES (?, ?)";
/**
* The connection to the database
*/
private final Connection con;
/**
* The type of the exam that is about a disease to be stored into the database
*/
private final IsAbout is_about;
/**
* Creates a new object for storing a type of the exam that is about a disease into the database.
*
* @param con
* the connection to the database.
* @param is_about
* the type of the exam that is about a disease to be stored into the database.
*/
public CreateIsAboutDatabase(final Connection con, final IsAbout is_about)
{
this.con = con;
this.is_about = is_about;
}
/**
* Stores a new type of the exam that is about a disease into the database
*
* @throws SQLException
* if any error occurs while storing the type of the exam that is about a disease.
*/
public void createIsAbout() throws SQLException
{
PreparedStatement pstmt = null;
try
{
pstmt = con.prepareStatement(STATEMENT);
pstmt.setString(1, is_about.getDisease());
pstmt.setString(2, is_about.getExam_type());
pstmt.execute();
}
finally
{
if (pstmt != null)
{
pstmt.close();
}
con.close();
}
}
}
|
package fr.lucluc;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import net.md_5.bungee.api.ChatColor;
public class Eggrenade extends JavaPlugin implements Listener {
public static Plugin instance;
public void onEnable() {
instance = this;
Bukkit.getServer().getPluginManager().registerEvents(new Events(), this);
getConfig().options().copyDefaults();
saveDefaultConfig();
}
public static void sm(Player player, String msg) {
player.sendMessage(ChatColor.translateAlternateColorCodes('&', msg));
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (label.equalsIgnoreCase("eggrenade")) {
if (sender.hasPermission("eggrenade.commands")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.RED + "Try /eggrenade reload");
}
if (args.length == 1) {
if (args[0].equalsIgnoreCase("reload")) {
reloadConfig();
sender.sendMessage(ChatColor.GREEN + "Eggrenade reloaded!");
} else {
sender.sendMessage(ChatColor.GREEN + "Unknow command. Try /eggrenade reload");
}
}
}
} else {
sender.sendMessage(ChatColor.RED + "You don't have the permissions.");
}
return false;
}
}
|
package com.codepath.simpletodo.dbhandlers;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by nedim on 9/25/16.
*/
abstract public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "simple_todo_app";
protected static final String TABLE_TODO_ITEMS = "todo_items";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_TODO_ITEMS +
" ( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"text TEXT, " +
"position INTEGER ) ";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + TABLE_TODO_ITEMS;
db.execSQL(sql);
onCreate(db);
}
}
|
/*
* Copyright (C) 2017
*
* 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 edu.gatech.mas.letsteach.itemanimator;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.support.v7.widget.RecyclerView;
import android.view.animation.Interpolator;
@SuppressWarnings("FieldCanBeLocal")
class SlideInUpDelayedAnimator extends BaseItemAnimator {
private final int offsetDelay = 200;
private final Interpolator mInterpolator;
SlideInUpDelayedAnimator(Interpolator interpolator) {
mInterpolator = interpolator;
}
@Override
protected void preAnimateAdd(RecyclerView.ViewHolder holder) {
ViewCompat.setTranslationY(holder.itemView, holder.itemView.getHeight());
ViewCompat.setAlpha(holder.itemView, 0);
}
@Override
protected ViewPropertyAnimatorCompat onAnimatedAdd(RecyclerView.ViewHolder holder) {
return ViewCompat.animate(holder.itemView)
.translationY(0)
.setInterpolator(mInterpolator)
.setStartDelay(offsetDelay*holder.getLayoutPosition());
}
}
|
/*
* 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.cassandra.hints;
import java.io.Closeable;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.cassandra.config.Config;
import org.apache.cassandra.net.MessagingService;
import sun.nio.ch.DirectBuffer;
/**
* A primitive pool of {@link HintsBuffer} buffers. Under normal conditions should only hold two buffers - the currently
* written to one, and a reserve buffer to switch to when the first one is beyond capacity.
*/
final class HintsBufferPool implements Closeable
{
interface FlushCallback
{
void flush(HintsBuffer buffer, HintsBufferPool pool);
}
static final int MAX_ALLOCATED_BUFFERS = Integer.getInteger(Config.PROPERTY_PREFIX + "MAX_HINT_BUFFERS", 3);
private volatile HintsBuffer currentBuffer;
private final BlockingQueue<HintsBuffer> reserveBuffers;
private final int bufferSize;
private final FlushCallback flushCallback;
private int allocatedBuffers = 0;
HintsBufferPool(int bufferSize, FlushCallback flushCallback)
{
reserveBuffers = new LinkedBlockingQueue<>();
this.bufferSize = bufferSize;
this.flushCallback = flushCallback;
}
/**
* @param hostIds host ids of the hint's target nodes
* @param hint the hint to store
*/
void write(Iterable<UUID> hostIds, Hint hint)
{
int hintSize = (int) Hint.serializer.serializedSize(hint, MessagingService.current_version);
try (HintsBuffer.Allocation allocation = allocate(hintSize))
{
allocation.write(hostIds, hint);
}
}
private HintsBuffer.Allocation allocate(int hintSize)
{
HintsBuffer current = currentBuffer();
while (true)
{
HintsBuffer.Allocation allocation = current.allocate(hintSize);
if (allocation != null)
return allocation;
// allocation failed due to insufficient size remaining in the buffer
if (switchCurrentBuffer(current))
flushCallback.flush(current, this);
current = currentBuffer;
}
}
void offer(HintsBuffer buffer)
{
if (!reserveBuffers.offer(buffer))
throw new RuntimeException("Failed to store buffer");
}
// A wrapper to ensure a non-null currentBuffer value on the first call.
HintsBuffer currentBuffer()
{
if (currentBuffer == null)
initializeCurrentBuffer();
return currentBuffer;
}
private synchronized void initializeCurrentBuffer()
{
if (currentBuffer == null)
currentBuffer = createBuffer();
}
private synchronized boolean switchCurrentBuffer(HintsBuffer previous)
{
if (currentBuffer != previous)
return false;
HintsBuffer buffer = reserveBuffers.poll();
if (buffer == null && allocatedBuffers >= MAX_ALLOCATED_BUFFERS)
{
try
{
//This BlockingQueue.take is a target for byteman in HintsBufferPoolTest
buffer = reserveBuffers.take();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
currentBuffer = buffer == null ? createBuffer() : buffer;
return true;
}
private HintsBuffer createBuffer()
{
allocatedBuffers++;
return HintsBuffer.create(bufferSize);
}
public void close()
{
currentBuffer.free();
}
}
|
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.DispatcherType;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.core.Ordered;
import org.springframework.util.StringUtils;
/**
* Configuration properties for Spring Security.
*
* @author Dave Syer
* @author Andy Wilkinson
* @author Madhura Bhave
* @since 1.0.0
*/
@ConfigurationProperties(prefix = "spring.security")
public class SecurityProperties {
/**
* Order applied to the WebSecurityConfigurerAdapter that is used to configure basic
* authentication for application endpoints. If you want to add your own
* authentication for all or some of those endpoints the best thing to do is to add
* your own WebSecurityConfigurerAdapter with lower order.
*/
public static final int BASIC_AUTH_ORDER = Ordered.LOWEST_PRECEDENCE - 5;
/**
* Order applied to the WebSecurityConfigurer that ignores standard static resource
* paths.
*/
public static final int IGNORED_ORDER = Ordered.HIGHEST_PRECEDENCE;
/**
* Default order of Spring Security's Filter in the servlet container (i.e. amongst
* other filters registered with the container). There is no connection between this
* and the {@code @Order} on a WebSecurityConfigurer.
*/
public static final int DEFAULT_FILTER_ORDER = OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100;
private final Filter filter = new Filter();
private User user = new User();
public User getUser() {
return this.user;
}
public Filter getFilter() {
return this.filter;
}
public static class Filter {
/**
* Security filter chain order.
*/
private int order = DEFAULT_FILTER_ORDER;
/**
* Security filter chain dispatcher types.
*/
private Set<DispatcherType> dispatcherTypes = new HashSet<>(
Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST));
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
public Set<DispatcherType> getDispatcherTypes() {
return this.dispatcherTypes;
}
public void setDispatcherTypes(Set<DispatcherType> dispatcherTypes) {
this.dispatcherTypes = dispatcherTypes;
}
}
public static class User {
/**
* Default user name.
*/
private String name = "user";
/**
* Password for the default user name.
*/
private String password = UUID.randomUUID().toString();
/**
* Granted roles for the default user name.
*/
private List<String> roles = new ArrayList<>();
private boolean passwordGenerated = true;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
if (!StringUtils.hasLength(password)) {
return;
}
this.passwordGenerated = false;
this.password = password;
}
public List<String> getRoles() {
return this.roles;
}
public void setRoles(List<String> roles) {
this.roles = new ArrayList<>(roles);
}
public boolean isPasswordGenerated() {
return this.passwordGenerated;
}
}
}
|
/**
* 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.
*/
/**
* This package provides a mechanism for satisfying the storage policy of a
* path.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
package org.apache.hadoop.hdfs.server.sps;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
|
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.text.format;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.util.Color;
import org.spongepowered.api.util.annotation.CatalogedBy;
/**
* Represents the color of the text of a {@link Text}.
*
* @see TextColors
*/
@CatalogedBy(TextColors.class)
public interface TextColor extends CatalogType {
/**
* Returns the corresponding {@link Color} for this {@link TextColor}.
*
* @return The RGB color of this text color
*/
Color getColor();
}
|
package com.fakemall.dao;
import com.fakemall.model.OrderItem;
public interface OrderItemMapper {
int deleteByPrimaryKey(Integer id);
int insert(OrderItem record);
int insertSelective(OrderItem record);
OrderItem selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(OrderItem record);
int updateByPrimaryKey(OrderItem record);
}
|
package org.mightyfish.crypto.prng.drbg;
import org.mightyfish.crypto.Mac;
import org.mightyfish.crypto.params.KeyParameter;
import org.mightyfish.crypto.prng.EntropySource;
import org.mightyfish.util.Arrays;
/**
* A SP800-90A HMAC DRBG.
*/
public class HMacSP800DRBG
implements SP80090DRBG
{
private final static long RESEED_MAX = 1L << (48 - 1);
private final static int MAX_BITS_REQUEST = 1 << (19 - 1);
private byte[] _K;
private byte[] _V;
private long _reseedCounter;
private EntropySource _entropySource;
private Mac _hMac;
/**
* Construct a SP800-90A Hash DRBG.
* <p>
* Minimum entropy requirement is the security strength requested.
* </p>
* @param hMac Hash MAC to base the DRBG on.
* @param securityStrength security strength required (in bits)
* @param entropySource source of entropy to use for seeding/reseeding.
* @param personalizationString personalization string to distinguish this DRBG (may be null).
* @param nonce nonce to further distinguish this DRBG (may be null).
*/
public HMacSP800DRBG(Mac hMac, int securityStrength, EntropySource entropySource, byte[] personalizationString, byte[] nonce)
{
if (securityStrength > Utils.getMaxSecurityStrength(hMac))
{
throw new IllegalArgumentException("Requested security strength is not supported by the derivation function");
}
if (entropySource.entropySize() < securityStrength)
{
throw new IllegalArgumentException("Not enough entropy for security strength required");
}
_entropySource = entropySource;
_hMac = hMac;
byte[] entropy = entropySource.getEntropy();
byte[] seedMaterial = Arrays.concatenate(entropy, nonce, personalizationString);
_K = new byte[hMac.getMacSize()];
_V = new byte[_K.length];
Arrays.fill(_V, (byte)1);
hmac_DRBG_Update(seedMaterial);
_reseedCounter = 1;
}
private void hmac_DRBG_Update(byte[] seedMaterial)
{
hmac_DRBG_Update_Func(seedMaterial, (byte)0x00);
if (seedMaterial != null)
{
hmac_DRBG_Update_Func(seedMaterial, (byte)0x01);
}
}
private void hmac_DRBG_Update_Func(byte[] seedMaterial, byte vValue)
{
_hMac.init(new KeyParameter(_K));
_hMac.update(_V, 0, _V.length);
_hMac.update(vValue);
if (seedMaterial != null)
{
_hMac.update(seedMaterial, 0, seedMaterial.length);
}
_hMac.doFinal(_K, 0);
_hMac.init(new KeyParameter(_K));
_hMac.update(_V, 0, _V.length);
_hMac.doFinal(_V, 0);
}
/**
* Return the block size (in bits) of the DRBG.
*
* @return the number of bits produced on each round of the DRBG.
*/
public int getBlockSize()
{
return _V.length * 8;
}
/**
* Populate a passed in array with random data.
*
* @param output output array for generated bits.
* @param additionalInput additional input to be added to the DRBG in this step.
* @param predictionResistant true if a reseed should be forced, false otherwise.
*
* @return number of bits generated, -1 if a reseed required.
*/
public int generate(byte[] output, byte[] additionalInput, boolean predictionResistant)
{
int numberOfBits = output.length * 8;
if (numberOfBits > MAX_BITS_REQUEST)
{
throw new IllegalArgumentException("Number of bits per request limited to " + MAX_BITS_REQUEST);
}
if (_reseedCounter > RESEED_MAX)
{
return -1;
}
if (predictionResistant)
{
reseed(additionalInput);
additionalInput = null;
}
// 2.
if (additionalInput != null)
{
hmac_DRBG_Update(additionalInput);
}
// 3.
byte[] rv = new byte[output.length];
int m = output.length / _V.length;
_hMac.init(new KeyParameter(_K));
for (int i = 0; i < m; i++)
{
_hMac.update(_V, 0, _V.length);
_hMac.doFinal(_V, 0);
System.arraycopy(_V, 0, rv, i * _V.length, _V.length);
}
if (m * _V.length < rv.length)
{
_hMac.update(_V, 0, _V.length);
_hMac.doFinal(_V, 0);
System.arraycopy(_V, 0, rv, m * _V.length, rv.length - (m * _V.length));
}
hmac_DRBG_Update(additionalInput);
_reseedCounter++;
System.arraycopy(rv, 0, output, 0, output.length);
return numberOfBits;
}
/**
* Reseed the DRBG.
*
* @param additionalInput additional input to be added to the DRBG in this step.
*/
public void reseed(byte[] additionalInput)
{
byte[] entropy = _entropySource.getEntropy();
byte[] seedMaterial = Arrays.concatenate(entropy, additionalInput);
hmac_DRBG_Update(seedMaterial);
_reseedCounter = 1;
}
}
|
package software.amazon.disco.agent.sql.source;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
public class MyStatementImpl implements Statement {
@Override
public ResultSet executeQuery(String sql) throws SQLException {
return null;
}
@Override
public int executeUpdate(String sql) throws SQLException {
return 0;
}
@Override
public void close() throws SQLException {
}
@Override
public int getMaxFieldSize() throws SQLException {
return 0;
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
}
@Override
public int getMaxRows() throws SQLException {
return 0;
}
@Override
public void setMaxRows(int max) throws SQLException {
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
}
@Override
public int getQueryTimeout() throws SQLException {
return 0;
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
}
@Override
public void cancel() throws SQLException {
}
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void clearWarnings() throws SQLException {
}
@Override
public void setCursorName(String name) throws SQLException {
}
@Override
public boolean execute(String sql) throws SQLException {
return false;
}
@Override
public ResultSet getResultSet() throws SQLException {
return null;
}
@Override
public int getUpdateCount() throws SQLException {
return 0;
}
@Override
public boolean getMoreResults() throws SQLException {
return false;
}
@Override
public void setFetchDirection(int direction) throws SQLException {
}
@Override
public int getFetchDirection() throws SQLException {
return 0;
}
@Override
public void setFetchSize(int rows) throws SQLException {
}
@Override
public int getFetchSize() throws SQLException {
return 0;
}
@Override
public int getResultSetConcurrency() throws SQLException {
return 0;
}
@Override
public int getResultSetType() throws SQLException {
return 0;
}
@Override
public void addBatch(String sql) throws SQLException {
}
@Override
public void clearBatch() throws SQLException {
}
@Override
public int[] executeBatch() throws SQLException {
return new int[0];
}
@Override
public Connection getConnection() throws SQLException {
return null;
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return false;
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return null;
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return 0;
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return 0;
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
return 0;
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return false;
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return false;
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
return false;
}
@Override
public int getResultSetHoldability() throws SQLException {
return 0;
}
@Override
public boolean isClosed() throws SQLException {
return false;
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
}
@Override
public boolean isPoolable() throws SQLException {
return false;
}
@Override
public void closeOnCompletion() throws SQLException {
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return false;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
public abstract class MyAbstractStatement extends MyStatementImpl {
public abstract int execute();
}
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.example.hellojnicallback;
import android.os.Build;
import android.support.annotation.Keep;
import android.util.Log;
/*
* A helper class to demo that JNI could call into:
* private non-static function
* public non-static function
* static public function
* The calling code is inside hello-jnicallback.c
*/
public class JniHandler {
/*
* Print out status to logcat
*/
@Keep
private void updateStatus(String msg) {
if (msg.toLowerCase().contains("error")) {
Log.e("JniHandler", "Native Err: " + msg);
} else {
Log.i("JniHandler", "Native Msg: " + msg);
}
}
/*
* Return OS build version: a static function
*/
@Keep
static public String getBuildVersion() {
return Build.VERSION.RELEASE;
}
/*
* Return Java memory info
*/
@Keep
public long getRuntimeMemorySize() {
return Runtime.getRuntime().freeMemory();
}
}
|
/**
* 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.pinot.segment.local.realtime.impl.dictionary;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReferenceArray;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.pinot.segment.local.io.readerwriter.PinotDataBufferMemoryManager;
import org.apache.pinot.segment.spi.memory.PinotDataBuffer;
/**
* Off-heap variable length mutable bytes store.
* <p>The class is thread-safe for single writer and multiple readers.
* <p>There are two sets of buffers allocated for the store:
* <ul>
* <li>
* Offset buffer: stores the value end offsets. The end offset here is the global offset for all the value buffers
* instead of the offset inside one value buffer (e.g. offset 9 in the 5th value buffer will have global offset of
* 4 * VALUE_BUFFER_SIZE + 9). New offset buffer is allocated when the previous buffer is filled up. The first entry
* of each offset buffer stores the end offset of the last value (or 0 for the first offset buffer) so that we can
* always get the previous and current value's end offset from the same buffer. Note that we use int type for the
* offset, so each bytes store can hold at most 2^31 = 2GB total size of values.
* </li>
* <li>
* Value buffer: stores the values. For performance concern, to avoid reading one value from multiple buffers, each
* value is stored in one value buffer (no cross-buffer value allowed), and has a size limit of the
* VALUE_BUFFER_SIZE (1MB). New value buffer is allocated when the previous buffer cannot hold the new added value.
* </li>
* </ul>
* <p>The maximum capacity for the bytes store is 2^24 ~= 17M values and 2^31 = 2GB total size of values.
*/
@ThreadSafe
public class OffHeapMutableBytesStore implements Closeable {
private static final byte[] EMPTY_BYTES = new byte[0];
// Each offset buffer holds 8_192 end offsets and one extra end offset for the last value in the previous buffer (or 0
// for the first buffer)
// OFFSET_BUFFER_SIZE = (8_192 + 1) * 4 = 32_772
private static final int OFFSET_BUFFER_SHIFT_OFFSET = 13;
private static final int OFFSET_BUFFER_SIZE = ((1 << OFFSET_BUFFER_SHIFT_OFFSET) + 1) << 2;
private static final int OFFSET_BUFFER_MASK = (1 << OFFSET_BUFFER_SHIFT_OFFSET) - 1;
// Each value buffer holds up to 1_048_576 bytes, which is also the size limit for each value
// VALUE_BUFFER_SIZE = 1_048_576
private static final int VALUE_BUFFER_SHIFT_OFFSET = 20;
private static final int VALUE_BUFFER_SIZE = 1 << VALUE_BUFFER_SHIFT_OFFSET;
private static final int VALUE_BUFFER_MASK = (1 << VALUE_BUFFER_SHIFT_OFFSET) - 1;
// With at most 2_048 buffers, we can store about 17M values of total size up to 2GB
// MAX_NUM_BUFFERS = 2_048
private static final int MAX_NUM_BUFFERS = 1 << 11;
private final AtomicReferenceArray<PinotDataBuffer> _offsetBuffers = new AtomicReferenceArray<>(MAX_NUM_BUFFERS);
private final AtomicReferenceArray<PinotDataBuffer> _valueBuffers = new AtomicReferenceArray<>(MAX_NUM_BUFFERS);
private final PinotDataBufferMemoryManager _memoryManager;
private final String _allocationContext;
// Global end offset of the previous added value
private int _previousValueEndOffset;
// Number of values added
private transient int _numValues;
// Total size of the OffHeap buffers (both offset buffers and value buffers)
private transient int _totalBufferSize;
public OffHeapMutableBytesStore(PinotDataBufferMemoryManager memoryManager, String allocationContext) {
_memoryManager = memoryManager;
_allocationContext = allocationContext;
}
/**
* Adds a value into the bytes store. The size of the given value should be smaller or equal to the VALUE_BUFFER_SIZE
* (1MB).
*/
public int add(byte[] value) {
int offsetBufferIndex = _numValues >>> OFFSET_BUFFER_SHIFT_OFFSET;
int offsetIndex = _numValues & OFFSET_BUFFER_MASK;
PinotDataBuffer offsetBuffer;
// If this is the first entry in the offset buffer, allocate a new buffer and store the end offset of the previous
// value
if (offsetIndex == 0) {
offsetBuffer = _memoryManager.allocate(OFFSET_BUFFER_SIZE, _allocationContext);
offsetBuffer.putInt(0, _previousValueEndOffset);
_offsetBuffers.set(offsetBufferIndex, offsetBuffer);
_totalBufferSize += OFFSET_BUFFER_SIZE;
} else {
offsetBuffer = _offsetBuffers.get(offsetBufferIndex);
}
int valueLength = value.length;
if (valueLength == 0) {
offsetBuffer.putInt((offsetIndex + 1) << 2, _previousValueEndOffset);
return _numValues++;
}
int valueBufferIndex = (_previousValueEndOffset + valueLength - 1) >>> VALUE_BUFFER_SHIFT_OFFSET;
PinotDataBuffer valueBuffer;
int valueStartOffset;
// If the current value buffer does not have enough space, allocate a new buffer to store the value
if ((_previousValueEndOffset - 1) >>> VALUE_BUFFER_SHIFT_OFFSET != valueBufferIndex) {
valueBuffer = _memoryManager.allocate(VALUE_BUFFER_SIZE, _allocationContext);
_valueBuffers.set(valueBufferIndex, valueBuffer);
_totalBufferSize += VALUE_BUFFER_SIZE;
valueStartOffset = valueBufferIndex << VALUE_BUFFER_SHIFT_OFFSET;
} else {
valueBuffer = _valueBuffers.get(valueBufferIndex);
valueStartOffset = _previousValueEndOffset;
}
int valueEndOffset = valueStartOffset + valueLength;
offsetBuffer.putInt((offsetIndex + 1) << 2, valueEndOffset);
valueBuffer.readFrom(valueStartOffset & VALUE_BUFFER_MASK, value);
_previousValueEndOffset = valueEndOffset;
return _numValues++;
}
/**
* Returns the value at the given index. The given index should be smaller than the number of values already added.
*/
@SuppressWarnings("Duplicates")
public byte[] get(int index) {
assert index < _numValues;
int offsetBufferIndex = index >>> OFFSET_BUFFER_SHIFT_OFFSET;
PinotDataBuffer offsetBuffer = _offsetBuffers.get(offsetBufferIndex);
int offsetIndex = index & OFFSET_BUFFER_MASK;
int previousValueEndOffset = offsetBuffer.getInt(offsetIndex << 2);
int valueEndOffset = offsetBuffer.getInt((offsetIndex + 1) << 2);
if (previousValueEndOffset == valueEndOffset) {
return EMPTY_BYTES;
}
int valueBufferIndex = (valueEndOffset - 1) >>> VALUE_BUFFER_SHIFT_OFFSET;
int startOffsetInValueBuffer;
int valueLength;
if ((previousValueEndOffset - 1) >>> VALUE_BUFFER_SHIFT_OFFSET != valueBufferIndex) {
// The first value in the value buffer
startOffsetInValueBuffer = 0;
valueLength = valueEndOffset & VALUE_BUFFER_MASK;
} else {
// Not the first value in the value buffer
startOffsetInValueBuffer = previousValueEndOffset & VALUE_BUFFER_MASK;
valueLength = valueEndOffset - previousValueEndOffset;
}
byte[] value = new byte[valueLength];
_valueBuffers.get(valueBufferIndex).copyTo(startOffsetInValueBuffer, value);
return value;
}
/**
* Returns whether the value at the given index equals the given value. The given index should be smaller than the
* number of values already added.
* <p>This method should be preferable when checking whether a value equals the value at a specific index in the bytes
* store compared to calling {@link #get(int)} and then compare the values because if the value length does not match,
* the value fetch can be skipped.
*/
@SuppressWarnings("Duplicates")
public boolean equalsValueAt(int index, byte[] valueToCompare) {
assert index < _numValues;
int offsetBufferIndex = index >>> OFFSET_BUFFER_SHIFT_OFFSET;
PinotDataBuffer offsetBuffer = _offsetBuffers.get(offsetBufferIndex);
int offsetIndex = index & OFFSET_BUFFER_MASK;
int previousValueEndOffset = offsetBuffer.getInt(offsetIndex << 2);
int valueEndOffset = offsetBuffer.getInt((offsetIndex + 1) << 2);
int inputValueLength = valueToCompare.length;
if (previousValueEndOffset == valueEndOffset) {
return inputValueLength == 0;
}
// Check value length first
int valueBufferIndex = (valueEndOffset - 1) >>> VALUE_BUFFER_SHIFT_OFFSET;
int startOffsetInValueBuffer;
if ((previousValueEndOffset - 1) >>> VALUE_BUFFER_SHIFT_OFFSET != valueBufferIndex) {
// The first value in the value buffer
if ((valueEndOffset & VALUE_BUFFER_MASK) != inputValueLength) {
return false;
}
startOffsetInValueBuffer = 0;
} else {
// Not the first value in the value buffer
if (valueEndOffset - previousValueEndOffset != inputValueLength) {
return false;
}
startOffsetInValueBuffer = previousValueEndOffset & VALUE_BUFFER_MASK;
}
// Value length matches, check value
PinotDataBuffer valueBuffer = _valueBuffers.get(valueBufferIndex);
if (inputValueLength <= PinotDataBuffer.BULK_BYTES_PROCESSING_THRESHOLD) {
for (int i = 0; i < inputValueLength; i++) {
if (valueToCompare[i] != valueBuffer.getByte(startOffsetInValueBuffer + i)) {
return false;
}
}
return true;
} else {
byte[] value = new byte[inputValueLength];
valueBuffer.copyTo(startOffsetInValueBuffer, value);
for (int i = 0; i < inputValueLength; i++) {
if (valueToCompare[i] != value[i]) {
return false;
}
}
return true;
}
}
public int getNumValues() {
return _numValues;
}
public int getTotalBufferSize() {
return _totalBufferSize;
}
@Override
public void close()
throws IOException {
for (int i = 0; i < MAX_NUM_BUFFERS; i++) {
PinotDataBuffer offsetBuffer = _offsetBuffers.get(i);
if (offsetBuffer != null) {
offsetBuffer.close();
} else {
break;
}
}
for (int i = 0; i < MAX_NUM_BUFFERS; i++) {
PinotDataBuffer valueBuffer = _valueBuffers.get(i);
if (valueBuffer != null) {
valueBuffer.close();
} else {
break;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.