text
stringlengths
7
1.01M
/* * 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.internal; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.search.Scroll; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; import static org.elasticsearch.search.Scroll.readScroll; /** * Shard level search request that gets created and consumed on the local node. * Used by warmers and by api that need to create a search context within their execution. * * Source structure: * <pre> * { * from : 0, size : 20, (optional, can be set on the request) * sort : { "name.first" : {}, "name.last" : { reverse : true } } * fields : [ "name.first", "name.last" ] * query : { ... } * aggs : { * "agg1" : { * terms : { ... } * } * } * } * </pre> */ public class ShardSearchLocalRequest implements ShardSearchRequest { private ShardId shardId; private int numberOfShards; private SearchType searchType; private Scroll scroll; private String[] types = Strings.EMPTY_ARRAY; private String[] filteringAliases; private SearchSourceBuilder source; private Boolean requestCache; private long nowInMillis; private boolean profile; ShardSearchLocalRequest() { } ShardSearchLocalRequest(SearchRequest searchRequest, ShardRouting shardRouting, int numberOfShards, String[] filteringAliases, long nowInMillis) { this(shardRouting.shardId(), numberOfShards, searchRequest.searchType(), searchRequest.source(), searchRequest.types(), searchRequest.requestCache()); this.scroll = searchRequest.scroll(); this.filteringAliases = filteringAliases; this.nowInMillis = nowInMillis; } public ShardSearchLocalRequest(String[] types, long nowInMillis) { this.types = types; this.nowInMillis = nowInMillis; } public ShardSearchLocalRequest(String[] types, long nowInMillis, String[] filteringAliases) { this(types, nowInMillis); this.filteringAliases = filteringAliases; } public ShardSearchLocalRequest(ShardId shardId, int numberOfShards, SearchType searchType, SearchSourceBuilder source, String[] types, Boolean requestCache) { this.shardId = shardId; this.numberOfShards = numberOfShards; this.searchType = searchType; this.source = source; this.types = types; this.requestCache = requestCache; } @Override public ShardId shardId() { return shardId; } @Override public String[] types() { return types; } @Override public SearchSourceBuilder source() { return source; } @Override public void source(SearchSourceBuilder source) { this.source = source; } @Override public int numberOfShards() { return numberOfShards; } @Override public SearchType searchType() { return searchType; } @Override public String[] filteringAliases() { return filteringAliases; } @Override public long nowInMillis() { return nowInMillis; } @Override public Boolean requestCache() { return requestCache; } @Override public Scroll scroll() { return scroll; } @Override public void setProfile(boolean profile) { this.profile = profile; } @Override public boolean isProfile() { return profile; } protected void innerReadFrom(StreamInput in) throws IOException { shardId = ShardId.readShardId(in); searchType = SearchType.fromId(in.readByte()); numberOfShards = in.readVInt(); if (in.readBoolean()) { scroll = readScroll(in); } if (in.readBoolean()) { source = new SearchSourceBuilder(in); } types = in.readStringArray(); filteringAliases = in.readStringArray(); nowInMillis = in.readVLong(); requestCache = in.readOptionalBoolean(); } protected void innerWriteTo(StreamOutput out, boolean asKey) throws IOException { shardId.writeTo(out); out.writeByte(searchType.id()); if (!asKey) { out.writeVInt(numberOfShards); } if (scroll == null) { out.writeBoolean(false); } else { out.writeBoolean(true); scroll.writeTo(out); } if (source == null) { out.writeBoolean(false); } else { out.writeBoolean(true); source.writeTo(out); } out.writeStringArray(types); out.writeStringArrayNullable(filteringAliases); if (!asKey) { out.writeVLong(nowInMillis); } out.writeOptionalBoolean(requestCache); } @Override public BytesReference cacheKey() throws IOException { BytesStreamOutput out = new BytesStreamOutput(); this.innerWriteTo(out, true); // copy it over, most requests are small, we might as well copy to make sure we are not sliced... // we could potentially keep it without copying, but then pay the price of extra unused bytes up to a page return new BytesArray(out.bytes().toBytesRef(), true);// do a deep copy } @Override public void rewrite(QueryShardContext context) throws IOException { SearchSourceBuilder source = this.source; SearchSourceBuilder rewritten = null; while (rewritten != source) { rewritten = source.rewrite(context); source = rewritten; } this.source = source; } }
package cz.tacr.elza.domain; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Type; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Evidence možných datových typů atributů archivního popisu. * Evidence je společná pro všechny archivní pomůcky. * * @author Tomáš Kubový [<a href="mailto:tomas.kubovy@marbes.cz">tomas.kubovy@marbes.cz</a>] * @since 20.8.2015 */ @Entity(name = "rul_data_type") @Table @Cache(region = "domain", usage = CacheConcurrencyStrategy.READ_WRITE) @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class RulDataType { @Id @GeneratedValue @Access(AccessType.PROPERTY) // required to read id without fetch from db private Integer dataTypeId; @Column(length = 50, nullable = false) private String code; @Column(length = 250, nullable = false) private String name; @Column(nullable = false) @Lob @Type(type = "org.hibernate.type.TextType") private String description; @Column(nullable = false) private Boolean regexpUse; @Column(nullable = false) private Boolean textLengthLimitUse; @Column(length = 250, nullable = false) private String storageTable; public Integer getDataTypeId() { return dataTypeId; } public void setDataTypeId(final Integer dataTypeId) { this.dataTypeId = dataTypeId; } public String getCode() { return code; } public void setCode(final String code) { this.code = code; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(final String description) { this.description = description; } /** * @return příznak, zda je možná u datového typu kontrola na regulární výraz. */ public Boolean getRegexpUse() { return regexpUse; } /** * @param regexpUse příznak, zda je možná u datového typu kontrola na regulární výraz. */ public void setRegexpUse(final Boolean regexpUse) { this.regexpUse = regexpUse; } /** * @return příznak, zda je možná u datového typu kontrola na maximální možnou délku textového řetězce. */ public Boolean getTextLengthLimitUse() { return textLengthLimitUse; } /** * @param textLengthLimitUse příznak, zda je možná u datového typu kontrola na maximální možnou délku textového řetězce. */ public void setTextLengthLimitUse(final Boolean textLengthLimitUse) { this.textLengthLimitUse = textLengthLimitUse; } /** * @return informace, kde je ulozena hodnota (arr_data_xxx). */ public String getStorageTable() { return storageTable; } /** * @param storageTable informace, kde je ulozena hodnota (arr_data_xxx). */ public void setStorageTable(final String storageTable) { this.storageTable = storageTable; } @Override public boolean equals(final Object obj) { if (!(obj instanceof RulDataType)) { return false; } if (this == obj) { return true; } RulDataType other = (RulDataType) obj; return new EqualsBuilder().append(dataTypeId, other.getDataTypeId()).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(dataTypeId).append(name).append(code).toHashCode(); } @Override public String toString() { return "RulDataType pk=" + dataTypeId; } }
/* * Created on May 17, 2006 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package biomight.body.brain.prosencephalon.telencephalon.temporallobe; /** * @author SurferJim * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class MiddleTemporalGyrus { }
package com.discordbot.LocalUtils; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class ArrayObjectUtilTest { @Test public void convertObjectToList() { ArrayList<String> data = new ArrayList<>(); data.add("abc"); data.add("def1"); Object[] toParse = data.toArray(); List<?> returned = ArrayObjectUtil.convertObjectToList(toParse); Assert.assertNotNull(returned); Assert.assertEquals("abc", returned.get(0)); Assert.assertEquals("def1", returned.get(1)); } }
package lokko12.CB4BQ; import java.lang.reflect.InvocationTargetException; import betterquesting.commands.BQ_Commands; import betterquesting.commands.admin.QuestCommandDefaults; import betterquesting.core.BetterQuesting; import net.minecraft.block.Block; import net.minecraft.block.BlockCommandBlock; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; public class BlockDLB extends BlockCommandBlock { public BlockDLB() { this.setHardness(1.0f); this.setBlockName("CB4BQ.DLB"); this.setBlockTextureName("command_block"); this.setCreativeTab(BetterQuesting.tabQuesting); } public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { if (!world.isRemote) { try { Class c = Class.forName("betterquesting.commands.BQ_Commands"); //try to use modded version of BQ new QuestCommandDefaults().runCommand((CommandBase) c.getConstructor().newInstance(), (ICommandSender)player, new String[]{"default", "load"}); } catch (ClassNotFoundException e) { //fallback to vanilla try { Class c = Class.forName("betterquesting.commands.BQ_CommandAdmin"); new QuestCommandDefaults().runCommand((CommandBase)c.getConstructor().newInstance(), (ICommandSender)player, new String[]{"default", "load"}); } catch (ClassNotFoundException f) { CB4BQ.CLClogger.fatal("Something went horribly wrong"); CB4BQ.CLClogger.catching(e); CB4BQ.CLClogger.catching(f); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (IllegalArgumentException e1) { e1.printStackTrace(); } catch (InvocationTargetException e1) { e1.printStackTrace(); } catch (NoSuchMethodException e1) { e1.printStackTrace(); } catch (SecurityException e1) { e1.printStackTrace(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return true; } }
/* * MIT License * * Copyright (c) 2018 ARHS Group * * 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.github.arhs.owl2json.model.configuration; import com.github.arhs.owl2json.model.configuration.PropertyRangePreference; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class PropertyRangePreferenceTest { @Test public void test() { final PropertyRangePreference prp = new PropertyRangePreference(); // default values assertNull(prp.getFormat()); assertNull(prp.getMaximum()); assertNull(prp.getMinimum()); assertNull(prp.getPattern()); assertNull(prp.getType()); // set values prp.setFormat("format"); prp.setMaximum(Integer.MAX_VALUE); prp.setMinimum(Integer.MIN_VALUE); prp.setPattern("pattern"); prp.setType("type"); // check value assertEquals("format", prp.getFormat()); assertEquals(Integer.valueOf(Integer.MAX_VALUE), prp.getMaximum()); assertEquals(Integer.valueOf(Integer.MIN_VALUE), prp.getMinimum()); assertEquals("pattern", prp.getPattern()); assertEquals("type", prp.getType()); } }
/* * 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.sejda.sambox.contentstream.operator.text; import java.io.IOException; import java.util.List; import org.sejda.sambox.contentstream.operator.MissingOperandException; import org.sejda.sambox.contentstream.operator.Operator; import org.sejda.sambox.contentstream.operator.OperatorProcessor; import org.sejda.sambox.cos.COSBase; import org.sejda.sambox.cos.COSNumber; /** * Tc: Set character spacing. * * @author Laurent Huault */ public class SetCharSpacing extends OperatorProcessor { @Override public void process(Operator operator, List<COSBase> arguments) throws IOException { if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } // there are some documents which are incorrectly structured, and have // a wrong number of arguments to this, so we will assume the last argument // in the list Object charSpacing = arguments.get(arguments.size()-1); if (charSpacing instanceof COSNumber) { COSNumber characterSpacing = (COSNumber)charSpacing; getContext().getGraphicsState().getTextState() .setCharacterSpacing(characterSpacing.floatValue()); } } @Override public String getName() { return "Tc"; } }
/** * Copyright 2017-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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.glowroot.instrumentation.elasticsearch; import java.io.Serializable; import java.net.InetSocketAddress; import java.util.Iterator; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.sort.SortOrder; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.glowroot.instrumentation.test.harness.AppUnderTest; import org.glowroot.instrumentation.test.harness.Container; import org.glowroot.instrumentation.test.harness.IncomingSpan; import org.glowroot.instrumentation.test.harness.OutgoingSpan; import org.glowroot.instrumentation.test.harness.Span; import org.glowroot.instrumentation.test.harness.TransactionMarker; import static org.assertj.core.api.Assertions.assertThat; public class ElasticsearchSyncIT { private static Container container; private static int elasticsearchPort; @BeforeClass public static void setUp() throws Exception { container = SharedSetupRunListener.getContainer(); elasticsearchPort = SharedSetupRunListener.getElasticsearchPort(); } @AfterClass public static void tearDown() throws Exception { SharedSetupRunListener.close(container); } @After public void afterEachTest() throws Exception { container.resetAfterEachTest(); } @Test public void shouldCaptureDocumentPut() throws Exception { // when IncomingSpan incomingSpan = container.execute(ExecuteDocumentPut.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).isEqualTo("PUT testindex/testtype"); assertThat(outgoingSpan.detail()).isEmpty(); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentGet() throws Exception { // when IncomingSpan incomingSpan = container.execute(ExecuteDocumentGet.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).isEqualTo("GET testindex/testtype"); assertThat(outgoingSpan.detail()).containsKey("id"); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentUpdate() throws Exception { // when IncomingSpan incomingSpan = container.execute(ExecuteDocumentUpdate.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).isEqualTo("PUT testindex/testtype"); assertThat(outgoingSpan.detail()).containsKey("id"); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentDelete() throws Exception { // when IncomingSpan incomingSpan = container.execute(ExecuteDocumentDelete.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).isEqualTo("DELETE testindex/testtype"); assertThat(outgoingSpan.detail()).containsKey("id"); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentSearchWithoutSource() throws Exception { // when IncomingSpan incomingSpan = container.execute(ExecuteDocumentSearchWithoutSource.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).startsWith("SEARCH testindex/testtype {"); assertThat(outgoingSpan.detail()).isEmpty(); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentSearchWithoutIndexesWithoutSource() throws Exception { // when IncomingSpan incomingSpan = container .execute(ExecuteDocumentSearchWithoutIndexesWithoutSource.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).startsWith("SEARCH _any/testtype {"); assertThat(outgoingSpan.detail()).isEmpty(); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentSearchWithoutIndexesWithoutTypesWithoutSource() throws Exception { // when IncomingSpan incomingSpan = container.execute( ExecuteDocumentSearchWithoutIndexesWithoutTypesWithoutSource.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).startsWith("SEARCH / {"); assertThat(outgoingSpan.detail()).isEmpty(); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentSearchWithMultipleIndexesWithMultipleTypesWithoutSource() throws Exception { // when IncomingSpan incomingSpan = container.execute( ExecuteDocumentSearchWithMultipleIndexesWithMultipleTypesWithoutSource.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()) .startsWith("SEARCH testindex,testindex2/testtype,testtype2 {"); assertThat(outgoingSpan.detail()).isEmpty(); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentSearchWithQuery() throws Exception { // when IncomingSpan incomingSpan = container.execute(ExecuteDocumentSearchWithQuery.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).startsWith("SEARCH testindex/testtype {"); assertThat(outgoingSpan.detail()).isEmpty(); assertThat(i.hasNext()).isFalse(); } @Test public void shouldCaptureDocumentSearchWithQueryAndSort() throws Exception { // when IncomingSpan incomingSpan = container.execute(ExecuteDocumentSearchWithQueryAndSort.class, elasticsearchPort); // then Iterator<Span> i = incomingSpan.childSpans().iterator(); OutgoingSpan outgoingSpan = (OutgoingSpan) i.next(); assertThat(outgoingSpan.type()).isEqualTo("Elasticsearch"); assertThat(outgoingSpan.message()).startsWith("SEARCH testindex/testtype {"); assertThat(outgoingSpan.detail()).isEmpty(); assertThat(i.hasNext()).isFalse(); } public static class ExecuteDocumentPut implements AppUnderTest, TransactionMarker { private TransportClient client; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); } } public static class ExecuteDocumentGet implements AppUnderTest, TransactionMarker { private TransportClient client; private String documentId; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); IndexResponse response = client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); documentId = response.getId(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareGet("testindex", "testtype", documentId) .get(); } } public static class ExecuteDocumentUpdate implements AppUnderTest, TransactionMarker { private TransportClient client; private String documentId; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); IndexResponse response = client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); documentId = response.getId(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareUpdate("testindex", "testtype", documentId) .setDoc("xyz", "some updated text") .get(); } } public static class ExecuteDocumentDelete implements AppUnderTest, TransactionMarker { private TransportClient client; private String documentId; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); IndexResponse response = client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); documentId = response.getId(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareDelete("testindex", "testtype", documentId) .get(); } } public static class ExecuteDocumentSearchWithoutSource implements AppUnderTest, TransactionMarker { private TransportClient client; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareSearch("testindex") .setTypes("testtype") .get(); } } public static class ExecuteDocumentSearchWithoutIndexesWithoutSource implements AppUnderTest, TransactionMarker { private TransportClient client; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareSearch() .setTypes("testtype") .get(); } } public static class ExecuteDocumentSearchWithoutTypesWithoutSource implements AppUnderTest, TransactionMarker { private TransportClient client; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareSearch("testindex") .get(); } } public static class ExecuteDocumentSearchWithoutIndexesWithoutTypesWithoutSource implements AppUnderTest, TransactionMarker { private TransportClient client; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareSearch() .get(); } } public static class ExecuteDocumentSearchWithMultipleIndexesWithMultipleTypesWithoutSource implements AppUnderTest, TransactionMarker { private TransportClient client; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); client.prepareIndex("testindex2", "testtype2") .setSource("abc2", 11, "xyz2", "some text") .get(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareSearch("testindex", "testindex2") .setTypes("testtype", "testtype2") .get(); } } public static class ExecuteDocumentSearchWithQuery implements AppUnderTest, TransactionMarker { private TransportClient client; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareSearch("testindex") .setTypes("testtype") .setQuery(QueryBuilders.termQuery("xyz", "text")) .get(); } } public static class ExecuteDocumentSearchWithQueryAndSort implements AppUnderTest, TransactionMarker { private TransportClient client; @Override public void executeApp(Serializable... args) throws Exception { client = Util.client(new InetSocketAddress("127.0.0.1", (Integer) args[0])); client.prepareIndex("testindex", "testtype") .setSource("abc", 11, "xyz", "some text") .get(); transactionMarker(); client.close(); } @Override public void transactionMarker() throws Exception { client.prepareSearch("testindex") .setTypes("testtype") .setQuery(QueryBuilders.termQuery("xyz", "text")) .addSort("abc", SortOrder.ASC) .get(); } } }
/* * Copyright (C) 2018 Ferdinand Mütsch */ package com.github.n1try.popularmovies.ui; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.ViewGroup; import com.github.n1try.popularmovies.R; import com.github.n1try.popularmovies.model.Movie; import com.github.n1try.popularmovies.model.MovieSortOrder; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity implements OverviewFragment.OnMovieSelectedListener, OverviewFragment.OnDataLoadedListener { public static final String KEY_SORT_ORDER = "sort_order"; public static final String KEY_PAGE = "page"; public static final String KEY_HIDE_LOADING_DIALOG = "hide_loading_dialog"; public static final String KEY_MOVIE_ID = "movie_id"; private static final String KEY_ACTIVE_MOVIE = "active_movie"; private static final String TAG_OVERVIEW_FRAGMENT = "overview_fragment"; @Nullable @BindView(R.id.main_details_container) ViewGroup detailsContainer; private FragmentManager fragmentManager; private OverviewFragment overviewFragment; private Movie activeMovie; private Movie movieToSelect; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); fragmentManager = getSupportFragmentManager(); OverviewFragment foundFragment = (OverviewFragment) fragmentManager.findFragmentByTag(TAG_OVERVIEW_FRAGMENT); if (foundFragment == null) { overviewFragment = new OverviewFragment(); fragmentManager.beginTransaction().replace(R.id.main_overview_container, overviewFragment, TAG_OVERVIEW_FRAGMENT).commit(); } else { overviewFragment = foundFragment; } if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_ACTIVE_MOVIE)) { movieToSelect = savedInstanceState.getParcelable(KEY_ACTIVE_MOVIE); } } updateTitle(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (activeMovie != null) { outState.putParcelable(KEY_ACTIVE_MOVIE, activeMovie); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public void onMovieSelected(Movie movie) { activeMovie = movie; if (isTabletLayout()) { Fragment fragment = DetailsFragment.newInstance(movie); fragmentManager.beginTransaction().replace(R.id.main_details_container, fragment).commit(); } else { Intent intent = new Intent(MainActivity.this, DetailsActivity.class); intent.putExtra(KEY_MOVIE_ID, movie); startActivity(intent); } } @Override public void onDataLoaded() { if (isTabletLayout() && activeMovie == null) { if (movieToSelect != null) { overviewFragment.selectMovie(movieToSelect); movieToSelect = null; } else { overviewFragment.selectMovieByIndex(0); } } updateTitle(); } private void updateTitle() { if (overviewFragment == null) return; if (overviewFragment.getSortOrder() == MovieSortOrder.TOP_RATED) setTitle(R.string.title_top_rated_movies); else if (overviewFragment.getSortOrder() == MovieSortOrder.FAVORITE) setTitle(getString(R.string.favorite)); else setTitle(R.string.title_popular_movies); } private boolean isTabletLayout() { return detailsContainer != null; } }
package tools.gnzlz.database.query.builder.data; public class DWhere{ boolean not; Object column; String operator; Object value; public DWhere(Object column, String operator, Object value, boolean not) { this.column = column; this.operator = operator; this.value = value; this.not = not; } public String column() { if(column instanceof DSelect) return ((DSelect)column).column(); return column.toString(); } public String value() { if(value instanceof DSelect) return ((DSelect)value).column(); return value.toString(); } public String not() { return not ? "NOT ":""; } public String where() { return not().concat(column()).concat(" ").concat(operator).concat(" ").concat(value()); } @Override public String toString() { return where(); } }
package com.arjunsk.networking.components.socket.clientserver; import java.io.DataOutputStream; import java.net.Socket; public class SocketClient { public static void main(String[] args) { try (Socket socket = new Socket("localhost", 6666)) { DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); outputStream.writeUTF("Hello Server"); outputStream.flush(); outputStream.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Sat Nov 28 05:48:39 GMT 2020 */ package weka.core; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.junit.AfterClass; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; import static org.evosuite.shaded.org.mockito.Mockito.*; @EvoSuiteClassExclude public class Optimization_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "weka.core.Optimization"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); try { initMocksToAvoidTimeoutsInTheTests(); } catch(ClassNotFoundException e) {} } @AfterClass public static void clearEvoSuiteFramework(){ Sandbox.resetDefaultSecurityManager(); java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); setSystemProperties(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); java.lang.System.setProperty("file.encoding", "UTF-8"); java.lang.System.setProperty("java.awt.headless", "true"); java.lang.System.setProperty("java.io.tmpdir", "/tmp"); java.lang.System.setProperty("user.dir", "/home/ubuntu/termite/projects/107_weka"); java.lang.System.setProperty("user.home", "/home/ubuntu"); java.lang.System.setProperty("user.language", "en"); java.lang.System.setProperty("user.name", "ubuntu"); java.lang.System.setProperty("user.timezone", "Etc/UTC"); } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(Optimization_ESTest_scaffolding.class.getClassLoader() , "weka.core.Optimization$DynamicIntArray", "weka.core.matrix.LinearRegression", "weka.core.TechnicalInformation$Type", "weka.core.matrix.QRDecomposition", "weka.core.matrix.CholeskyDecomposition", "weka.core.matrix.EigenvalueDecomposition", "weka.core.TechnicalInformationHandler", "weka.core.matrix.LUDecomposition", "weka.core.RevisionUtils", "weka.core.matrix.IntVector", "weka.core.Optimization", "weka.core.matrix.DoubleVector", "weka.core.TechnicalInformation", "weka.core.matrix.Matrix", "weka.core.Utils", "weka.core.RevisionHandler", "weka.core.RevisionUtils$Type", "weka.core.matrix.Maths", "weka.core.matrix.SingularValueDecomposition", "weka.core.TechnicalInformation$Field" ); } private static void initMocksToAvoidTimeoutsInTheTests() throws ClassNotFoundException { mock(Class.forName("weka.core.Optimization", false, Optimization_ESTest_scaffolding.class.getClassLoader())); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(Optimization_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "weka.core.Optimization", "weka.core.Optimization$DynamicIntArray", "weka.core.TechnicalInformation$Type", "weka.core.TechnicalInformation$Field", "weka.core.RevisionUtils", "weka.core.matrix.Matrix", "weka.core.matrix.LUDecomposition", "weka.core.matrix.SingularValueDecomposition", "weka.core.matrix.Maths", "weka.core.matrix.EigenvalueDecomposition", "weka.core.matrix.LinearRegression", "weka.core.matrix.QRDecomposition", "weka.core.Utils", "weka.core.matrix.CholeskyDecomposition" ); } }
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.provision.node.filter; import com.yahoo.component.Version; import com.yahoo.vespa.hosted.provision.Node; import java.util.Objects; /** * Filter nodes by their OS version. * * @author mpolden */ public class NodeOsVersionFilter extends NodeFilter { private final Version version; private NodeOsVersionFilter(Version version, NodeFilter next) { super(next); this.version = Objects.requireNonNull(version, "version cannot be null"); } @Override public boolean matches(Node node) { if (!version.isEmpty() && !node.status().osVersion().filter(v -> v.equals(version)).isPresent()) { return false; } return nextMatches(node); } public static NodeOsVersionFilter from(String version, NodeFilter filter) { return new NodeOsVersionFilter(Version.fromString(version), filter); } }
/** * 核心常量 */ package pro.haichuang.framework.base.constant;
/* Copyright (c) 2000-2012 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.ashdin; import java.io.*; import java.util.*; import org.lockss.test.*; import org.lockss.util.*; import org.lockss.config.*; import org.lockss.repository.*; import org.lockss.extractor.*; import org.lockss.plugin.*; import org.lockss.plugin.simulated.*; /** * One of the articles used to get the html source for this plugin is: * http://www.ingentaconnect.com/content/maney/bjdd/2011/00000057/00000113/art00004 */ public class TestAshdinMetadataExtractorFactory extends LockssTestCase { static Logger log = Logger.getLogger("TestAshdinMetadataExtractorFactory"); //Simulated AU to generate content private SimulatedArchivalUnit sau; //Ingenta AU private ArchivalUnit hau; private MockLockssDaemon theDaemon; private static String PLUGIN_NAME = "org.lockss.plugin.ashdin.AshdinPlugin"; private static String BASE_URL = "http://www.ashdin.com/"; private static final int DEFAULT_FILESIZE = 3000; public void setUp() throws Exception { super.setUp(); String tempDirPath = setUpDiskSpace(); theDaemon = getMockLockssDaemon(); theDaemon.getAlertManager(); theDaemon.getPluginManager().setLoadablePluginsReady(true); theDaemon.setDaemonInited(true); theDaemon.getPluginManager().startService(); theDaemon.getCrawlManager(); sau = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin.class, simAuConfig(tempDirPath)); hau = PluginTestUtil.createAndStartAu(PLUGIN_NAME, ashdinAuConfig()); } public void tearDown() throws Exception { sau.deleteContentTree(); theDaemon.stopDaemon(); super.tearDown(); } Configuration simAuConfig(String rootPath) { Configuration conf = ConfigManager.newConfiguration(); conf.put("root", rootPath); conf.put("base_url", "http://www.ashdin.com/"); conf.put("depth", "1"); conf.put("branch", "4"); conf.put("numFiles", "7"); conf.put("fileTypes", "" + (SimulatedContentGenerator.FILE_TYPE_PDF)); conf.put("binFileSize", ""+ DEFAULT_FILESIZE); return conf; } Configuration ashdinAuConfig() { Configuration conf = ConfigManager.newConfiguration(); conf.put("base_url", "http://www.ashdin.com/"); conf.put("year", "2010"); conf.put("journal_code", "acpsf"); return conf; } String goodDate = "Date"; String goodJournal = "Journal of Testing"; String goodArticle = "Article Title"; String goodAuthor = "John A. Author; John B. Author"; String goodDoi = "10.5555/TEST_DOI"; String goodVolume = "Volume"; String goodContent = "<HTML><BODY>\n"+ "<div class=\"abs\" xmlns=\"http://www.w3.org/1999/xhtml\">\n"+ "<pre>Journal of Testing<br />Vol.Volume (Date), Article ID F0A0K0E, 12 pages &nbsp;[<a class=\"hrefcont\" href=\"TESTING.pdf\">Full-Text PDF</a>]<br/>doi:10.5555/TEST_DOI</pre>\n"+ "<h2 class=\"abstitle\">Article Title</h2>\n"+ "<h3 class=\"absauthor\">John A. Author<sup>1</sup>; John B. Author<sup>2</sup></h3>\n"+ "<p class=\"absaddr\"><sup>1</sup>Department of Testing, USA<br/>\n"+ "<sup>2</sup>Department of Computer Science, Brazil<br/>\n"+ "<br/>"; public void testExtractFromGoodContent() throws Exception { String url = "http://www.ashdin.com/journals/ACPSF/235465.aspx"; MockCachedUrl cu = new MockCachedUrl(url, hau); cu.setContent(goodContent); cu.setContentSize(goodContent.length()); cu.setProperty(CachedUrl.PROPERTY_CONTENT_TYPE, "text/html"); FileMetadataExtractor me = new AshdinMetadataExtractorFactory.AshdinHtmlMetadataExtractor(); assertNotNull(me); FileMetadataListExtractor mle = new FileMetadataListExtractor(me); List<ArticleMetadata> mdlist = mle.extract(MetadataTarget.Any, cu); assertNotEmpty(mdlist); ArticleMetadata md = mdlist.get(0); assertNotNull(md); assertEquals(goodDoi, md.get(MetadataField.FIELD_DOI)); assertEquals(goodArticle, md.get(MetadataField.FIELD_ARTICLE_TITLE)); assertEquals(goodAuthor, md.get(MetadataField.FIELD_AUTHOR)); assertEquals(goodDate, md.get(MetadataField.FIELD_DATE)); assertEquals(goodVolume, md.get(MetadataField.FIELD_VOLUME)); assertEquals(goodJournal, md.get(MetadataField.FIELD_JOURNAL_TITLE)); } String badContent = "<HTML><HEAD><TITLE>" + goodArticle + "</TITLE></HEAD><BODY>\n" + "<meta name=\"foo\"" + " content=\"bar\">\n" + " <pre xmlns=\"issn\">" + "<!-- FILE: /data/templates/www.example.com/bogus/issn.inc -->MUMBLE: " + goodJournal + " </div>\n"; public void testExtractFromBadContent() throws Exception { String url = "http://www.example.com/vol1/issue2/art3/"; MockCachedUrl cu = new MockCachedUrl(url, hau); cu.setContent(badContent); cu.setContentSize(badContent.length()); FileMetadataExtractor me = new AshdinMetadataExtractorFactory.AshdinHtmlMetadataExtractor(); assertNotNull(me); log.debug3("Extractor: " + me.toString()); FileMetadataListExtractor mle = new FileMetadataListExtractor(me); List<ArticleMetadata> mdlist = mle.extract(MetadataTarget.Any, cu); assertNotEmpty(mdlist); ArticleMetadata md = mdlist.get(0); assertNotNull(md); assertNull(md.get(MetadataField.FIELD_DOI)); assertEquals(1, md.rawSize()); } /** * Inner class that where a number of Archival Units can be created * */ public static class MySimulatedPlugin extends SimulatedPlugin { public ArchivalUnit createAu0(Configuration auConfig) throws ArchivalUnit.ConfigurationException { ArchivalUnit au = new SimulatedArchivalUnit(this); au.setConfiguration(auConfig); return au; } public SimulatedContentGenerator getContentGenerator(Configuration cf, String fileRoot) { return new MySimulatedContentGenerator(fileRoot); } } /** * Inner class to create a html source code simulated content */ public static class MySimulatedContentGenerator extends SimulatedContentGenerator { protected MySimulatedContentGenerator(String fileRoot) { super(fileRoot); } public String getHtmlFileContent(String filename, int fileNum, int depth, int branchNum, boolean isAbnormal) { String file_content = "<HTML><HEAD><TITLE>" + filename + "</TITLE></HEAD><BODY>\n"; file_content += " <meta name=\"lockss.filenum\" content=\"" + fileNum + "\">\n"; file_content += " <meta name=\"lockss.depth\" content=\"" + depth + "\">\n"; file_content += " <meta name=\"lockss.branchnum\" content=\"" + branchNum + "\">\n"; file_content += getHtmlContent(fileNum, depth, branchNum, isAbnormal); file_content += "\n</BODY></HTML>"; logger.debug2("MySimulatedContentGenerator.getHtmlFileContent: " + file_content); return file_content; } } }
public void test33() throws Throwable { AdvancedSettings advancedSettings0 = new AdvancedSettings(); advancedSettings0.setMaxThreadsForNioWrite(3324); assertEquals(3324, advancedSettings0.getMaxThreadsForNioWrite()); }
/** * Copyright (c)2018, Laoyuan.me. All Rights Reserved. */ package me.laoyuan.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** * RestTemplate配置 * * @author laoyuan.me * */ @Configuration public class RestTemplateConfig { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }
/* * This file was automatically generated by EvoSuite * Sun Nov 29 14:49:25 GMT 2020 */ package com.browsersoft.openhre.hl7.impl.regular; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import com.browsersoft.openhre.hl7.api.config.HL7Field; import com.browsersoft.openhre.hl7.api.config.HL7FieldList; import com.browsersoft.openhre.hl7.api.regular.ExpressionElementMapper; import com.browsersoft.openhre.hl7.api.regular.ExpressionElementMapperItem; import com.browsersoft.openhre.hl7.impl.config.HL7MessageGroupImpl; import com.browsersoft.openhre.hl7.impl.config.HL7MessageSegmentImpl; import com.browsersoft.openhre.hl7.impl.config.HL7SegmentImpl; import com.browsersoft.openhre.hl7.impl.parser.HL7CheckerStateImpl; import com.browsersoft.openhre.hl7.impl.regular.ExpressionElementMapperImpl; import com.browsersoft.openhre.hl7.impl.regular.ExpressionElementMapperItemImpl; import com.browsersoft.openhre.hl7.impl.regular.ExpressionImpl; import com.browsersoft.openhre.hl7.impl.regular.ExpressionMatrixImpl; import com.browsersoft.openhre.hl7.impl.regular.MessageTracerImpl; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class ExpressionMatrixImpl_ESTest extends ExpressionMatrixImpl_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=1.680309617482782 */ @Test(timeout = 4000) public void test00() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(2783); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); hL7MessageSegmentImpl0.setRequired(false); ExpressionImpl expressionImpl0 = new ExpressionImpl(); messageTracerImpl0.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.getValue(0, 161); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.setValue(0, 2, 1); // Undeclared exception! expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); } /** //Test case number: 1 /*Coverage entropy=1.7723628301455152 */ @Test(timeout = 4000) public void test01() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(2765); expressionMatrixImpl0.toString(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.getNumberOfElements(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.setValue(1, 2, 1); // Undeclared exception! expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); } /** //Test case number: 2 /*Coverage entropy=1.5679540060061348 */ @Test(timeout = 4000) public void test02() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(162, 1409); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); messageTracerImpl0.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl1.creatMatrix(1409); expressionMatrixImpl1.getValue(162, 162); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(1, 0, 0); ExpressionMatrixImpl expressionMatrixImpl2 = new ExpressionMatrixImpl(); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl2.toString(); expressionMatrixImpl1.toString(); expressionMatrixImpl1.setValue(0, 1, 0); messageTracerImpl0.getMapper(); expressionMatrixImpl1.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.toString(); expressionMatrixImpl2.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.toString(); int int0 = expressionMatrixImpl1.getNumberOfElements(); assertEquals(1409, int0); } /** //Test case number: 3 /*Coverage entropy=1.7740376442826764 */ @Test(timeout = 4000) public void test03() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getNumberOfElements(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); messageTracerImpl0.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); HL7MessageSegmentImpl hL7MessageSegmentImpl1 = new HL7MessageSegmentImpl(); hL7MessageSegmentImpl0.setRequired(false); ExpressionImpl expressionImpl1 = new ExpressionImpl(); messageTracerImpl0.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); messageTracerImpl0.getMapper(); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.getValue((-93), 0); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.setValue(1, 0, 144); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.getValue(2, (-1)); int int0 = expressionMatrixImpl0.addNewNode(); assertEquals(162, expressionMatrixImpl0.getNumberOfElements()); assertEquals(3, int0); } /** //Test case number: 4 /*Coverage entropy=1.4946014118867081 */ @Test(timeout = 4000) public void test04() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(162, 1409); String string0 = expressionMatrixImpl0.toString(); assertEquals("MATRIX\n-----------------------\n | A , B , C , D , E , F , G , H , I , J , K , L , M , N , O , P , Q , R , S , T , U , V , W , X , Y , Z , [ , \\ , ] , ^ , _ , ` , a , b , c , d , e , f , g , h , i , j , k , l , m , n , o , p , q , r , s , t , u , v , w , x , y , z , { , | , } , ~ ,  , \u0080 , \u0081 , \u0082 , \u0083 , \u0084 , \u0085 , \u0086 , \u0087 , \u0088 , \u0089 , \u008A , \u008B , \u008C , \u008D , \u008E , \u008F , \u0090 , \u0091 , \u0092 , \u0093 , \u0094 , \u0095 , \u0096 , \u0097 , \u0098 , \u0099 , \u009A , \u009B , \u009C , \u009D , \u009E , \u009F , \u00A0 , \u00A1 , \u00A2 , \u00A3 , \u00A4 , \u00A5 , \u00A6 , \u00A7 , \u00A8 , \u00A9 , \u00AA , \u00AB , \u00AC , \u00AD , \u00AE , \u00AF , \u00B0 , \u00B1 , \u00B2 , \u00B3 , \u00B4 , \u00B5 , \u00B6 , \u00B7 , \u00B8 , \u00B9 , \u00BA , \u00BB , \u00BC , \u00BD , \u00BE , \u00BF , \u00C0 , \u00C1 , \u00C2 , \u00C3 , \u00C4 , \u00C5 , \u00C6 , \u00C7 , \u00C8 , \u00C9 , \u00CA , \u00CB , \u00CC , \u00CD , \u00CE , \u00CF , \u00D0 , \u00D1 , \u00D2 , \u00D3 , \u00D4 , \u00D5 , \u00D6 , \u00D7 , \u00D8 , \u00D9 , \u00DA , \u00DB , \u00DC , \u00DD , \u00DE , \u00DF , \u00E0 , \u00E1 , \u00E2\n\nCONNECTIONS\n-----------------------\n", string0); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl1.creatMatrix(1409); expressionMatrixImpl1.getValue(162, 162); expressionMatrixImpl0.addNewNode(); int int0 = expressionMatrixImpl1.addNewNode(); assertEquals(0, int0); expressionMatrixImpl0.setValue(1, 0, 0); ExpressionMatrixImpl expressionMatrixImpl2 = new ExpressionMatrixImpl(); String string1 = expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); assertEquals("1 --- A ---> 0\n", string1); expressionMatrixImpl2.toString(); expressionMatrixImpl1.toString(); expressionMatrixImpl1.setValue(0, 1, (-1192)); messageTracerImpl0.getMapper(); String string2 = expressionMatrixImpl2.toString(); assertEquals("MATRIX\n-----------------------\n | \n\nCONNECTIONS\n-----------------------\n", string2); String string3 = expressionMatrixImpl1.outNoStandardConnections(true, (ExpressionElementMapper) null); assertEquals("", string3); expressionMatrixImpl0.toString(); expressionMatrixImpl2.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); int int1 = expressionMatrixImpl1.getValue(733, 1409); assertEquals((-1), int1); } /** //Test case number: 5 /*Coverage entropy=1.5007921682387784 */ @Test(timeout = 4000) public void test05() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(162, 1409); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); HL7SegmentImpl hL7SegmentImpl0 = new HL7SegmentImpl(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl1.creatMatrix(1409); expressionMatrixImpl1.getValue(162, 162); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(1, 0, 0); expressionMatrixImpl1.toString(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl1.toString(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(0, 1, (-1288)); expressionMatrixImpl0.toString(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); // Undeclared exception! expressionMatrixImpl1.toString(); } /** //Test case number: 6 /*Coverage entropy=1.7115472862863528 */ @Test(timeout = 4000) public void test06() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(2765); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(919, 2765); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getNumberOfElements(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); expressionMatrixImpl0.toString(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); expressionMatrixImpl0.creatMatrix(919); expressionMatrixImpl0.getValue(2765, (-23)); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.setValue(0, 870, 2765); assertEquals(919, expressionMatrixImpl0.getNumberOfElements()); } /** //Test case number: 7 /*Coverage entropy=1.3668012866860653 */ @Test(timeout = 4000) public void test07() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(162, 1409); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); HL7SegmentImpl hL7SegmentImpl0 = new HL7SegmentImpl(); HL7FieldList hL7FieldList0 = hL7SegmentImpl0.getFields(); HL7CheckerStateImpl hL7CheckerStateImpl0 = new HL7CheckerStateImpl(); hL7CheckerStateImpl0.getActualField(); hL7FieldList0.setItem((-1), (HL7Field) null); hL7SegmentImpl0.setID("MATRIX\n-----------------------\n | A , B , C , D , E , F , G , H , I , J , K , L , M , N , O , P , Q , R , S , T , U , V , W , X , Y , Z , [ , , ] , ^ , _ , ` , a , b , c , d , e , f , g , h , i , j , k , l , m , n , o , p , q , r , s , t , u , v , w , x , y , z , { , | , } , ~ ,  , \u0080 , \u0081 , \u0082 , \u0083 , \u0084 , \u0085 , \u0086 , \u0087 , \u0088 , \u0089 , \u008A , \u008B , \u008C , \u008D , \u008E , \u008F , \u0090 , \u0091 , \u0092 , \u0093 , \u0094 , \u0095 , \u0096 , \u0097 , \u0098 , \u0099 , \u009A , \u009B , \u009C , \u009D , \u009E , \u009F , \u00A0 , \u00A1 , \u00A2 , \u00A3 , \u00A4 , \u00A5 , \u00A6 , \u00A7 , \u00A8 , \u00A9 , \u00AA , \u00AB , \u00AC , \u00AD , \u00AE , \u00AF , \u00B0 , \u00B1 , \u00B2 , \u00B3 , \u00B4 , \u00B5 , \u00B6 , \u00B7 , \u00B8 , \u00B9 , \u00BA , \u00BB , \u00BC , \u00BD , \u00BE , \u00BF , \u00C0 , \u00C1 , \u00C2 , \u00C3 , \u00C4 , \u00C5 , \u00C6 , \u00C7 , \u00C8 , \u00C9 , \u00CA , \u00CB , \u00CC , \u00CD , \u00CE , \u00CF , \u00D0 , \u00D1 , \u00D2 , \u00D3 , \u00D4 , \u00D5 , \u00D6 , \u00D7 , \u00D8 , \u00D9 , \u00DA , \u00DB , \u00DC , \u00DD , \u00DE , \u00DF , \u00E0 , \u00E1 , \u00E2\n\nCONNECTIONS\n-----------------------\n"); hL7SegmentImpl0.setFields(hL7FieldList0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); ExpressionImpl expressionImpl0 = new ExpressionImpl(); messageTracerImpl0.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.creatMatrix(1409); expressionMatrixImpl1.getValue(162, 162); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(1, 0, 0); ExpressionMatrixImpl expressionMatrixImpl2 = new ExpressionMatrixImpl(); expressionMatrixImpl1.toString(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl2.setValue(1, 1, (-1288)); expressionMatrixImpl2.getValue(2, 4); expressionMatrixImpl0.toString(); assertEquals(162, expressionMatrixImpl0.getNumberOfElements()); int int0 = expressionMatrixImpl2.getNumberOfElements(); int int1 = expressionMatrixImpl2.getValue(0, 65); assertFalse(int1 == int0); } /** //Test case number: 8 /*Coverage entropy=1.5921245198372675 */ @Test(timeout = 4000) public void test08() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(162, 1409); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); HL7SegmentImpl hL7SegmentImpl0 = new HL7SegmentImpl(); HL7FieldList hL7FieldList0 = hL7SegmentImpl0.getFields(); hL7SegmentImpl0.setID(""); hL7SegmentImpl0.setFields(hL7FieldList0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); ExpressionImpl expressionImpl0 = new ExpressionImpl(); messageTracerImpl0.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.creatMatrix(1409); expressionMatrixImpl1.getValue(162, 162); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(1, 0, 0); ExpressionMatrixImpl expressionMatrixImpl2 = new ExpressionMatrixImpl(); expressionMatrixImpl1.toString(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl2.setValue(0, 1, (-1288)); expressionMatrixImpl2.getValue(1, 4); expressionMatrixImpl0.toString(); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); assertEquals(162, expressionMatrixImpl0.getNumberOfElements()); expressionMatrixImpl2.getNumberOfElements(); int int0 = expressionMatrixImpl2.getValue(0, 65); assertEquals((-1), int0); } /** //Test case number: 9 /*Coverage entropy=1.5921245198372675 */ @Test(timeout = 4000) public void test09() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(162, 1409); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); HL7SegmentImpl hL7SegmentImpl0 = new HL7SegmentImpl(); HL7FieldList hL7FieldList0 = hL7SegmentImpl0.getFields(); hL7SegmentImpl0.setID(""); hL7SegmentImpl0.setFields(hL7FieldList0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.creatMatrix(1409); expressionMatrixImpl1.getValue(162, 162); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(1, 0, 0); ExpressionMatrixImpl expressionMatrixImpl2 = new ExpressionMatrixImpl(); expressionMatrixImpl1.toString(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl2.setValue(0, 1, (-1288)); expressionMatrixImpl2.getValue(1, 4); expressionMatrixImpl0.toString(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); assertEquals(162, expressionMatrixImpl0.getNumberOfElements()); expressionMatrixImpl2.getNumberOfElements(); int int0 = expressionMatrixImpl2.getValue(0, 65); assertEquals((-1), int0); } /** //Test case number: 10 /*Coverage entropy=1.0397207708399179 */ @Test(timeout = 4000) public void test10() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); int int0 = 12345; expressionMatrixImpl0.creatMatrix(12345); ExpressionElementMapperImpl expressionElementMapperImpl0 = new ExpressionElementMapperImpl(); expressionElementMapperImpl0.clearAll(); // Undeclared exception! expressionMatrixImpl0.addNewNode(); } /** //Test case number: 11 /*Coverage entropy=1.4325856503946854 */ @Test(timeout = 4000) public void test11() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(162, 1409); expressionMatrixImpl0.toString(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); messageTracerImpl0.doEndItem(expressionImpl0, hL7MessageSegmentImpl0); HL7MessageSegmentImpl hL7MessageSegmentImpl1 = new HL7MessageSegmentImpl(); ExpressionImpl expressionImpl1 = new ExpressionImpl(); HL7MessageGroupImpl hL7MessageGroupImpl0 = new HL7MessageGroupImpl(); HL7SegmentImpl hL7SegmentImpl0 = new HL7SegmentImpl(); HL7FieldList hL7FieldList0 = hL7SegmentImpl0.getFields(); hL7SegmentImpl0.setFields(hL7FieldList0); hL7MessageSegmentImpl1.setSegment(hL7SegmentImpl0); hL7MessageSegmentImpl1.setSegment(hL7SegmentImpl0); ExpressionImpl expressionImpl2 = new ExpressionImpl(); messageTracerImpl0.doBeginItem(expressionImpl2, hL7MessageSegmentImpl1); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.creatMatrix(1409); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(0, (-1), (-1)); ExpressionMatrixImpl expressionMatrixImpl2 = new ExpressionMatrixImpl(); expressionMatrixImpl1.toString(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl2.setValue(0, 0, (-1288)); expressionMatrixImpl2.getValue(1, 4); expressionMatrixImpl0.toString(); assertEquals(162, expressionMatrixImpl0.getNumberOfElements()); expressionMatrixImpl2.getNumberOfElements(); int int0 = expressionMatrixImpl2.getValue((-1288), 1807); assertEquals((-1), int0); } /** //Test case number: 12 /*Coverage entropy=1.5226308976088523 */ @Test(timeout = 4000) public void test12() throws Throwable { MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); MessageTracerImpl messageTracerImpl1 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); HL7SegmentImpl hL7SegmentImpl0 = new HL7SegmentImpl(); HL7FieldList hL7FieldList0 = hL7SegmentImpl0.getFields(); hL7SegmentImpl0.setID(""); hL7SegmentImpl0.setFields(hL7FieldList0); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); ExpressionImpl expressionImpl0 = new ExpressionImpl(); MessageTracerImpl messageTracerImpl2 = new MessageTracerImpl(); messageTracerImpl2.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); int int0 = 2349; expressionMatrixImpl0.creatMatrix(2349); expressionMatrixImpl0.getValue(2854, 526); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.setValue((-1), 2277, 2349); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(2349, 558, (-3306)); expressionMatrixImpl0.getValue(2854, 2277); expressionMatrixImpl1.toString(); // Undeclared exception! expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); } /** //Test case number: 13 /*Coverage entropy=1.4941751382893083 */ @Test(timeout = 4000) public void test13() throws Throwable { MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); MessageTracerImpl messageTracerImpl1 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.getValue((-1505), (-681)); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); messageTracerImpl1.setMapper((ExpressionElementMapper) null); expressionMatrixImpl0.setValue(29, (-681), (-1)); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.getValue((-1505), 730); messageTracerImpl0.getMapper(); String string0 = expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); assertEquals("", string0); } /** //Test case number: 14 /*Coverage entropy=1.8775242811493909 */ @Test(timeout = 4000) public void test14() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(162); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getValue(162, 1409); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); HL7SegmentImpl hL7SegmentImpl0 = new HL7SegmentImpl(); HL7FieldList hL7FieldList0 = hL7SegmentImpl0.getFields(); hL7SegmentImpl0.setID(""); hL7SegmentImpl0.setFields(hL7FieldList0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); hL7MessageSegmentImpl0.setSegment(hL7SegmentImpl0); ExpressionImpl expressionImpl0 = new ExpressionImpl(); messageTracerImpl0.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.creatMatrix(1409); expressionMatrixImpl1.getValue(162, 162); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.setValue(1, 0, 0); expressionMatrixImpl1.creatMatrix((-1)); expressionMatrixImpl0.getNumberOfElements(); expressionMatrixImpl1.getNumberOfElements(); messageTracerImpl0.getMapper(); expressionMatrixImpl1.outNoStandardConnections(false, (ExpressionElementMapper) null); // Undeclared exception! try { expressionMatrixImpl1.addNewNode(); fail("Expecting exception: NegativeArraySizeException"); } catch(NegativeArraySizeException e) { // // no message in exception (getMessage() returned null) // verifyException("com.browsersoft.openhre.hl7.impl.regular.ExpressionMatrixImpl", e); } } /** //Test case number: 15 /*Coverage entropy=1.4184836619456564 */ @Test(timeout = 4000) public void test15() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); ExpressionElementMapperImpl expressionElementMapperImpl0 = new ExpressionElementMapperImpl(); expressionMatrixImpl0.addNewNode(); messageTracerImpl0.getMapper(); expressionMatrixImpl0.getValue((-962), (-640)); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.addNewNode(); int int0 = expressionMatrixImpl1.addNewNode(); assertEquals(1, int0); expressionMatrixImpl1.setValue((-640), 2717, (-962)); expressionMatrixImpl0.outNoStandardConnections(false, expressionElementMapperImpl0); int int1 = expressionMatrixImpl1.getValue(1, (-1)); assertEquals((-1), int1); } /** //Test case number: 16 /*Coverage entropy=1.8089909587099502 */ @Test(timeout = 4000) public void test16() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); ExpressionElementMapperImpl expressionElementMapperImpl0 = new ExpressionElementMapperImpl(); expressionMatrixImpl0.toString(); expressionElementMapperImpl0.getItem(0); expressionElementMapperImpl0.addItem((ExpressionElementMapperItem) null); expressionElementMapperImpl0.removeItem(318); expressionMatrixImpl0.outNoStandardConnections(false, expressionElementMapperImpl0); expressionMatrixImpl0.creatMatrix(0); String string0 = expressionMatrixImpl0.toString(); assertEquals("MATRIX\n-----------------------\n | \n0| \n\nCONNECTIONS\n-----------------------\n", string0); ExpressionElementMapperImpl expressionElementMapperImpl1 = new ExpressionElementMapperImpl(); expressionElementMapperImpl1.removeItem(5484); expressionElementMapperImpl1.getItem(5484); expressionElementMapperImpl1.addItem((ExpressionElementMapperItem) null); expressionElementMapperImpl1.addItem((ExpressionElementMapperItem) null); expressionMatrixImpl0.outNoStandardConnections(false, expressionElementMapperImpl1); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.setValue(0, 0, 0); expressionMatrixImpl0.setValue(0, 1, 0); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.getNumberOfElements(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.setValue((-1458), 0, 2); int int0 = expressionMatrixImpl0.addNewNode(); assertEquals(5, int0); expressionMatrixImpl0.getValue(318, 670); int int1 = expressionMatrixImpl0.getValue(0, (-426)); assertEquals((-1), int1); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); assertEquals(0, expressionMatrixImpl0.getNumberOfElements()); } /** //Test case number: 17 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test17() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.setValue(4, 4, 4); expressionMatrixImpl0.setValue(0, 0, 0); assertEquals(0, expressionMatrixImpl0.getNumberOfElements()); } /** //Test case number: 18 /*Coverage entropy=1.4735023850806486 */ @Test(timeout = 4000) public void test18() throws Throwable { MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); MessageTracerImpl messageTracerImpl1 = new MessageTracerImpl(); ExpressionElementMapperImpl expressionElementMapperImpl0 = new ExpressionElementMapperImpl(); expressionElementMapperImpl0.removeItem(0); expressionElementMapperImpl0.getItem((-733)); expressionElementMapperImpl0.addItem((ExpressionElementMapperItem) null); expressionElementMapperImpl0.addItem((ExpressionElementMapperItem) null); ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.outNoStandardConnections(true, expressionElementMapperImpl0); expressionMatrixImpl0.addNewNode(); expressionElementMapperImpl0.setItem(0, (ExpressionElementMapperItem) null); MessageTracerImpl messageTracerImpl2 = new MessageTracerImpl(); messageTracerImpl2.getMapper(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.getValue((-962), 138); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.addNewNode(); expressionMatrixImpl0.addNewNode(); messageTracerImpl2.setMapper((ExpressionElementMapper) null); expressionMatrixImpl0.setValue(0, 1, 65); expressionMatrixImpl0.getValue(139, 65); ExpressionElementMapperImpl expressionElementMapperImpl1 = new ExpressionElementMapperImpl(); messageTracerImpl0.getMapper(); String string0 = expressionMatrixImpl1.outNoStandardConnections(true, (ExpressionElementMapper) null); assertEquals("", string0); } /** //Test case number: 19 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test19() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); ExpressionElementMapperImpl expressionElementMapperImpl0 = new ExpressionElementMapperImpl(); MessageTracerImpl messageTracerImpl1 = new MessageTracerImpl(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); HL7MessageSegmentImpl hL7MessageSegmentImpl0 = new HL7MessageSegmentImpl(); messageTracerImpl1.doBeginItem(expressionImpl0, hL7MessageSegmentImpl0); messageTracerImpl1.getMapper(); expressionMatrixImpl0.setValue(2951, (-1705), 66); assertEquals(0, expressionMatrixImpl0.getNumberOfElements()); } /** //Test case number: 20 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test20() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); MessageTracerImpl messageTracerImpl1 = new MessageTracerImpl(); int int0 = expressionMatrixImpl0.addNewNode(); assertEquals(0, int0); int int1 = expressionMatrixImpl0.getNumberOfNodes(); assertFalse(int1 == int0); } /** //Test case number: 21 /*Coverage entropy=1.073542846408523 */ @Test(timeout = 4000) public void test21() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(1); expressionMatrixImpl0.toString(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(0); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.getNumberOfElements(); int int0 = expressionMatrixImpl0.getNumberOfElements(); assertEquals(0, int0); } /** //Test case number: 22 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test22() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); int int0 = expressionMatrixImpl0.getValue(0, 0); assertEquals((-1), int0); } /** //Test case number: 23 /*Coverage entropy=1.4241299173467734 */ @Test(timeout = 4000) public void test23() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); ExpressionImpl expressionImpl0 = new ExpressionImpl(); HL7MessageGroupImpl hL7MessageGroupImpl0 = new HL7MessageGroupImpl(); messageTracerImpl0.processGroup(expressionImpl0, hL7MessageGroupImpl0); MessageTracerImpl messageTracerImpl1 = new MessageTracerImpl(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.addNewNode(); ExpressionElementMapperImpl expressionElementMapperImpl0 = new ExpressionElementMapperImpl(); expressionElementMapperImpl0.setItem(497, (ExpressionElementMapperItem) null); expressionMatrixImpl0.outNoStandardConnections(false, expressionElementMapperImpl0); expressionMatrixImpl0.getValue(0, 9); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); ExpressionElementMapperImpl expressionElementMapperImpl1 = new ExpressionElementMapperImpl(); messageTracerImpl1.setMapper(expressionElementMapperImpl1); expressionMatrixImpl0.setValue(9, 2717, 2); expressionMatrixImpl0.outNoStandardConnections(true, expressionElementMapperImpl1); ExpressionMatrixImpl expressionMatrixImpl1 = new ExpressionMatrixImpl(); expressionMatrixImpl1.getValue(29, 2717); String string0 = expressionMatrixImpl1.outNoStandardConnections(false, expressionElementMapperImpl0); assertEquals("", string0); } /** //Test case number: 24 /*Coverage entropy=1.0805738483648537 */ @Test(timeout = 4000) public void test24() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.creatMatrix(30); expressionMatrixImpl0.creatMatrix(30); expressionMatrixImpl0.toString(); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.creatMatrix((-651)); expressionMatrixImpl0.toString(); expressionMatrixImpl0.getNumberOfElements(); int int0 = expressionMatrixImpl0.getNumberOfElements(); assertEquals((-651), int0); } /** //Test case number: 25 /*Coverage entropy=0.965642172437147 */ @Test(timeout = 4000) public void test25() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.addNewNode(); int int0 = 30; expressionMatrixImpl0.creatMatrix(3646); expressionMatrixImpl0.toString(); // Undeclared exception! expressionMatrixImpl0.toString(); } /** //Test case number: 26 /*Coverage entropy=1.3522093992338282 */ @Test(timeout = 4000) public void test26() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); expressionMatrixImpl0.addNewNode(); boolean boolean0 = false; MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); expressionMatrixImpl0.addNewNode(); int int0 = 776; expressionMatrixImpl0.creatMatrix(776); ExpressionElementMapperImpl expressionElementMapperImpl0 = new ExpressionElementMapperImpl(); int int1 = (-1302); ExpressionElementMapperItemImpl expressionElementMapperItemImpl0 = new ExpressionElementMapperItemImpl(); expressionElementMapperImpl0.setItem(0, expressionElementMapperItemImpl0); expressionElementMapperImpl0.getItem(1699); expressionElementMapperImpl0.setItem((-1302), (ExpressionElementMapperItem) null); expressionElementMapperImpl0.removeItem(1); expressionElementMapperImpl0.getItem(1); expressionElementMapperImpl0.addItem(expressionElementMapperItemImpl0); expressionElementMapperImpl0.addItem((ExpressionElementMapperItem) null); // Undeclared exception! try { expressionMatrixImpl0.outNoStandardConnections(true, expressionElementMapperImpl0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.evosuite.runtime.System", e); } } /** //Test case number: 27 /*Coverage entropy=1.5943445783804724 */ @Test(timeout = 4000) public void test27() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); messageTracerImpl0.getMapper(); messageTracerImpl0.setMapper((ExpressionElementMapper) null); messageTracerImpl0.setMapper((ExpressionElementMapper) null); messageTracerImpl0.getMapper(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.toString(); expressionMatrixImpl0.creatMatrix(65); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); expressionMatrixImpl0.getNumberOfElements(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); messageTracerImpl0.getMapper(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.getValue((-229), 2123); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.setValue(1340, 1, 618); messageTracerImpl0.getMapper(); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.toString(); expressionMatrixImpl0.addNewNode(); int int0 = expressionMatrixImpl0.getValue(65, (-304)); assertEquals(65, expressionMatrixImpl0.getNumberOfElements()); assertEquals((-1), int0); } /** //Test case number: 28 /*Coverage entropy=1.4750763110546947 */ @Test(timeout = 4000) public void test28() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); ExpressionElementMapperImpl expressionElementMapperImpl0 = new ExpressionElementMapperImpl(); expressionElementMapperImpl0.getItem(3); expressionElementMapperImpl0.addItem((ExpressionElementMapperItem) null); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.addNewNode(); expressionElementMapperImpl0.setItem(3, (ExpressionElementMapperItem) null); expressionMatrixImpl0.outNoStandardConnections(true, (ExpressionElementMapper) null); expressionMatrixImpl0.getValue((-962), (-962)); expressionMatrixImpl0.addNewNode(); expressionMatrixImpl0.addNewNode(); messageTracerImpl0.setMapper((ExpressionElementMapper) null); expressionMatrixImpl0.setValue((-962), 0, 574); expressionMatrixImpl0.getValue((-2776), 20480); ExpressionElementMapperImpl expressionElementMapperImpl1 = new ExpressionElementMapperImpl(); String string0 = expressionMatrixImpl0.outNoStandardConnections(false, (ExpressionElementMapper) null); assertEquals("", string0); } /** //Test case number: 29 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test29() throws Throwable { ExpressionMatrixImpl expressionMatrixImpl0 = new ExpressionMatrixImpl(); MessageTracerImpl messageTracerImpl0 = new MessageTracerImpl(); messageTracerImpl0.getMapper(); MessageTracerImpl messageTracerImpl1 = new MessageTracerImpl(); int int0 = expressionMatrixImpl0.getNumberOfNodes(); assertEquals(0, int0); } }
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2021 Adobe ~ ~ 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.adobe.cq.wcm.core.components.it.seljup.tests.teaser.v2; import java.util.HashMap; import java.util.concurrent.TimeoutException; import org.apache.sling.testing.clients.ClientException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import com.adobe.cq.testing.selenium.pageobject.cq.sites.PropertiesPage; import com.adobe.cq.testing.selenium.pagewidgets.coral.CoralCheckbox; import com.adobe.cq.wcm.core.components.it.seljup.util.Commons; import com.adobe.cq.wcm.core.components.it.seljup.util.components.teaser.v2.Teaser; import com.adobe.cq.wcm.core.components.it.seljup.util.components.teaser.v2.TeaserEditDialog; import com.adobe.cq.wcm.core.components.it.seljup.util.constant.RequestConstants; import static com.adobe.cq.testing.selenium.utils.ElementUtils.clickableClick; import static com.codeborne.selenide.Selenide.$; import static org.junit.jupiter.api.Assertions.assertTrue; @Tag("group3") public class TeaserIT extends com.adobe.cq.wcm.core.components.it.seljup.tests.teaser.v1.TeaserIT { protected Teaser teaser; protected void setup() throws ClientException { super.setup(Commons.rtImage_v3); } protected void setupResources() { super.setupResources(); teaserRT = Commons.rtTeaser_v2; clientlibs = "core.wcm.components.teaser.v2"; teaser = new Teaser(); } /** * Before Test Case **/ @BeforeEach public void setupBeforeEach() throws ClientException { setupResources(); setup(); } /** * Test: Links to elements for Teaser * * @throws TimeoutException * @throws InterruptedException * @throws ClientException */ @Test @DisplayName("Test: Links to elements for Teaser") public void testLinksToElementsTeaser() throws TimeoutException, InterruptedException, ClientException { String policySuffix = "/teaser/new_policy"; HashMap<String, String> data = new HashMap<String, String>(); data.clear(); data.put("jcr:title", "New Policy"); data.put("sling:resourceType", "wcm/core/components/policy/policy"); String policyPath1 = "/conf/"+ label + "/settings/wcm/policies/core-component/components"; String policyPath = Commons.createPolicy(adminClient, policySuffix, data , policyPath1); // add a policy for teaser component String policyLocation = "core-component/components"; String policyAssignmentPath = defaultPageTemplate + "/policies/jcr:content/root/responsivegrid/core-component/components"; data.clear(); data.put("cq:policy", policyLocation + policySuffix); data.put("sling:resourceType", "wcm/core/components/policies/mappings"); Commons.assignPolicy(adminClient,"/teaser",data, policyAssignmentPath, 200, 201); Commons.openSidePanel(); assetFinder.setFiltersPath(testAssetsPath); Commons.openEditDialog(editorPage, cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openAssetsTab(); editDialog.checkImageFromPageImage(); editDialog.uploadImageFromSidePanel(testImagePath); editDialog.openLinksTab(); editDialog.setLinkURL(testPage); Commons.saveConfigureDialog(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresent(testPage), "Image should be present"); assertTrue(!teaser.isTitleLinkPresent(testPage, title),"Title link should not be present"); } /** * Test: Fully Configured Teaser * @throws TimeoutException * @throws InterruptedException */ @Test @DisplayName("Test: Fully configured Teaser") public void testFullyConfiguredTeaser() throws TimeoutException, InterruptedException { Commons.openSidePanel(); assetFinder.setFiltersPath(testAssetsPath); Commons.openEditDialog(editorPage,cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openAssetsTab(); editDialog.checkImageFromPageImage(); editDialog.uploadImageFromSidePanel(testImagePath); editDialog.openLinksTab(); editDialog.setLinkURL(testPage); editDialog.clickLinkTarget(); editDialog.openTextTab(); editDialog.setPreTitle(preTitle); assertTrue(editDialog.isTitleFromPagePresent()); editDialog.clickTitleFromPage(); editDialog.setTitle(title); assertTrue(editDialog.isDescriptionFromPagePresent()); editDialog.clickDescriptionFromPage(); editDialog.setDescription(description); Commons.saveConfigureDialog(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresent(testPage), "Image should be present"); assertTrue(teaser.isPreTitlePresent(preTitle), "PreTitle should be present"); assertTrue(teaser.isTeaserLinkPresentWithTarget(testPage, title, "_blank"),"Teaser link should be present with target"); assertTrue(teaser.isDescriptionPresent(description),"Description should be present"); assertTrue(!teaser.isImageLinkPresent(),"The image should not be linked"); } /** * Test: Teaser with link and image and not title and description * @throws TimeoutException * @throws InterruptedException */ @Test @DisplayName("Test: Teaser with link and image and inherited title and description") public void testWithLinkAndImageTeaser() throws TimeoutException, InterruptedException { Commons.openSidePanel(); assetFinder.setFiltersPath(testAssetsPath); Commons.openEditDialog(editorPage,cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openAssetsTab(); editDialog.checkImageFromPageImage(); editDialog.uploadImageFromSidePanel(testImagePath); editDialog.openLinksTab(); editDialog.setLinkURL(testPage); Commons.saveConfigureDialog(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresent(testPage), "Image should be present"); assertTrue(!teaser.isImageLinkPresent(), "The image should not be linked"); assertTrue(teaser.isTitlePresent(), "Teaser title should be present"); assertTrue(teaser.isDescriptionPresent(), "Teaser description should be present"); } /** * Teaser with External Actions * * @throws TimeoutException * @throws InterruptedException */ @Test @DisplayName("Teaser with External Actions") public void testWithExternalActionsTeaser() throws TimeoutException, InterruptedException { Commons.openSidePanel(); assetFinder.setFiltersPath(testAssetsPath); Commons.openEditDialog(editorPage, cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openAssetsTab(); editDialog.checkImageFromPageImage(); editDialog.uploadImageFromSidePanel(testImagePath); editDialog.openLinksTab(); editDialog.addActionLink(); editDialog.setActionLinkUrl(actionExternalLink); editDialog.setActionText(actionExternalText); editDialog.addActionLink(); editDialog.setActionLinkUrl(secondTestPage); editDialog.clickLActionLinkTarget(); editDialog.setActionText(actionText2); Commons.saveConfigureDialog(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isTitleHidden(), "Title and Link should not be displayed"); assertTrue(teaser.isImagePresent(testPage), "Image should be present"); assertTrue(!teaser.isImageLinkPresent(), "Image should not be linked"); assertTrue(!teaser.isTitleLinkPresent(), "Title link should not be present"); assertTrue(teaser.isDescriptionPresent(), "Teaser description should be present"); assertTrue(teaser.isActionLinkPresent(actionExternalText), actionExternalLink + " action link should be present"); assertTrue(teaser.isActionLinkPresentWithTarget(actionText2, "_blank"), actionText2 + " action link should be present"); } /** * Test: Inherited Properties Teaser * * @throws TimeoutException * @throws InterruptedException */ @Test @DisplayName("Test: Teaser with inherited properties") public void testInheritedPropertiesTeaser() throws TimeoutException, InterruptedException { Commons.openSidePanel(); assetFinder.setFiltersPath(testAssetsPath); Commons.openEditDialog(editorPage,cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openAssetsTab(); editDialog.checkImageFromPageImage(); editDialog.uploadImageFromSidePanel(testImagePath); editDialog.openLinksTab(); editDialog.setLinkURL(testPage); Commons.saveConfigureDialog(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresent(testPage), "Image should be present"); assertTrue(teaser.isTeaserLinkPresent(testPage, pageTitle),"Teaser link should be present"); assertTrue(teaser.isDescriptionPresent(pageDescription),"Description from page should be present"); } /** * Teaser with Actions * * @throws TimeoutException * @throws InterruptedException */ @Test @DisplayName("Teaser with Actions") public void testWithActionsTeaser() throws TimeoutException, InterruptedException { Commons.openSidePanel(); assetFinder.setFiltersPath(testAssetsPath); Commons.openEditDialog(editorPage, cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openAssetsTab(); editDialog.checkImageFromPageImage(); editDialog.uploadImageFromSidePanel(testImagePath); editDialog.openTextTab(); editDialog.openLinksTab(); editDialog.addActionLink(); editDialog.setActionLinkUrl(testPage); editDialog.addActionLink(); editDialog.setActionLinkUrl(secondTestPage); Commons.saveConfigureDialog(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresent(testPage), "Image should be present"); assertTrue(!teaser.isImageLinkPresent(), "Image should not be linked"); assertTrue(teaser.isTitleHidden(), "Title and Link should not be displayed"); assertTrue(!teaser.isTitleLinkPresent(testPage, pageTitle),"Page title should not be present as title link "); assertTrue(teaser.isDescriptionPresent(pageDescription),"Description from page should be present"); assertTrue(teaser.isActionLinkPresent(pageTitle), "Test Page action link should be present"); assertTrue(teaser.isActionLinkPresent(secondPageTitle), "Second Test Page action link should be present"); } /** * Test: Checkbox-Textfield Tuple * * 1. open the edit dialog * 2. switch to the 'Text' tab * 3. populate the title tuple textfield * 4. open the 'Linka' tab * 5. add a link * 6. open the 'Text' tab * 7. verify the title tuple textfield value has not changed and that the textfield is not disabled * 8. set 'Get title from linked page' checkbox, checked * 9. verify the title value and disabled state * 10. set 'Get title from linked page' checkbox, unchecked * 11. verify the title has reverted to its previous user-input value * * @throws TimeoutException * @throws InterruptedException */ @Test @DisplayName("Test: Checkbox-Textfield Tuple") public void testCheckboxTextfieldTuple() throws TimeoutException, InterruptedException { // 1. Commons.openEditDialog(editorPage, cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); // 2. editDialog.openTextTab(); // 3. editDialog.clickTitleFromPage(); editDialog.setTitle(title); // 4. editDialog.openLinksTab(); // 5. editDialog.setLinkURL(testPage); // 6. editDialog.openTextTab(); // 7. assertTrue(editDialog.getTitleValue().equals(title) && editDialog.isTitleEnabled(), "Title should be enabled and should be set to " + title); // 8. editDialog.clickTitleFromPage(); // 9. assertTrue(editDialog.getTitleValue().equals(pageTitle) && !editDialog.isTitleEnabled(), "Title should be disabled and should not be set"); // 10. editDialog.clickTitleFromPage(); // 11. assertTrue(editDialog.getTitleValue().equals(title) && editDialog.isTitleEnabled(), "Title should be enabled and should be set to " + title); } @Test @DisplayName("Test: Inherit image from current page") public void testInheritImageFromCurrentPage() throws ClientException, InterruptedException { // set the page image for the current page setPageImage(testPage, climbingAsset); editorPage.enterPreviewMode(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresentWithAltText(testPage, climbingAssetAltText),"image should be rendered with alt text: " + climbingAssetAltText); assertTrue(teaser.isImagePresentWithFileName(climbingAssetFormatted),"image should be rendered with file name: " + climbingAssetFormatted); } @Test @DisplayName("Test: Inherit image from current page and no alt text") public void testInheritImageFromCurrentPage_isDecorative() throws ClientException, InterruptedException, TimeoutException { // set the page image for the current page setPageImage(testPage, climbingAsset); // set image to decorative Commons.openEditDialog(editorPage,cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openAssetsTab(); editDialog.checkInheritAltFromPage(); editDialog.setAltText(alt); editDialog.checkIsDecorative(); Commons.saveConfigureDialog(); editorPage.enterPreviewMode(); Commons.switchContext("ContentFrame"); Commons.webDriverWait(RequestConstants.WEBDRIVER_WAIT_TIME_MS); assertTrue(teaser.isImagePresentWithAltText(testPage, ""),"image should be rendered without alt text"); assertTrue(teaser.isImagePresentWithFileName(climbingAssetFormatted),"image should be rendered with file name: " + climbingAssetFormatted); } @Test @DisplayName("Test: Inherit image from linked page") public void testInheritImageFromLinkedPage() throws ClientException, InterruptedException, TimeoutException { // set the page image for the linked page setPageImage(secondTestPage, surfingAsset); // set the page image for the current page setPageImage(testPage, climbingAsset); // set the link URL Commons.openEditDialog(editorPage,cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openLinksTab(); editDialog.setLinkURL(secondTestPage); Commons.saveConfigureDialog(); editorPage.enterPreviewMode(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresentWithAltText(testPage, surfingAssetAltText),"image should be rendered with alt text: " + surfingAssetAltText); assertTrue(teaser.isImagePresentWithFileName(surfingAssetFormatted),"image should be rendered with file name: " + surfingAssetFormatted); } @Test @DisplayName("Test: Inherit image from linked page with alt defined in the dialog") public void testInheritImageFromLinkedPage_altNotInherited() throws ClientException, InterruptedException, TimeoutException { // set the page image for the linked page setPageImage(secondTestPage, surfingAsset); // set the page image for the current page setPageImage(testPage, climbingAsset); // set the link URL Commons.openEditDialog(editorPage,cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openLinksTab(); editDialog.setLinkURL(secondTestPage); // define alt on the resource editDialog.openAssetsTab(); editDialog.checkInheritAltFromPage(); editDialog.setAltText(alt); Commons.saveConfigureDialog(); editorPage.enterPreviewMode(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresentWithAltText(testPage, alt),"image should be rendered with alt text: " + alt); assertTrue(teaser.isImagePresentWithFileName(surfingAssetFormatted),"image should be rendered with file name: " + surfingAssetFormatted); } @Test @DisplayName("Test: Inherit image from action page") public void testInheritImageFromAction() throws ClientException, InterruptedException, TimeoutException { // set the page image for the action page setPageImage(thirdTestPage, skiingAsset); // set the page image for the current page setPageImage(testPage, climbingAsset); // set the action URL Commons.openEditDialog(editorPage,cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openLinksTab(); editDialog.addActionLink(); editDialog.setActionLinkUrl(thirdTestPage); Commons.saveConfigureDialog(); editorPage.enterPreviewMode(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresentWithAltText(testPage, skiingAssetAltText),"image should be rendered with alt text: " + skiingAssetAltText); assertTrue(teaser.isImagePresentWithFileName(skiingAssetFormatted),"image should be rendered with file name: " + skiingAssetFormatted); } /** * Test: Teaser with title, description and without image and link * * @throws TimeoutException * @throws InterruptedException */ @Test @DisplayName("Test: Teaser with title, description and without image and link") public void testNoImageTeaser() throws TimeoutException, InterruptedException { Commons.openSidePanel(); Commons.openEditDialog(editorPage,cmpPath); com.adobe.cq.wcm.core.components.it.seljup.util.components.teaser.v1.TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openTextTab(); editDialog.clickTitleFromPage(); editDialog.setTitle(title); editDialog.clickDescriptionFromPage(); editDialog.setDescription(description); Commons.saveConfigureDialog(); Commons.switchContext("ContentFrame"); assertTrue(!teaser.isImagePresent(testPage), "Image should not be present"); assertTrue(teaser.isTitlePresent(title),"Title link should be present"); assertTrue(teaser.isDescriptionPresent(description),"Description should be present"); } /** * Hide elements for Teaser * * @throws TimeoutException * @throws InterruptedException * @throws ClientException */ @Test @DisplayName("Test: Hide elements for Teaser") @Override public void testHideElementsTeaser() throws TimeoutException, InterruptedException, ClientException { createComponentPolicy(proxyPath.substring(proxyPath.lastIndexOf('/')), new HashMap<String, String>() {{ put("titleHidden", "true"); put("descriptionHidden", "true"); }}); Commons.openEditDialog(editorPage, cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openTextTab(); assertTrue(!editDialog.isDescriptionFromPagePresent(), "Description from Page checkbox should not be present"); assertTrue(!editDialog.isTitleFromPagePresent(), "Title from Page checkbox should not be present"); } /** * Disable Actions for Teaser * * @throws ClientException * @throws TimeoutException * @throws InterruptedException */ @Test @DisplayName("Disable Actions for Teaser") public void testDisableActionsTeaser() throws ClientException, TimeoutException, InterruptedException { createComponentPolicy(proxyPath.substring(proxyPath.lastIndexOf('/')), new HashMap<String, String>() {{ put("actionsDisabled", "true"); }}); Commons.openSidePanel(); Commons.openEditDialog(editorPage, cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openLinksTab(); assertTrue(!editDialog.isActionsPresent(), "Actions should not be present"); } @Test @DisplayName("Test: Inherit image from action page with alt defined in the dialog") public void testInheritImageFromAction_altNotInherited() throws ClientException, InterruptedException, TimeoutException { // set the page image for the action page setPageImage(thirdTestPage, skiingAsset); // set the page image for the current page setPageImage(testPage, climbingAsset); // set the action URL Commons.openEditDialog(editorPage,cmpPath); TeaserEditDialog editDialog = teaser.getEditDialog(); editDialog.openLinksTab(); editDialog.addActionLink(); editDialog.setActionLinkUrl(thirdTestPage); // define alt on the resource editDialog.openAssetsTab(); editDialog.checkInheritAltFromPage(); editDialog.setAltText(alt); Commons.saveConfigureDialog(); editorPage.enterPreviewMode(); Commons.switchContext("ContentFrame"); assertTrue(teaser.isImagePresentWithAltText(testPage, alt),"image should be rendered with alt text: " + alt); assertTrue(teaser.isImagePresentWithFileName(skiingAssetFormatted),"image should be rendered with file name: " + skiingAssetFormatted); } // ---------------------------------------------------------- // private stuff // ---------------------------------------------------------- /** * Sets the featured image for a page. */ private void setPageImage(String page, String asset) throws ClientException, InterruptedException { // set page resource type to page v3 adminClient.setPageProperty(page, "sling:resourceType", "core/wcm/components/page/v3/page", 200); PropertiesPage pageProperties = new PropertiesPage(page); pageProperties.open(); $("coral-tab[data-foundation-tracking-event*='images']").click(); $(".cq-FileUpload-picker").click(); $("*[data-foundation-collection-item-id='/content/dam/core-components']").click(); try { $("*[data-foundation-collection-item-id='/content/dam/core-components/" + asset + "'] coral-checkbox").click(); } catch (Throwable t) { // Fallback for AEM 6.5 $("*[data-foundation-collection-item-id='/content/dam/core-components/" + asset + "'] coral-columnview-item-thumbnail").click(); } clickableClick($(".granite-pickerdialog-submit")); // inherit alt text from DAM String altValueFromDAMSelector = ".cq-siteadmin-admin-properties coral-checkbox[name='./cq:featuredimage/altValueFromDAM']"; CoralCheckbox altValueFromDAMCheckbox = new CoralCheckbox(altValueFromDAMSelector); altValueFromDAMCheckbox.click(); pageProperties.saveAndClose(); Commons.webDriverWait(RequestConstants.WEBDRIVER_WAIT_TIME_MS); editorPage.open(); } }
/* * 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.carbondata.core.statusmanager; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.carbondata.common.logging.LogServiceFactory; import org.apache.carbondata.core.constants.CarbonCommonConstants; import org.apache.carbondata.core.datamap.Segment; import org.apache.carbondata.core.datastore.filesystem.CarbonFile; import org.apache.carbondata.core.datastore.filesystem.CarbonFileFilter; import org.apache.carbondata.core.datastore.impl.FileFactory; import org.apache.carbondata.core.fileoperations.AtomicFileOperationFactory; import org.apache.carbondata.core.fileoperations.AtomicFileOperations; import org.apache.carbondata.core.fileoperations.FileWriteOperation; import org.apache.carbondata.core.locks.CarbonLockFactory; import org.apache.carbondata.core.locks.ICarbonLock; import org.apache.carbondata.core.locks.LockUsage; import org.apache.carbondata.core.metadata.AbsoluteTableIdentifier; import org.apache.carbondata.core.metadata.schema.table.CarbonTable; import org.apache.carbondata.core.mutate.CarbonUpdateUtil; import org.apache.carbondata.core.mutate.SegmentUpdateDetails; import org.apache.carbondata.core.mutate.TupleIdEnum; import org.apache.carbondata.core.mutate.UpdateVO; import org.apache.carbondata.core.util.CarbonUtil; import org.apache.carbondata.core.util.path.CarbonTablePath; import com.google.gson.Gson; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; /** * Manages Segment & block status of carbon table for Delete operation */ public class SegmentUpdateStatusManager { /** * logger */ private static final Logger LOG = LogServiceFactory.getLogService(SegmentUpdateStatusManager.class.getName()); private final AbsoluteTableIdentifier identifier; private LoadMetadataDetails[] segmentDetails; private SegmentUpdateDetails[] updateDetails; private Map<String, SegmentUpdateDetails> blockAndDetailsMap; private boolean isStandardTable; public SegmentUpdateStatusManager(CarbonTable table, LoadMetadataDetails[] segmentDetails) { this.identifier = table.getAbsoluteTableIdentifier(); this.isStandardTable = CarbonUtil.isStandardCarbonTable(table); // current it is used only for read function scenarios, as file update always requires to work // on latest file status. this.segmentDetails = segmentDetails; updateDetails = readLoadMetadata(); populateMap(); } public SegmentUpdateStatusManager(CarbonTable table) { this.identifier = table.getAbsoluteTableIdentifier(); this.isStandardTable = CarbonUtil.isStandardCarbonTable(table); // current it is used only for read function scenarios, as file update always requires to work // on latest file status. if (!table.getTableInfo().isTransactionalTable()) { // fileExist is costly operation, so check based on table Type segmentDetails = new LoadMetadataDetails[0]; } else { segmentDetails = SegmentStatusManager.readLoadMetadata( CarbonTablePath.getMetadataPath(identifier.getTablePath())); } if (segmentDetails.length != 0) { updateDetails = readLoadMetadata(); } else { updateDetails = new SegmentUpdateDetails[0]; } populateMap(); } /** * populate the block and its details in a map. */ private void populateMap() { blockAndDetailsMap = new HashMap<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); for (SegmentUpdateDetails blockDetails : updateDetails) { String blockIdentifier = CarbonUpdateUtil .getSegmentBlockNameKey(blockDetails.getSegmentName(), blockDetails.getActualBlockName()); blockAndDetailsMap.put(blockIdentifier, blockDetails); } } /** * * @param segID * @param actualBlockName * @return null if block is not present in segment update status. */ private SegmentUpdateDetails getDetailsForABlock(String segID, String actualBlockName) { String blockIdentifier = CarbonUpdateUtil .getSegmentBlockNameKey(segID, actualBlockName); return blockAndDetailsMap.get(blockIdentifier); } /** * * @param key will be like (segid/blockname) 0/0-0-5464654654654 * @return */ public SegmentUpdateDetails getDetailsForABlock(String key) { return blockAndDetailsMap.get(key); } /** * Returns the LoadMetadata Details * @return */ public LoadMetadataDetails[] getLoadMetadataDetails() { return segmentDetails; } /** * Returns the UpdateStatus Details. * @return */ public SegmentUpdateDetails[] getUpdateStatusDetails() { return updateDetails; } /** * * @param segmentUpdateDetails */ public void setUpdateStatusDetails(SegmentUpdateDetails[] segmentUpdateDetails) { this.updateDetails = segmentUpdateDetails; } /** * This will return the lock object used to lock the table update status file before updation. * * @return */ public ICarbonLock getTableUpdateStatusLock() { return CarbonLockFactory.getCarbonLockObj(identifier, LockUsage.TABLE_UPDATE_STATUS_LOCK); } /** * Returns all update delta files of specified Segment. * * @param segmentId * @return * @throws Exception */ public List<String> getUpdateDeltaFiles(final String segmentId) { List<String> updatedDeltaFilesList = new ArrayList<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); String endTimeStamp = ""; String startTimeStamp = ""; String segmentPath = CarbonTablePath.getSegmentPath( identifier.getTablePath(), segmentId); CarbonFile segDir = FileFactory.getCarbonFile(segmentPath, FileFactory.getFileType(segmentPath)); for (LoadMetadataDetails eachSeg : segmentDetails) { if (eachSeg.getLoadName().equalsIgnoreCase(segmentId)) { // if the segment is found then take the start and end time stamp. startTimeStamp = eachSeg.getUpdateDeltaStartTimestamp(); endTimeStamp = eachSeg.getUpdateDeltaEndTimestamp(); } } // if start timestamp is empty then no update delta is found. so return empty list. if (startTimeStamp.isEmpty()) { return updatedDeltaFilesList; } final Long endTimeStampFinal = CarbonUpdateUtil.getTimeStampAsLong(endTimeStamp); final Long startTimeStampFinal = CarbonUpdateUtil.getTimeStampAsLong(startTimeStamp); // else scan the segment for the delta files with the respective timestamp. CarbonFile[] files = segDir.listFiles(new CarbonFileFilter() { @Override public boolean accept(CarbonFile pathName) { String fileName = pathName.getName(); if (fileName.endsWith(CarbonCommonConstants.UPDATE_DELTA_FILE_EXT)) { String firstPart = fileName.substring(0, fileName.indexOf('.')); long timestamp = Long.parseLong(firstPart .substring(firstPart.lastIndexOf(CarbonCommonConstants.HYPHEN) + 1, firstPart.length())); if (Long.compare(timestamp, endTimeStampFinal) <= 0 && Long.compare(timestamp, startTimeStampFinal) >= 0) { // if marked for delete then it is invalid. if (!isBlockValid(segmentId, fileName)) { return false; } return true; } } return false; } }); for (CarbonFile cfile : files) { updatedDeltaFilesList.add(cfile.getCanonicalPath()); } return updatedDeltaFilesList; } /** * Below method will be used to get all the delete delta files based on block name * * @param blockFilePath actual block filePath * @return all delete delta files * @throws Exception */ public String[] getDeleteDeltaFilePath(String blockFilePath, String segmentId) throws Exception { String blockId = CarbonUtil.getBlockId(identifier, blockFilePath, segmentId, true, isStandardTable); String tupleId; if (!isStandardTable) { tupleId = CarbonTablePath.getShortBlockIdForPartitionTable(blockId); } else { tupleId = CarbonTablePath.getShortBlockId(blockId); } return getDeltaFiles(tupleId, CarbonCommonConstants.DELETE_DELTA_FILE_EXT) .toArray(new String[0]); } /** * Returns all delta file paths of specified block */ private List<String> getDeltaFiles(String tupleId, String extension) throws Exception { String segment = CarbonUpdateUtil.getRequiredFieldFromTID(tupleId, TupleIdEnum.SEGMENT_ID); String completeBlockName = CarbonTablePath.addDataPartPrefix( CarbonUpdateUtil.getRequiredFieldFromTID(tupleId, TupleIdEnum.BLOCK_ID) + CarbonCommonConstants.FACT_FILE_EXT); String blockPath; if (!isStandardTable) { blockPath = identifier.getTablePath() + CarbonCommonConstants.FILE_SEPARATOR + CarbonUpdateUtil.getRequiredFieldFromTID(tupleId, TupleIdEnum.PART_ID) .replace("#", "/") + CarbonCommonConstants.FILE_SEPARATOR + completeBlockName; } else { String carbonDataDirectoryPath = CarbonTablePath.getSegmentPath( identifier.getTablePath(), segment); blockPath = carbonDataDirectoryPath + CarbonCommonConstants.FILE_SEPARATOR + completeBlockName; } CarbonFile file = FileFactory.getCarbonFile(blockPath, FileFactory.getFileType(blockPath)); if (!file.exists()) { throw new Exception("Invalid tuple id " + tupleId); } String blockNameWithoutExtn = completeBlockName.substring(0, completeBlockName.lastIndexOf('.')); //blockName without timestamp final String blockNameFromTuple = blockNameWithoutExtn.substring(0, blockNameWithoutExtn.lastIndexOf("-")); return getDeltaFiles(file, blockNameFromTuple, extension, segment); } /** * This method returns the list of Blocks associated with the segment * from the SegmentUpdateDetails List. * @param segmentName * @return */ public List<String> getBlockNameFromSegment(String segmentName) { List<String> blockNames = new ArrayList<String>(); for (SegmentUpdateDetails block : updateDetails) { if (block.getSegmentName().equalsIgnoreCase(segmentName) && !CarbonUpdateUtil .isBlockInvalid(block.getSegmentStatus())) { blockNames.add(block.getBlockName()); } } return blockNames; } /** * check the block whether is valid * * @param segName segment name * @param blockName block name * @return the status of block whether is valid */ public boolean isBlockValid(String segName, String blockName) { SegmentUpdateDetails details = getDetailsForABlock(segName, blockName); return details == null || !CarbonUpdateUtil.isBlockInvalid(details.getSegmentStatus()); } /** * Returns all delta file paths of specified block * * @param blockDir block directory with CarbonFile format * @param blockNameFromTuple block name from tuple * @param extension the file extension name * @param segment the segment name * @return the list of delete file */ private List<String> getDeltaFiles(CarbonFile blockDir, final String blockNameFromTuple, final String extension, String segment) throws IOException { List<String> deleteFileList = new ArrayList<>(); for (SegmentUpdateDetails block : updateDetails) { if (block.getBlockName().equalsIgnoreCase(blockNameFromTuple) && block.getSegmentName() .equalsIgnoreCase(segment) && !CarbonUpdateUtil .isBlockInvalid(block.getSegmentStatus())) { final long deltaStartTimestamp = getStartTimeOfDeltaFile(extension, block); // If there is no delete delete file , then return null if (deltaStartTimestamp == 0) { return deleteFileList; } final long deltaEndTimeStamp = getEndTimeOfDeltaFile(extension, block); // final long deltaEndTimeStamp = block.getDeleteDeltaEndTimeAsLong(); // final long deltaStartTimestamp = block.getDeleteDeltaStartTimeAsLong(); return getFilePaths(blockDir, blockNameFromTuple, extension, deleteFileList, deltaStartTimestamp, deltaEndTimeStamp); } } return deleteFileList; } private List<String> getFilePaths(CarbonFile blockDir, final String blockNameFromTuple, final String extension, List<String> deleteFileList, final long deltaStartTimestamp, final long deltaEndTimeStamp) throws IOException { if (null != blockDir.getParentFile()) { CarbonFile[] files = blockDir.getParentFile().listFiles(new CarbonFileFilter() { @Override public boolean accept(CarbonFile pathName) { String fileName = pathName.getName(); if (fileName.endsWith(extension) && pathName.getSize() > 0) { String firstPart = fileName.substring(0, fileName.lastIndexOf('.')); String blockName = firstPart.substring(0, firstPart.lastIndexOf(CarbonCommonConstants.HYPHEN)); long timestamp = Long.parseLong(firstPart .substring(firstPart.lastIndexOf(CarbonCommonConstants.HYPHEN) + 1, firstPart.length())); if (blockNameFromTuple.equals(blockName) && ( (Long.compare(timestamp, deltaEndTimeStamp) <= 0) && ( Long.compare(timestamp, deltaStartTimestamp) >= 0))) { return true; } } return false; } }); for (CarbonFile cfile : files) { if (null == deleteFileList) { deleteFileList = new ArrayList<String>(files.length); } deleteFileList.add(cfile.getCanonicalPath()); } } else { throw new IOException("Parent file could not found"); } return deleteFileList; } /** * Return all delta file for a block. * @param segmentId * @param blockName * @return */ public CarbonFile[] getDeleteDeltaFilesList(final Segment segmentId, final String blockName) { String segmentPath = CarbonTablePath.getSegmentPath( identifier.getTablePath(), segmentId.getSegmentNo()); CarbonFile segDir = FileFactory.getCarbonFile(segmentPath, FileFactory.getFileType(segmentPath)); for (SegmentUpdateDetails block : updateDetails) { if ((block.getBlockName().equalsIgnoreCase(blockName)) && (block.getSegmentName().equalsIgnoreCase(segmentId.getSegmentNo())) && !CarbonUpdateUtil.isBlockInvalid((block.getSegmentStatus()))) { final long deltaStartTimestamp = getStartTimeOfDeltaFile(CarbonCommonConstants.DELETE_DELTA_FILE_EXT, block); final long deltaEndTimeStamp = getEndTimeOfDeltaFile(CarbonCommonConstants.DELETE_DELTA_FILE_EXT, block); return segDir.listFiles(new CarbonFileFilter() { @Override public boolean accept(CarbonFile pathName) { String fileName = pathName.getName(); if (fileName.endsWith(CarbonCommonConstants.DELETE_DELTA_FILE_EXT) && pathName.getSize() > 0) { String firstPart = fileName.substring(0, fileName.indexOf('.')); String blkName = firstPart.substring(0, firstPart.lastIndexOf("-")); long timestamp = Long.parseLong( firstPart.substring(firstPart.lastIndexOf("-") + 1, firstPart.length())); if (blockName.equals(blkName) && (Long.compare(timestamp, deltaEndTimeStamp) <= 0) && (Long.compare(timestamp, deltaStartTimestamp) >= 0)) { return true; } } return false; } }); } } return null; } /** * Returns all update delta files of specified Segment. * * @param loadMetadataDetail metadatadetails of segment * @param validUpdateFiles if true then only the valid range files will be returned. * @return */ public CarbonFile[] getUpdateDeltaFilesList(LoadMetadataDetails loadMetadataDetail, final boolean validUpdateFiles, final String fileExtension, final boolean excludeOriginalFact, CarbonFile[] allFilesOfSegment, boolean isAbortedFile) { String endTimeStamp = ""; String startTimeStamp = ""; long factTimeStamp = 0; // if the segment is found then take the start and end time stamp. startTimeStamp = loadMetadataDetail.getUpdateDeltaStartTimestamp(); endTimeStamp = loadMetadataDetail.getUpdateDeltaEndTimestamp(); factTimeStamp = loadMetadataDetail.getLoadStartTime(); // if start timestamp is empty then no update delta is found. so return empty list. if (startTimeStamp.isEmpty()) { return new CarbonFile[0]; } final Long endTimeStampFinal = CarbonUpdateUtil.getTimeStampAsLong(endTimeStamp); final Long startTimeStampFinal = CarbonUpdateUtil.getTimeStampAsLong(startTimeStamp); final long factTimeStampFinal = factTimeStamp; List<CarbonFile> listOfCarbonFiles = new ArrayList<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); // else scan the segment for the delta files with the respective timestamp. for (CarbonFile eachFile : allFilesOfSegment) { String fileName = eachFile.getName(); if (fileName.endsWith(fileExtension)) { String firstPart = fileName.substring(0, fileName.lastIndexOf('.')); long timestamp = Long.parseLong(firstPart .substring(firstPart.lastIndexOf(CarbonCommonConstants.HYPHEN) + 1, firstPart.length())); if (excludeOriginalFact) { if (Long.compare(factTimeStampFinal, timestamp) == 0) { continue; } } if (validUpdateFiles) { if (Long.compare(timestamp, endTimeStampFinal) <= 0 && Long.compare(timestamp, startTimeStampFinal) >= 0) { listOfCarbonFiles.add(eachFile); } } else { // invalid cases. if (isAbortedFile) { if (Long.compare(timestamp, endTimeStampFinal) > 0) { listOfCarbonFiles.add(eachFile); } } else if (Long.compare(timestamp, startTimeStampFinal) < 0 || Long.compare(timestamp, endTimeStampFinal) > 0) { listOfCarbonFiles.add(eachFile); } } } } return listOfCarbonFiles.toArray(new CarbonFile[listOfCarbonFiles.size()]); } /** * Returns all update delta files of specified Segment. * * @param segmentId * @param validUpdateFiles * @param fileExtension * @param excludeOriginalFact * @param allFilesOfSegment * @return */ public CarbonFile[] getUpdateDeltaFilesForSegment(String segmentId, final boolean validUpdateFiles, final String fileExtension, final boolean excludeOriginalFact, CarbonFile[] allFilesOfSegment) { String endTimeStamp = ""; String startTimeStamp = ""; long factTimeStamp = 0; for (LoadMetadataDetails eachSeg : segmentDetails) { if (eachSeg.getLoadName().equalsIgnoreCase(segmentId)) { // if the segment is found then take the start and end time stamp. startTimeStamp = eachSeg.getUpdateDeltaStartTimestamp(); endTimeStamp = eachSeg.getUpdateDeltaEndTimestamp(); factTimeStamp = eachSeg.getLoadStartTime(); } } // if start timestamp is empty then no update delta is found. so return empty list. if (startTimeStamp.isEmpty()) { return new CarbonFile[0]; } final Long endTimeStampFinal = CarbonUpdateUtil.getTimeStampAsLong(endTimeStamp); final Long startTimeStampFinal = CarbonUpdateUtil.getTimeStampAsLong(startTimeStamp); final long factTimeStampFinal = factTimeStamp; List<CarbonFile> listOfCarbonFiles = new ArrayList<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); // else scan the segment for the delta files with the respective timestamp. for (CarbonFile eachFile : allFilesOfSegment) { String fileName = eachFile.getName(); if (fileName.endsWith(fileExtension)) { String firstPart = fileName.substring(0, fileName.indexOf('.')); long timestamp = Long.parseLong(firstPart .substring(firstPart.lastIndexOf(CarbonCommonConstants.HYPHEN) + 1, firstPart.length())); if (excludeOriginalFact) { if (Long.compare(factTimeStampFinal, timestamp) == 0) { continue; } } if (validUpdateFiles) { if (Long.compare(timestamp, endTimeStampFinal) <= 0 && Long.compare(timestamp, startTimeStampFinal) >= 0) { boolean validBlock = true; for (SegmentUpdateDetails blockDetails : getUpdateStatusDetails()) { if (blockDetails.getActualBlockName().equalsIgnoreCase(eachFile.getName()) && CarbonUpdateUtil.isBlockInvalid(blockDetails.getSegmentStatus())) { validBlock = false; } } if (validBlock) { listOfCarbonFiles.add(eachFile); } } } else { // invalid cases. if (Long.compare(timestamp, startTimeStampFinal) < 0) { listOfCarbonFiles.add(eachFile); } } } } return listOfCarbonFiles.toArray(new CarbonFile[listOfCarbonFiles.size()]); } /** * * @param extension * @param block * @return */ private long getStartTimeOfDeltaFile(String extension, SegmentUpdateDetails block) { long startTimestamp; switch (extension) { case CarbonCommonConstants.DELETE_DELTA_FILE_EXT: startTimestamp = block.getDeleteDeltaStartTimeAsLong(); break; default: startTimestamp = 0; } return startTimestamp; } /** * * @param extension * @param block * @return */ private long getEndTimeOfDeltaFile(String extension, SegmentUpdateDetails block) { long endTimestamp; switch (extension) { case CarbonCommonConstants.DELETE_DELTA_FILE_EXT: endTimestamp = block.getDeleteDeltaEndTimeAsLong(); break; default: endTimestamp = 0; } return endTimestamp; } /** * This method loads segment update details * * @return */ public SegmentUpdateDetails[] readLoadMetadata() { Gson gsonObjectToRead = new Gson(); DataInputStream dataInputStream = null; BufferedReader buffReader = null; InputStreamReader inStream = null; SegmentUpdateDetails[] listOfSegmentUpdateDetailsArray; // get the updated status file identifier from the table status. String tableUpdateStatusIdentifier = getUpdatedStatusIdentifier(); if (StringUtils.isEmpty(tableUpdateStatusIdentifier)) { return new SegmentUpdateDetails[0]; } String tableUpdateStatusPath = CarbonTablePath.getMetadataPath(identifier.getTablePath()) + CarbonCommonConstants.FILE_SEPARATOR + tableUpdateStatusIdentifier; AtomicFileOperations fileOperation = AtomicFileOperationFactory.getAtomicFileOperations(tableUpdateStatusPath); try { if (!FileFactory .isFileExist(tableUpdateStatusPath, FileFactory.getFileType(tableUpdateStatusPath))) { return new SegmentUpdateDetails[0]; } dataInputStream = fileOperation.openForRead(); inStream = new InputStreamReader(dataInputStream, CarbonCommonConstants.DEFAULT_CHARSET); buffReader = new BufferedReader(inStream); listOfSegmentUpdateDetailsArray = gsonObjectToRead.fromJson(buffReader, SegmentUpdateDetails[].class); } catch (IOException e) { return new SegmentUpdateDetails[0]; } finally { closeStreams(buffReader, inStream, dataInputStream); } return listOfSegmentUpdateDetailsArray; } /** * @return updateStatusFileName */ private String getUpdatedStatusIdentifier() { if (segmentDetails.length == 0) { return null; } return segmentDetails[0].getUpdateStatusFileName(); } /** * writes segment update details into a given file at @param dataLoadLocation * * @param listOfSegmentUpdateDetailsArray * @throws IOException */ public void writeLoadDetailsIntoFile(List<SegmentUpdateDetails> listOfSegmentUpdateDetailsArray, String updateStatusFileIdentifier) throws IOException { String fileLocation = CarbonTablePath.getMetadataPath(identifier.getTablePath()) + CarbonCommonConstants.FILE_SEPARATOR + CarbonUpdateUtil.getUpdateStatusFileName(updateStatusFileIdentifier); AtomicFileOperations fileWrite = AtomicFileOperationFactory.getAtomicFileOperations(fileLocation); BufferedWriter brWriter = null; DataOutputStream dataOutputStream = null; Gson gsonObjectToWrite = new Gson(); // write the updated data into the metadata file. try { dataOutputStream = fileWrite.openForWrite(FileWriteOperation.OVERWRITE); brWriter = new BufferedWriter(new OutputStreamWriter(dataOutputStream, CarbonCommonConstants.DEFAULT_CHARSET)); String metadataInstance = gsonObjectToWrite.toJson(listOfSegmentUpdateDetailsArray); brWriter.write(metadataInstance); } catch (IOException ioe) { LOG.error("Error message: " + ioe.getLocalizedMessage()); fileWrite.setFailed(); throw ioe; } finally { if (null != brWriter) { brWriter.flush(); } CarbonUtil.closeStreams(brWriter); fileWrite.close(); } } /** * This method closes the streams * * @param streams - streams to close. */ private void closeStreams(Closeable... streams) { // Added if to avoid NullPointerException in case one stream is being passed as null if (null != streams) { for (Closeable stream : streams) { if (null != stream) { try { stream.close(); } catch (IOException e) { LOG.error("Error while closing stream" + stream); } } } } } /** * Returns the invalid timestamp range of a segment. * @param segmentId * @return */ public UpdateVO getInvalidTimestampRange(String segmentId) { UpdateVO range = new UpdateVO(); for (LoadMetadataDetails segment : segmentDetails) { if (segment.getLoadName().equalsIgnoreCase(segmentId)) { range.setSegmentId(segmentId); range.setFactTimestamp(segment.getLoadStartTime()); if (!segment.getUpdateDeltaStartTimestamp().isEmpty() && !segment .getUpdateDeltaEndTimestamp().isEmpty()) { range.setUpdateDeltaStartTimestamp( CarbonUpdateUtil.getTimeStampAsLong(segment.getUpdateDeltaStartTimestamp())); range.setLatestUpdateTimestamp( CarbonUpdateUtil.getTimeStampAsLong(segment.getUpdateDeltaEndTimestamp())); } return range; } } return range; } /** * * @param block * @param needCompleteList * @return */ public CarbonFile[] getDeleteDeltaInvalidFilesList( final SegmentUpdateDetails block, final boolean needCompleteList, CarbonFile[] allSegmentFiles, boolean isAbortedFile) { final long deltaStartTimestamp = getStartTimeOfDeltaFile(CarbonCommonConstants.DELETE_DELTA_FILE_EXT, block); final long deltaEndTimestamp = getEndTimeOfDeltaFile(CarbonCommonConstants.DELETE_DELTA_FILE_EXT, block); List<CarbonFile> files = new ArrayList<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); for (CarbonFile eachFile : allSegmentFiles) { String fileName = eachFile.getName(); if (fileName.endsWith(CarbonCommonConstants.DELETE_DELTA_FILE_EXT)) { String blkName = CarbonTablePath.DataFileUtil.getBlockNameFromDeleteDeltaFile(fileName); // complete list of delta files of that block is returned. if (needCompleteList && block.getBlockName().equalsIgnoreCase(blkName)) { files.add(eachFile); } // invalid delete delta files only will be returned. long timestamp = CarbonUpdateUtil.getTimeStampAsLong( CarbonTablePath.DataFileUtil.getTimeStampFromDeleteDeltaFile(fileName)); if (block.getBlockName().equalsIgnoreCase(blkName)) { if (isAbortedFile) { if (Long.compare(timestamp, deltaEndTimestamp) > 0) { files.add(eachFile); } } else if (Long.compare(timestamp, deltaStartTimestamp) < 0 || Long.compare(timestamp, deltaEndTimestamp) > 0) { files.add(eachFile); } } } } return files.toArray(new CarbonFile[files.size()]); } }
/* * Copyright 1999-2015 dangdang.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package com.dangdang.ddframe.job.integrate.fixture.simple; import lombok.Getter; import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext; import com.dangdang.ddframe.job.plugin.job.type.simple.AbstractSimpleElasticJob; public final class SimpleElasticJob extends AbstractSimpleElasticJob { @Getter private static volatile boolean completed; @Override public void process(final JobExecutionMultipleShardingContext context) { completed = true; } public static void reset() { completed = false; } }
package us.codecraft.webmagic.pipeline; import us.codecraft.webmagic.ResultItems; import us.codecraft.webmagic.Task; import us.codecraft.webmagic.entity.InfoEntity; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; public class MysqlPipeline implements Pipeline { private static final String url = "jdbc:mysql://localhost:3306/test"; private static final String name = "com.mysql.jdbc.Driver"; private static final String username = "root"; private static final String password = "lkf@123456"; private Connection connection=null; private PreparedStatement preparedStatement=null; private void dbManager(String sql){ try{ Class.forName(name); connection = DriverManager.getConnection(url, username, password); preparedStatement = connection.prepareStatement(sql); }catch(Exception e){ e.printStackTrace(); } } private void close() throws Exception{ try{ this.connection.close(); this.preparedStatement.close(); }catch (Exception e){ e.printStackTrace(); throw new Exception(e); } } @Override public void process(ResultItems resultItems, Task task){ String sql = "SELECT * FROM spider"; dbManager(sql); //实例化 String title, description; List<InfoEntity> infoEntityList = (List<InfoEntity>)resultItems.get("dataInfo"); try{ ResultSet result = preparedStatement.executeQuery(); while(result.next()){ //若有数据,就输出 title = result.getString(3); description = result.getString(4); //显示出每一行数据 System.out.println(title + " " + description); } result.close(); close(); }catch (Exception e){ e.printStackTrace(); } sql = "INSERT INTO spider(taskid,title,description) VALUES (?,?,?)"; dbManager(sql); //实例化 try{ if(!infoEntityList.isEmpty()){ for(InfoEntity item : infoEntityList){ preparedStatement.setString(1,"oschina"); preparedStatement.setString(2,item.getTitle()); preparedStatement.setString(3,item.getDescription()); preparedStatement.addBatch(); } } preparedStatement.executeBatch(); close(); }catch (Exception e){ e.printStackTrace(); } } }
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -------------------------------------------------------------------------------- package com.echothree.control.user.filter.server.command; import com.echothree.control.user.filter.common.form.CreateFilterAdjustmentDescriptionForm; import com.echothree.model.control.filter.server.control.FilterControl; import com.echothree.model.control.party.common.PartyTypes; import com.echothree.model.control.party.server.control.PartyControl; import com.echothree.model.control.security.common.SecurityRoleGroups; import com.echothree.model.control.security.common.SecurityRoles; import com.echothree.model.data.filter.server.entity.FilterAdjustment; import com.echothree.model.data.filter.server.entity.FilterAdjustmentDescription; import com.echothree.model.data.filter.server.entity.FilterKind; import com.echothree.model.data.party.server.entity.Language; import com.echothree.model.data.user.common.pk.UserVisitPK; import com.echothree.util.common.command.BaseResult; import com.echothree.util.common.message.ExecutionErrors; import com.echothree.util.common.validation.FieldDefinition; import com.echothree.util.common.validation.FieldType; import com.echothree.util.server.control.BaseSimpleCommand; import com.echothree.util.server.control.CommandSecurityDefinition; import com.echothree.util.server.control.PartyTypeDefinition; import com.echothree.util.server.control.SecurityRoleDefinition; import com.echothree.util.server.persistence.Session; import java.util.List; public class CreateFilterAdjustmentDescriptionCommand extends BaseSimpleCommand<CreateFilterAdjustmentDescriptionForm> { private final static CommandSecurityDefinition COMMAND_SECURITY_DEFINITION; private final static List<FieldDefinition> FORM_FIELD_DEFINITIONS; static { COMMAND_SECURITY_DEFINITION = new CommandSecurityDefinition(List.of( new PartyTypeDefinition(PartyTypes.UTILITY.name(), null), new PartyTypeDefinition(PartyTypes.EMPLOYEE.name(), List.of( new SecurityRoleDefinition(SecurityRoleGroups.FilterAdjustment.name(), SecurityRoles.Description.name()) )) )); FORM_FIELD_DEFINITIONS = List.of( new FieldDefinition("FilterKindName", FieldType.ENTITY_NAME, true, null, null), new FieldDefinition("FilterAdjustmentName", FieldType.ENTITY_NAME, true, null, null), new FieldDefinition("LanguageIsoName", FieldType.ENTITY_NAME, true, null, null), new FieldDefinition("Description", FieldType.STRING, true, 1L, 80L) ); } /** Creates a new instance of CreateFilterAdjustmentDescriptionCommand */ public CreateFilterAdjustmentDescriptionCommand(UserVisitPK userVisitPK, CreateFilterAdjustmentDescriptionForm form) { super(userVisitPK, form, COMMAND_SECURITY_DEFINITION, FORM_FIELD_DEFINITIONS, false); } @Override protected BaseResult execute() { var filterControl = Session.getModelController(FilterControl.class); String filterKindName = form.getFilterKindName(); FilterKind filterKind = filterControl.getFilterKindByName(filterKindName); if(filterKind != null) { String filterAdjustmentName = form.getFilterAdjustmentName(); FilterAdjustment filterAdjustment = filterControl.getFilterAdjustmentByName(filterKind, filterAdjustmentName); if(filterAdjustment != null) { var partyControl = Session.getModelController(PartyControl.class); String languageIsoName = form.getLanguageIsoName(); Language language = partyControl.getLanguageByIsoName(languageIsoName); if(language != null) { FilterAdjustmentDescription filterAdjustmentDescription = filterControl.getFilterAdjustmentDescription(filterAdjustment, language); if(filterAdjustmentDescription == null) { var description = form.getDescription(); filterControl.createFilterAdjustmentDescription(filterAdjustment, language, description, getPartyPK()); } else { addExecutionError(ExecutionErrors.DuplicateFilterAdjustmentDescription.name(), filterKindName, filterAdjustmentName, languageIsoName); } } else { addExecutionError(ExecutionErrors.UnknownLanguageIsoName.name(), languageIsoName); } } else { addExecutionError(ExecutionErrors.UnknownFilterAdjustmentName.name(), filterKindName, filterAdjustmentName); } } else { addExecutionError(ExecutionErrors.UnknownFilterKindName.name(), filterKindName); } return null; } }
package org.interledger.connector.packetswitch.filters; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import org.interledger.connector.accounts.AccountId; import org.interledger.connector.accounts.AccountRateLimitSettings; import org.interledger.connector.accounts.AccountSettings; import org.interledger.connector.packetswitch.PacketRejector; import org.interledger.core.InterledgerAddress; import org.interledger.core.InterledgerCondition; import org.interledger.core.InterledgerErrorCode; import org.interledger.core.InterledgerFulfillPacket; import org.interledger.core.InterledgerPreparePacket; import org.interledger.core.InterledgerRejectPacket; import org.interledger.core.InterledgerResponsePacket; import com.github.benmanes.caffeine.cache.Cache; import com.google.common.util.concurrent.RateLimiter; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.time.Instant; import java.util.Optional; import java.util.concurrent.ExecutionException; /** * Unit tests for {@link RateLimitIlpPacketFilter}. */ public class RateLimitIlpPacketFilterTest { private static final AccountId SOURCE_ACCOUNT_ID = AccountId.of("123"); private static final InterledgerPreparePacket PREPARE_PACKET = InterledgerPreparePacket.builder() .expiresAt(Instant.now()) .destination(InterledgerAddress.of("test.dest")) .executionCondition(InterledgerCondition.of(new byte[32])) .build(); private static final InterledgerRejectPacket REJECT_PACKET = InterledgerRejectPacket.builder() .triggeredBy(InterledgerAddress.of("test.conn")) .code(InterledgerErrorCode.F00_BAD_REQUEST) .message("error message") .build(); @Mock private PacketRejector packetRejectorMock; @Mock private AccountRateLimitSettings rateLimitSettingsMock; @Mock private AccountSettings accountSettingsMock; @Mock private InterledgerFulfillPacket responsePacketMock; @Mock private PacketSwitchFilterChain filterChainMock; @Mock private Cache<AccountId, Optional<RateLimiter>> cacheMock; @Mock private RateLimiter rateLimiterMock; private RateLimitIlpPacketFilter filter; private RateLimitIlpPacketFilter filterWithMockCache; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(filterChainMock.doFilter(accountSettingsMock, PREPARE_PACKET)).thenReturn(responsePacketMock); // enable rate limiting by default when(rateLimitSettingsMock.maxPacketsPerSecond()).thenReturn(Optional.of(1000)); when(accountSettingsMock.accountId()).thenReturn(SOURCE_ACCOUNT_ID); when(accountSettingsMock.maximumPacketAmount()).thenReturn(Optional.empty()); when(accountSettingsMock.rateLimitSettings()).thenReturn(rateLimitSettingsMock); when(packetRejectorMock.reject(any(), any(), any(), any())).thenReturn(REJECT_PACKET); filter = new RateLimitIlpPacketFilter(packetRejectorMock); filterWithMockCache = new RateLimitIlpPacketFilter(packetRejectorMock, cacheMock); } /////////////////////// // Tests with a real Loading Cache... /////////////////////// @Test public void doFilterWithNoAccount() { filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); } @Test public void doFilterWithNoMaxPacketAmount() { when(rateLimitSettingsMock.maxPacketsPerSecond()).thenReturn(Optional.empty()); InterledgerResponsePacket response = filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerFulfillPacket, is(true)); response = filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat( "Response was: " + response.getClass().getName(), response instanceof InterledgerFulfillPacket, is(true) ); response = filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat( "Response was: " + response.getClass().getName(), response instanceof InterledgerFulfillPacket, is(true) ); verify(filterChainMock, times(3)).doFilter(accountSettingsMock, PREPARE_PACKET); } @Test public void doFilterWithInsufficientTickets() { when(rateLimitSettingsMock.maxPacketsPerSecond()).thenReturn(Optional.of(1)); InterledgerResponsePacket response = filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerFulfillPacket, is(true)); response = filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerRejectPacket, is(true)); response = filter.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerRejectPacket, is(true)); verify(filterChainMock, times(1)).doFilter(accountSettingsMock, PREPARE_PACKET); verify(packetRejectorMock, times(2)).reject(any(), any(), any(), any()); } /////////////////////// // Tests with a Mock Loading Cache... /////////////////////// @Test public void doFilterWithNoPermits() throws ExecutionException { when(cacheMock.get(any(), any())).thenReturn(Optional.of(rateLimiterMock)); when(rateLimiterMock.tryAcquire(1)).thenReturn(Boolean.FALSE); InterledgerResponsePacket response = filterWithMockCache.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerRejectPacket, is(true)); response = filterWithMockCache.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerRejectPacket, is(true)); verifyZeroInteractions(filterChainMock); } @Test public void doFilterWithPermit() throws ExecutionException { when(cacheMock.get(any(), any())).thenReturn(Optional.of(rateLimiterMock)); when(rateLimiterMock.tryAcquire(1)).thenReturn(true); InterledgerResponsePacket response = filterWithMockCache.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerFulfillPacket, is(true)); response = filterWithMockCache.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerFulfillPacket, is(true)); verify(filterChainMock, times(2)).doFilter(accountSettingsMock, PREPARE_PACKET); } @Test public void doFilterWithNoRateLimiter() throws ExecutionException { when(cacheMock.get(any(), any())).thenReturn(Optional.empty()); InterledgerResponsePacket response = filterWithMockCache.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerFulfillPacket, is(true)); response = filterWithMockCache.doFilter(accountSettingsMock, PREPARE_PACKET, filterChainMock); assertThat(response instanceof InterledgerFulfillPacket, is(true)); verify(filterChainMock, times(2)).doFilter(accountSettingsMock, PREPARE_PACKET); } }
/* * Copyright (c) 2018-2020 Karlatemp. All rights reserved. * @author Karlatemp <karlatemp@vip.qq.com> <https://github.com/Karlatemp> * @create 2020/08/04 19:29:26 * * kar-framework/kar-framework.spigot-nms-1_16_1.main/NBTDouble.java */ package io.github.karlatemp.karframework.nms.v1_8_R2; import io.github.karlatemp.karframework.opennbt.ITagDouble; import net.minecraft.server.v1_8_R2.NBTTagDouble; import org.jetbrains.annotations.NotNull; public class NBTDouble extends NBTBaseWrapper<NBTTagDouble> implements ITagDouble { public NBTDouble(NBTTagDouble base) { super(base); } @Override public double getValue() { return base.h(); } @Override public @NotNull ITagDouble clone() { return new NBTDouble(new NBTTagDouble(asDouble())); } @Override public int asInt() { return base.d(); } @Override public byte asByte() { return base.f(); } @Override public short asShort() { return base.e(); } @Override public long asLong() { return base.c(); } @Override public double asDouble() { return base.g(); } @Override public float asFloat() { return base.h(); } }
package org.aj.lists.filter.model.columndata; public class FilterColumnDataTestParameters { private final String familyFilterInput; private final String groupFilterInput; private final String typeFilterInput; private final int familyFilterReturnListLength; private final String familyFilterReturnListFirstValue; private final String familyFilterReturnListLastValue; private final int groupFilterReturnListLength; private final String groupFilterReturnListFirstValue; private final String groupFilterReturnListLastValue; private final int typeFilterReturnListLength; private final String typeFilterReturnListFirstValue; private final String typeFilterReturnListLastValue; public FilterColumnDataTestParameters(String familyFilterInput, String groupFilterInput, String typeFilterInput, int familyFilterReturnListLength, int groupFilterReturnListLength, int typeFilterReturnListLength, String familyFilterReturnListFirstValue, String familyFilterReturnListLastValue, String groupFilterReturnListFirstValue, String groupFilterReturnListLastValue, String typeFilterReturnListFirstValue, String typeFilterReturnListLastValue) { this.familyFilterInput = familyFilterInput; this.groupFilterInput = groupFilterInput; this.typeFilterInput = typeFilterInput; this.familyFilterReturnListLength = familyFilterReturnListLength; this.familyFilterReturnListFirstValue = familyFilterReturnListFirstValue; this.familyFilterReturnListLastValue = familyFilterReturnListLastValue; this.groupFilterReturnListLength = groupFilterReturnListLength; this.groupFilterReturnListFirstValue = groupFilterReturnListFirstValue; this.groupFilterReturnListLastValue = groupFilterReturnListLastValue; this.typeFilterReturnListLength = typeFilterReturnListLength; this.typeFilterReturnListFirstValue = typeFilterReturnListFirstValue; this.typeFilterReturnListLastValue = typeFilterReturnListLastValue; } public String getFamilyFilterInput() { return familyFilterInput; } public String getGroupFilterInput() { return groupFilterInput; } public String getTypeFilterInput() { return typeFilterInput; } public int getFamilyFilterReturnListLength() { return familyFilterReturnListLength; } public String getFamilyFilterReturnListFirstValue() { return familyFilterReturnListFirstValue; } public String getFamilyFilterReturnListLastValue() { return familyFilterReturnListLastValue; } public int getGroupFilterReturnListLength() { return groupFilterReturnListLength; } public String getGroupFilterReturnListFirstValue() { return groupFilterReturnListFirstValue; } public String getGroupFilterReturnListLastValue() { return groupFilterReturnListLastValue; } public int getTypeFilterReturnListLength() { return typeFilterReturnListLength; } public String getTypeFilterReturnListFirstValue() { return typeFilterReturnListFirstValue; } public String getTypeFilterReturnListLastValue() { return typeFilterReturnListLastValue; } }
package com.github.jitwxs.addax.core.mock.mocker.implicit; import com.github.jitwxs.addax.common.bean.MockConfig; import com.github.jitwxs.addax.core.mock.mocker.BaseMocker; import com.github.jitwxs.addax.core.mock.mocker.IMocker; import lombok.AllArgsConstructor; import java.lang.reflect.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * 数组模拟器 */ @AllArgsConstructor public class ArrayMocker implements IMocker<Object> { private final Type type; @Override public Object mock(MockConfig mockConfig) { if (type instanceof GenericArrayType) { // 创建有参数化的数组 return createGenericArray(mockConfig); } else { return createArray(mockConfig); } } private Object createArray(MockConfig mockConfig) { int size = mockConfig.nexSize(); Class<?> componentClass = ((Class<?>) type).getComponentType(); final Object result = Array.newInstance(componentClass, size); final BaseMocker<?> baseMocker = new BaseMocker<>(componentClass); for (int index = 0; index < size; index++) { Array.set(result, index, baseMocker.mock(mockConfig)); } return result; } // TODO 代码还需要整理 // 由于GenericArrayType无法获得Class,所以递归创建多维数组 private Object createGenericArray(MockConfig mockConfig) { GenericArrayType genericArrayType = (GenericArrayType) this.type; // 递归获取该数组的维数,以及最后的Class类型 Map<Integer, Map<Class, Type[]>> map = map(mockConfig, genericArrayType, 0); Entry<Integer, Map<Class, Type[]>> entry = map.entrySet().iterator().next(); Entry<Class, Type[]> baseEntry = entry.getValue().entrySet().iterator().next(); int[] dimensions = new int[entry.getKey()]; for (int index = 0; index < dimensions.length; index++) { dimensions[index] = mockConfig.nexSize(); } // 创建多维数组每种维度的对象 List<Object> list = new ArrayList<>(dimensions.length); Class clazz = baseEntry.getKey(); for (int index = dimensions.length - 1; index >= 0; index--) { Object array = Array.newInstance(clazz, dimensions[index]); list.add(array); clazz = array.getClass(); } // 实例化多维数组 Object baseResult = new BaseMocker(baseEntry.getKey(), baseEntry.getValue()).mock(mockConfig); for (int i = 0; i < list.size(); i++) { Object array = list.get(i); for (int j = 0; j < dimensions[dimensions.length - i - 1]; j++) { Array.set(array, j, baseResult); } baseResult = array; } return baseResult; } private Map<Integer, Map<Class, Type[]>> map(MockConfig mockConfig, GenericArrayType genericArrayType, int dimension) { Map<Integer, Map<Class, Type[]>> result = new HashMap<>(); Type componentType = genericArrayType.getGenericComponentType(); dimension++; if (componentType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) componentType; Map<Class, Type[]> map = new HashMap<>(); map.put((Class) parameterizedType.getRawType(), parameterizedType.getActualTypeArguments()); result.put(dimension, map); return result; } if (componentType instanceof GenericArrayType) { return map(mockConfig, (GenericArrayType) componentType, dimension); } if (componentType instanceof TypeVariable) { Map<Class, Type[]> map = new HashMap<>(); final String name = ((TypeVariable) componentType).getName(); map.put((Class) mockConfig.getTypeVariableCache().get(name), null); result.put(dimension, map); return result; } Map<Class, Type[]> map = new HashMap<>(); map.put((Class) componentType, null); result.put(dimension, map); return result; } }
package com.incognia; import com.fasterxml.jackson.annotation.JsonProperty; public enum FeedbackEvent { @JsonProperty("payment_accepted") PAYMENT_ACCEPTED, @JsonProperty("payment_declined") PAYMENT_DECLINED, @JsonProperty("payment_declined_by_risk_analysis") PAYMENT_DECLINED_BY_RISK_ANALYSIS, @JsonProperty("payment_declined_by_acquirer") PAYMENT_DECLINED_BY_ACQUIRER, @JsonProperty("payment_declined_by_business") PAYMENT_DECLINED_BY_BUSINESS, @JsonProperty("payment_declined_by_manual_review") PAYMENT_DECLINED_BY_MANUAL_REVIEW, @JsonProperty("login_accepted") LOGIN_ACCEPTED, @JsonProperty("login_declined") LOGIN_DECLINED, @JsonProperty("signup_accepted") SIGNUP_ACCEPTED, @JsonProperty("signup_declined") SIGNUP_DECLINED, @JsonProperty("challenge_passed") CHALLENGE_PASSED, @JsonProperty("challenge_failed") CHALLENGE_FAILED, @JsonProperty("password_changed_successfully") PASSWORD_CHANGED_SUCCESSFULLY, @JsonProperty("password_change_failed") PASSWORD_CHANGE_FAILED, @JsonProperty("verified") VERIFIED, @JsonProperty("not_verified") NOT_VERIFIED, @JsonProperty("chargeback") CHARGEBACK, @JsonProperty("promotion_abuse") PROMOTION_ABUSE, @JsonProperty("account_takeover") ACCOUNT_TAKEOVER; }
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; import de.metas.inoutcandidate.model.I_M_ShipmentSchedule; /** Generated Interface for M_PackagingTreeItemSched * @author Adempiere (generated) * @version Release 3.5.4a */ public interface I_M_PackagingTreeItemSched { /** TableName=M_PackagingTreeItemSched */ public static final String Table_Name = "M_PackagingTreeItemSched"; /** AD_Table_ID=540260 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 3 - Client - Org */ BigDecimal accessLevel = BigDecimal.valueOf(3); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Mandant. * Mandant fuer diese Installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organisation. * Organisatorische Einheit des Mandanten */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organisation. * Organisatorische Einheit des Mandanten */ public int getAD_Org_ID(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Erstellt. * Datum, an dem dieser Eintrag erstellt wurde */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Erstellt durch. * Nutzer, der diesen Eintrag erstellt hat */ public int getCreatedBy(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Aktiv. * Der Eintrag ist im System aktiv */ public void setIsActive (boolean IsActive); /** Get Aktiv. * Der Eintrag ist im System aktiv */ public boolean isActive(); /** Column name M_PackagingTreeItemSched_ID */ public static final String COLUMNNAME_M_PackagingTreeItemSched_ID = "M_PackagingTreeItemSched_ID"; /** Set Packaging Tree Item Schedule */ public void setM_PackagingTreeItemSched_ID (int M_PackagingTreeItemSched_ID); /** Get Packaging Tree Item Schedule */ public int getM_PackagingTreeItemSched_ID(); /** Column name M_ShipmentSchedule_ID */ public static final String COLUMNNAME_M_ShipmentSchedule_ID = "M_ShipmentSchedule_ID"; /** Set M_ShipmentSchedule_ID */ public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID); /** Get M_ShipmentSchedule_ID */ public int getM_ShipmentSchedule_ID(); public I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException; /** Column name M_PackagingTreeItem_ID */ public static final String COLUMNNAME_M_PackagingTreeItem_ID = "M_PackagingTreeItem_ID"; /** Set Packaging Tree Item */ public void setM_PackagingTreeItem_ID (int M_PackagingTreeItem_ID); /** Get Packaging Tree Item */ public int getM_PackagingTreeItem_ID(); public I_M_PackagingTreeItem getM_PackagingTreeItem() throws RuntimeException; /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Aktualisiert. * Datum, an dem dieser Eintrag aktualisiert wurde */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Aktualisiert durch. * Nutzer, der diesen Eintrag aktualisiert hat */ public int getUpdatedBy(); /** Column name Qty */ public static final String COLUMNNAME_Qty = "Qty"; /** Set Menge. * Menge */ public void setQty (BigDecimal Qty); /** Get Menge. * Menge */ public BigDecimal getQty(); }
package ru.matevosyan.entity; import org.springframework.stereotype.Component; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Column; /** * Role entity. */ @Component @Entity(name = "Role") @Table(name = "roles") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(unique = true) private String name; /** * Role default constructor. */ public Role() { } /** * Role constructor with id. * @param id role id. */ public Role(Integer id) { this.id = id; } /** * Getter for role id. * @return role id. */ public Integer getId() { return id; } /** * Setter for role id. * @param id id role id. */ public void setId(Integer id) { this.id = id; } /** * Getter for role name. * @return role name. */ public String getName() { return name; } /** * Setter for role name. * @param name id role name. */ public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Role role = (Role) o; return (id != null ? id.equals(role.id) : role.id == null) && (name != null ? name.equals(role.name) : role.name == null); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); return result; } }
// 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.azure.messaging.eventgrid.systemevents; import com.azure.core.annotation.Immutable; /** The MediaJobOutputScheduledEventData model. */ @Immutable public final class MediaJobOutputScheduledEventData extends MediaJobOutputStateChangeEventData {}
package ru.stqa.pft.addressbook.testdrive; public class Program1test { public static void main(String[] args) { int x = 1; while (x < 10) { if (x > 3) { System.out.println("большой икс"); } // return; } } }
package com.github.kickshare.db.dao; import java.io.IOException; import java.util.List; import com.github.kickshare.db.dao.common.EnhancedDAO; import com.github.kickshare.db.jooq.tables.pojos.ProjectDB; import com.github.kickshare.db.jooq.tables.records.ProjectRecordDB; import com.github.kickshare.db.query.SearchOptionsDB; import org.springframework.stereotype.Repository; /** * @author Jan.Kucera * @since 30.3.2017 */ @Repository public interface ProjectRepository extends EnhancedDAO<ProjectRecordDB, ProjectDB, Long> { List<ProjectDB> findProjects(); List<ProjectDB> searchProjects(SearchOptionsDB options) throws IOException; }
/*************************************************************************** Copyright (c) 2016, EPAM SYSTEMS INC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ package com.epam.dlab.backendapi.resources; import com.epam.dlab.auth.UserInfo; import com.epam.dlab.backendapi.ProvisioningServiceApplicationConfiguration; import com.epam.dlab.backendapi.core.Directories; import com.epam.dlab.backendapi.core.FileHandlerCallback; import com.epam.dlab.backendapi.core.commands.*; import com.epam.dlab.backendapi.core.response.folderlistener.FolderListenerExecutor; import com.epam.dlab.backendapi.core.response.handlers.ExploratoryCallbackHandler; import com.epam.dlab.dto.exploratory.ExploratoryActionDTO; import com.epam.dlab.dto.exploratory.ExploratoryBaseDTO; import com.epam.dlab.dto.exploratory.ExploratoryCreateDTO; import com.epam.dlab.dto.exploratory.ExploratoryStopDTO; import com.epam.dlab.rest.client.RESTService; import com.google.inject.Inject; import io.dropwizard.auth.Auth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.io.IOException; @Path("/exploratory") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class ExploratoryResource implements DockerCommands { private static final Logger LOGGER = LoggerFactory.getLogger(ExploratoryResource.class); @Inject private ProvisioningServiceApplicationConfiguration configuration; @Inject private FolderListenerExecutor folderListenerExecutor; @Inject private ICommandExecutor commandExecutor; @Inject private CommandBuilder commandBuilder; @Inject private RESTService selfService; @Path("/create") @POST public String create(@Auth UserInfo ui, ExploratoryCreateDTO dto) throws IOException, InterruptedException { return action(ui.getName(), dto, DockerAction.CREATE); } @Path("/start") @POST public String start(@Auth UserInfo ui, ExploratoryActionDTO<?> dto) throws IOException, InterruptedException { return action(ui.getName(), dto, DockerAction.START); } @Path("/terminate") @POST public String terminate(@Auth UserInfo ui, ExploratoryActionDTO<?> dto) throws IOException, InterruptedException { return action(ui.getName(), dto, DockerAction.TERMINATE); } @Path("/stop") @POST public String stop(@Auth UserInfo ui, ExploratoryStopDTO dto) throws IOException, InterruptedException { return action(ui.getName(), dto, DockerAction.STOP); } private String action(String username, ExploratoryBaseDTO<?> dto, DockerAction action) throws IOException, InterruptedException { LOGGER.debug("{} exploratory environment", action); String uuid = DockerCommands.generateUUID(); folderListenerExecutor.start(configuration.getImagesDirectory(), configuration.getResourceStatusPollTimeout(), getFileHandlerCallback(action, uuid, dto)); RunDockerCommand runDockerCommand = new RunDockerCommand() .withInteractive() .withName(nameContainer(dto.getEdgeUserName(), action, dto.getExploratoryName())) .withVolumeForRootKeys(configuration.getKeyDirectory()) .withVolumeForResponse(configuration.getImagesDirectory()) .withVolumeForLog(configuration.getDockerLogDirectory(), getResourceType()) .withResource(getResourceType()) .withRequestId(uuid) .withConfKeyName(configuration.getAdminKey()) .withImage(dto.getNotebookImage()) .withAction(action); commandExecutor.executeAsync(username, uuid, commandBuilder.buildCommand(runDockerCommand, dto)); return uuid; } private FileHandlerCallback getFileHandlerCallback(DockerAction action, String uuid, ExploratoryBaseDTO<?> dto) { return new ExploratoryCallbackHandler(selfService, action, uuid, dto.getAwsIamUser(), dto.getExploratoryName()); } private String nameContainer(String user, DockerAction action, String name) { return nameContainer(user, action.toString(), "exploratory", name); } public String getResourceType() { return Directories.NOTEBOOK_LOG_DIRECTORY; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.test.sql.parser.parameterized.asserts.statement.distsql.rdl.alter.impl; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.shardingsphere.dbdiscovery.distsql.parser.segment.DatabaseDiscoveryRuleSegment; import org.apache.shardingsphere.dbdiscovery.distsql.parser.statement.AlterDatabaseDiscoveryRuleStatement; import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.SQLCaseAssertContext; import org.apache.shardingsphere.test.sql.parser.parameterized.asserts.segment.distsql.rdl.DatabaseDiscoveryRuleAssert; import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.segment.impl.distsql.rdl.ExpectedDatabaseDiscoveryRule; import org.apache.shardingsphere.test.sql.parser.parameterized.jaxb.cases.domain.statement.distsql.rdl.alter.AlterDataBaseDiscoveryRuleStatementTestCase; import java.util.Collection; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; /** * Alter database discovery rule statement assert. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class AlterDatabaseDiscoveryRuleStatementAssert { /** * Assert alter database discovery rule statement is correct with expected parser result. * * @param assertContext assert context * @param actual actual alter database discovery rule statement * @param expected expected alter database discovery rule statement test case */ public static void assertIs(final SQLCaseAssertContext assertContext, final AlterDatabaseDiscoveryRuleStatement actual, final AlterDataBaseDiscoveryRuleStatementTestCase expected) { if (null == expected) { assertNull(assertContext.getText("Actual should not exist."), actual); } else { assertNotNull(assertContext.getText("Actual should exist."), actual); assertDatabaseDiscoveryRules(assertContext, actual.getRules(), expected.getRules()); } } private static void assertDatabaseDiscoveryRules(final SQLCaseAssertContext assertContext, final Collection<DatabaseDiscoveryRuleSegment> actual, final List<ExpectedDatabaseDiscoveryRule> expected) { if (null == expected) { assertNull(assertContext.getText("Actual should not exist."), actual); } else { assertNotNull(assertContext.getText("Actual should exist."), actual); assertThat(assertContext.getText(String.format("Actual database discovery rule size should be %s , but it was %s", expected.size(), actual.size())), actual.size(), is(expected.size())); int count = 0; for (DatabaseDiscoveryRuleSegment databaseDiscoveryRuleSegment : actual) { ExpectedDatabaseDiscoveryRule expectedDatabaseDiscoveryRule = expected.get(count); DatabaseDiscoveryRuleAssert.assertIs(assertContext, databaseDiscoveryRuleSegment, expectedDatabaseDiscoveryRule); count++; } } } }
package de.bauhaus.digital.controller; import static de.bauhaus.digital.DomainFactory.createSampleProjekt; import static de.bauhaus.digital.DomainFactory.createSampleProjektBuilder; import static de.bauhaus.digital.DomainFactory.createSampleTeilnehmer; import static io.restassured.RestAssured.given; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import de.bauhaus.digital.DomainFactory; import de.bauhaus.digital.domain.Projekt; import de.bauhaus.digital.domain.Teilnehmer; import io.restassured.http.ContentType; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import org.apache.http.HttpStatus; import org.assertj.core.api.Assertions; import org.junit.Assert; import org.junit.Test; public class ProjekteControllerTest extends AbstractControllerTest { @Test public void givenInvalidCredentials_whenAddingProjekt_thenHttp401Unauthorized() { Projekt projekt = createSampleProjekt(); given() .auth().basic("wrong", "credentials") .body(projekt) .contentType(ContentType.JSON) .when() .post(BASE_URL + "/projects") .then() .statusCode(HttpStatus.SC_UNAUTHORIZED); } @Test public void givenProjekte_whenAddingTwoProjekteAndRetrievingAll_thenListHasTwoAdditionalEntries() { int initialSize = getAllProjects().size(); addProject(createSampleProjekt()); addProject(createSampleProjekt()); List<Projekt> alleProjekte = getAllProjects(); assertThat(alleProjekte.size(), is(initialSize + 2)); } @Test public void givenInvalidId_whenRequestingProject_thenNotFound() { getNoProjekt(-1L); } @Test public void givenProjekt_whenAddingAndRetrieving_thenTheyMatch() { Projekt projekt = createSampleProjekt(); Long projektId = addProject(projekt); Projekt responseProjekt = getProject(projektId); Assertions.assertThat(responseProjekt). usingRecursiveComparison() .ignoringFields("id") .isEqualTo(projekt); } @Test public void givenProjektWithAngemeldetenTeilnehmern_whenAddingAndRetrieving_thenAngemeldeteTeilnehmerAreNotIncluded() { Long teilnehmerId = addUser(createSampleTeilnehmer()); Long projektId = addProject(createSampleProjekt()); assignUserToProject(projektId, teilnehmerId); Projekt responseProjekt = getProject(projektId); assertThat(responseProjekt.getAngemeldeteTeilnehmer().size(), is(0)); } @Test public void givenProjektWithStorniertenTeilnehmern_whenAddingAndRetrieving_thenStornierteTeilnehmerAreNotIncluded() { Long teilnehmerId = addUser(createSampleTeilnehmer()); Long projektId = addProject(createSampleProjekt()); assignUserToProject(projektId, teilnehmerId); unassignUserFromProject(projektId, teilnehmerId); Projekt responseProjekt = getProject(projektId); assertThat(responseProjekt.getStornierteTeilnehmer().size(), is(0)); } @Test public void givenProjektInDb_whenUpdatingAndRetrieving_thenRetrievedProjektMatchesUpdated() { Long projektId = addProject(createSampleProjekt()); Projekt originalProjekt = getProject(projektId); boolean aktiv = true; String name = "Testprojekt U"; LocalDate datumBeginn = LocalDate.of(2030, 3, 1); LocalDate datumEnde = LocalDate.of(2030, 3, 15); int mindestAlter = 10; int hoechstAlter = 20; int plaetzeGesamt = 30; int plaetzeReserviert = 7; String gruppe = "Neue Gruppe"; // Important: We use the copy-builder, so we automatically use the correct ID Projekt projektToUpdate = Projekt.newBuilder(originalProjekt) .aktiv(aktiv) .name(name) .datumBeginn(datumBeginn) .datumEnde(datumEnde) .mindestAlter(mindestAlter) .hoechstAlter(hoechstAlter) .plaetzeGesamt(plaetzeGesamt) .plaetzeReserviert(plaetzeReserviert) .gruppe(gruppe) .build(); // actual update is here updateProjekt(projektToUpdate); Projekt responseProjekt = getProject(projektId); Assertions.assertThat(responseProjekt). usingRecursiveComparison() .isEqualTo(projektToUpdate); } @Test public void givenProjektWithAnmeldungenAndStornierungenInDb_whenUpdatingAndRetrieving_AnmeldungenUndStornierungenAreNotLost() { Long projektId = addProject(createSampleProjekt()); Projekt originalProjekt = getProject(projektId); Long teilnehmerId = addUser(createSampleTeilnehmer()); Long teilnehmerId2 = addUser(createSampleTeilnehmer()); assignUserToProject(projektId, teilnehmerId); assignUserToProject(projektId, teilnehmerId2); unassignUserFromProject(projektId, teilnehmerId); List<Teilnehmer> allAssignedUsersForOriginalProject = getAllAssignedUsersForGivenProject(projektId); List<Teilnehmer> allCancelledUsersForOriginalProject = getAllCancelledUsersForGivenProject(projektId); // Important: We use the copy-builder, so we automatically use the correct ID Projekt projektToUpdate = Projekt.newBuilder(originalProjekt).build(); // actual update is here updateProjekt(projektToUpdate); List<Teilnehmer> allAssignedUsersForUpdatedProject = getAllAssignedUsersForGivenProject(projektId); List<Teilnehmer> allCancelledUsersForUpdatedProject = getAllCancelledUsersForGivenProject(projektId); assertThat(allAssignedUsersForOriginalProject.get(0).getId(), is(allAssignedUsersForUpdatedProject.get(0).getId())); assertThat(allCancelledUsersForOriginalProject.get(0).getId(), is(allCancelledUsersForUpdatedProject.get(0).getId())); } @Test public void givenProjekt_whenDeletedAndRequested_thenIsNotFound() { Long projektId = addProject(createSampleProjekt()); Projekt responseProjekt = getProject(projektId); Assert.assertThat(responseProjekt.getId(), is(projektId)); deleteProjekt(responseProjekt.getId()); getNoProjekt(projektId); } @Test public void givenTeilnehmerThatIsAssignedToProjekt_whenDeletingProjekt_thenNoFail() { // Given Long teilnehmerId = addUser(createSampleTeilnehmer()); Long projektId = addProject(createSampleProjekt()); assignUserToProject(projektId, teilnehmerId); // When deleteProjekt(projektId); // Then // pass :) } @Test public void givenTeilnehmerThatWasCancelledFromProjekt_whenDeletingProjekt_thenNoFail() { // Given Long teilnehmerId = addUser(createSampleTeilnehmer()); Long projektId = addProject(createSampleProjekt()); assignUserToProject(projektId, teilnehmerId); unassignUserFromProject(projektId, teilnehmerId); // When deleteProjekt(projektId); // Then // pass :) } @Test public void givenProjekt_whenUserIsAssigned_thenUserIsCorrectlyAssigned() { // Given Long userId = addUser(createSampleTeilnehmer()); Long projectId = addProject(createSampleProjekt()); // When assignUserToProject(projectId, userId); // Then List<Teilnehmer> allAssignedUsersForGivenProject = getAllAssignedUsersForGivenProject(projectId); assertThat(allAssignedUsersForGivenProject.size(), is(1)); assertThat(allAssignedUsersForGivenProject.get(0).getId(), is(userId)); List<Teilnehmer> getAllCancelledUsersForGivenProject = getAllCancelledUsersForGivenProject(projectId); assertThat(getAllCancelledUsersForGivenProject.size(), is(0)); } @Test public void givenProjektWithAssignedUser_whenUserIsCancelled_thenUserIsCorrectlyCancelled() { // Given Long userId = addUser(createSampleTeilnehmer()); Long projectId = addProject(createSampleProjekt()); assignUserToProject(projectId, userId); // When unassignUserFromProject(projectId, userId); // Then List<Teilnehmer> allAssignedUsersForGivenProject = getAllAssignedUsersForGivenProject(projectId); assertThat(allAssignedUsersForGivenProject.size(), is(0)); List<Teilnehmer> getAllCancelledUsersForGivenProject = getAllCancelledUsersForGivenProject(projectId); assertThat(getAllCancelledUsersForGivenProject.size(), is(1)); assertThat(getAllCancelledUsersForGivenProject.get(0).getId(), is(userId)); } @Test public void givenProjektWithNoFreeSlots_whenUserIsAssigned_thenFullyBooked() { // Given Long userId = addUser(createSampleTeilnehmer()); Projekt fullyBookedProjekt = createSampleProjektBuilder().plaetzeGesamt(5).plaetzeReserviert(5).build(); Long projectId = addProject(fullyBookedProjekt); given() .pathParam("projectId", projectId) .pathParam("userId", userId) .contentType(ContentType.JSON) .when() .put(BASE_URL + "/projects/{projectId}/users/{userId}") .then() .statusCode(HttpStatus.SC_CONFLICT); } @Test public void givenProjektWithOneTeilnehmer_whenUpdatingProjektWithTooMuchReservedSlots_thenHttpUnprocessableEntity() { Long projectId = addProject(createSampleProjektBuilder().plaetzeGesamt(10).plaetzeReserviert(9).build()); Long userId = addUser(createSampleTeilnehmer()); assignUserToProject(projectId, userId); Projekt projekt = Projekt.newBuilder(getProject(projectId)) .plaetzeReserviert(10) .build(); given() .body(projekt) .contentType(ContentType.JSON) .when() .put(BASE_URL + "/projects") .then() .statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY); } // Check Custom Constraint Validations ------------------------------------------------------------ @Test public void givenDatumEndeBeforeDatumBeginn_whenCreatingProjekt_thenBadRequest() { Projekt projekt = Projekt.newBuilder(DomainFactory.createSampleProjekt()) .datumBeginn(LocalDate.of(2019, 12, 5)) .datumEnde(LocalDate.of(2019, 12, 4)) .build(); given() .body(projekt) .contentType(ContentType.JSON) .when() .post(BASE_URL + "/projects") .then() .statusCode(HttpStatus.SC_BAD_REQUEST) .body("errors", hasSize(1)) .body("errors[0].field", is("datumEnde")); } @Test public void givenHoechstAlterSmallerThanMindestAlter_whenCreatingProjekt_thenBadRequest() { Projekt projekt = Projekt.newBuilder(DomainFactory.createSampleProjekt()) .mindestAlter(11) .hoechstAlter(10) .build(); given() .body(projekt) .contentType(ContentType.JSON) .when() .post(BASE_URL + "/projects") .then() .statusCode(HttpStatus.SC_BAD_REQUEST) .body("errors", hasSize(1)) .body("errors[0].field", is("hoechstAlter")); } @Test public void givenMehrReserviertePlaetzeAlsGesamtplaetze_whenCreatingProjekt_thenBadRequest() { Projekt projekt = Projekt.newBuilder(DomainFactory.createSampleProjekt()) .plaetzeReserviert(10) .plaetzeGesamt(9) .build(); given() .body(projekt) .contentType(ContentType.JSON) .when() .post(BASE_URL + "/projects") .then() .statusCode(HttpStatus.SC_BAD_REQUEST) .body("errors", hasSize(1)) .body("errors[0].field", is("plaetzeReserviert")); } // Helpers ----------------------------------------------------------------------------------- private void updateProjekt(Projekt projekt) { given() .body(projekt) .contentType(ContentType.JSON) .when() .put(BASE_URL+"/projects") .then() .statusCode(HttpStatus.SC_OK); } private void deleteProjekt(Long projektId) { given() .pathParam("projekt_id", projektId) .contentType(ContentType.JSON) .when() .delete(BASE_URL + "/projects/{projekt_id}") .then() .statusCode(HttpStatus.SC_OK); } private void getNoProjekt(Long projektId) { given() .pathParam("id", projektId) .when() .get(BASE_URL + "/projects/{id}") .then() .statusCode(HttpStatus.SC_NOT_FOUND); } private List<Teilnehmer> getAllAssignedUsersForGivenProject(Long projectId) { return Arrays.asList( given() .pathParam("projektId", projectId) .contentType(ContentType.JSON) .when() .get(BASE_URL+"/projects/{projektId}/users") .then() .statusCode(HttpStatus.SC_OK) .extract().as(Teilnehmer[].class)); } private List<Teilnehmer> getAllCancelledUsersForGivenProject(Long projectId) { return Arrays.asList( given() .pathParam("projektId", projectId) .contentType(ContentType.JSON) .when() .get(BASE_URL+"/projects/{projektId}/cancelledusers") .then() .statusCode(HttpStatus.SC_OK) .extract().as(Teilnehmer[].class)); } }
package com.coviam.internalapp.hrms.designation.controller; import com.coviam.internalapp.hrms.designation.DesignationAdaptor; import com.coviam.internalapp.hrms.designation.dto.DesignationDto; import com.coviam.internalapp.hrms.designation.entity.Designation; import com.coviam.internalapp.hrms.designation.service.DesignationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; /** * Created by coviam on 25/01/17. */ @RestController public class DesignationController { @Autowired DesignationService designationservice; @Autowired DesignationAdaptor designationAdaptor; @RequestMapping(value="designation/{customerId}",method = RequestMethod.GET) public ResponseEntity getAlldesignation(@PathVariable String customerId){ return new ResponseEntity(designationservice.getAlldesignation(customerId), HttpStatus.OK); } @RequestMapping(value="designation/add/{customerId}",method= RequestMethod.POST) public ResponseEntity addDesignation(@PathVariable String customerId, @RequestBody Designation designation)throws Exception{ return new ResponseEntity(designationservice.addDesignation(designation), HttpStatus.OK); } @RequestMapping(value="designation/delete/{customerId}/{designationId}",method= RequestMethod.PUT) public ResponseEntity deleteDesignation(@PathVariable String customerId,@PathVariable String designationId){ return new ResponseEntity(designationservice.deleteDesignation(customerId, designationId), HttpStatus.OK); } @RequestMapping(value="designation/update/{designationId}",method= RequestMethod.PUT) public ResponseEntity updateDesignation(@PathVariable String designationId, @RequestBody Designation designation)throws Exception{ return new ResponseEntity(designationservice.updateDesignation(designation), HttpStatus.OK); } @RequestMapping(value="designation/getById/{customerId}/{designationId}",method= RequestMethod.GET) public DesignationDto getDesignation(@PathVariable String customerId, @PathVariable String designationId){ Designation designation = designationservice.getDesignation(customerId,designationId); DesignationDto designationDto = designationAdaptor.convertToDto(designation); return designationDto; } @RequestMapping(value="designation/getByCode/{customerId}/{designationCode}",method= RequestMethod.GET) public ResponseEntity getDesignationByDesignationCode(@PathVariable String customerId, @PathVariable String designationCode){ return new ResponseEntity(designationservice.getDesignationByDesignationCode(customerId,designationCode), HttpStatus.OK); } }
/* * 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.hdfstests; import org.apache.flink.api.common.io.FileOutputFormat; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.ExecutionEnvironmentFactory; import org.apache.flink.api.java.LocalEnvironment; import org.apache.flink.api.java.io.AvroOutputFormat; import org.apache.flink.configuration.BlobServerOptions; import org.apache.flink.configuration.ConfigConstants; import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.HighAvailabilityOptions; import org.apache.flink.core.fs.FileSystem; import org.apache.flink.core.fs.Path; import org.apache.flink.examples.java.wordcount.WordCount; import org.apache.flink.runtime.blob.BlobRecoveryITCase; import org.apache.flink.runtime.blob.BlobStoreService; import org.apache.flink.runtime.blob.BlobUtils; import org.apache.flink.runtime.fs.hdfs.HadoopFileSystem; import org.apache.flink.runtime.jobmanager.HighAvailabilityMode; import org.apache.flink.util.FileUtils; import org.apache.flink.util.OperatingSystem; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.Arrays; import java.util.UUID; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * This test should logically be located in the 'flink-runtime' tests. However, this project * has already all dependencies required (flink-java-examples). Also, the ParallelismOneExecEnv is here. */ public class HDFSTest { protected String hdfsURI; private MiniDFSCluster hdfsCluster; private org.apache.hadoop.fs.Path hdPath; protected org.apache.hadoop.fs.FileSystem hdfs; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @BeforeClass public static void verifyOS() { Assume.assumeTrue("HDFS cluster cannot be started on Windows without extensions.", !OperatingSystem.isWindows()); } @Before public void createHDFS() { try { Configuration hdConf = new Configuration(); File baseDir = new File("./target/hdfs/hdfsTest").getAbsoluteFile(); FileUtil.fullyDelete(baseDir); hdConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath()); MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(hdConf); hdfsCluster = builder.build(); hdfsURI = "hdfs://" + hdfsCluster.getURI().getHost() + ":" + hdfsCluster.getNameNodePort() + "/"; hdPath = new org.apache.hadoop.fs.Path("/test"); hdfs = hdPath.getFileSystem(hdConf); FSDataOutputStream stream = hdfs.create(hdPath); for (int i = 0; i < 10; i++) { stream.write("Hello HDFS\n".getBytes(ConfigConstants.DEFAULT_CHARSET)); } stream.close(); } catch (Throwable e) { e.printStackTrace(); Assert.fail("Test failed " + e.getMessage()); } } @After public void destroyHDFS() { try { hdfs.delete(hdPath, false); hdfsCluster.shutdown(); } catch (IOException e) { throw new RuntimeException(e); } } @Test public void testHDFS() { Path file = new Path(hdfsURI + hdPath); org.apache.hadoop.fs.Path result = new org.apache.hadoop.fs.Path(hdfsURI + "/result"); try { FileSystem fs = file.getFileSystem(); assertTrue("Must be HadoopFileSystem", fs instanceof HadoopFileSystem); DopOneTestEnvironment.setAsContext(); try { WordCount.main(new String[]{ "--input", file.toString(), "--output", result.toString()}); } catch (Throwable t) { t.printStackTrace(); Assert.fail("Test failed with " + t.getMessage()); } finally { DopOneTestEnvironment.unsetAsContext(); } assertTrue("No result file present", hdfs.exists(result)); // validate output: org.apache.hadoop.fs.FSDataInputStream inStream = hdfs.open(result); StringWriter writer = new StringWriter(); IOUtils.copy(inStream, writer); String resultString = writer.toString(); Assert.assertEquals("hdfs 10\n" + "hello 10\n", resultString); inStream.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail("Error in test: " + e.getMessage()); } } @Test public void testAvroOut() { String type = "one"; AvroOutputFormat<String> avroOut = new AvroOutputFormat<String>(String.class); org.apache.hadoop.fs.Path result = new org.apache.hadoop.fs.Path(hdfsURI + "/avroTest"); avroOut.setOutputFilePath(new Path(result.toString())); avroOut.setWriteMode(FileSystem.WriteMode.NO_OVERWRITE); avroOut.setOutputDirectoryMode(FileOutputFormat.OutputDirectoryMode.ALWAYS); try { avroOut.open(0, 2); avroOut.writeRecord(type); avroOut.close(); avroOut.open(1, 2); avroOut.writeRecord(type); avroOut.close(); assertTrue("No result file present", hdfs.exists(result)); FileStatus[] files = hdfs.listStatus(result); Assert.assertEquals(2, files.length); for (FileStatus file : files) { assertTrue("1.avro".equals(file.getPath().getName()) || "2.avro".equals(file.getPath().getName())); } } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } /** * Test that {@link FileUtils#deletePathIfEmpty(FileSystem, Path)} deletes the path if it is * empty. A path can only be empty if it is a directory which does not contain any * files/directories. */ @Test public void testDeletePathIfEmpty() throws IOException { final Path basePath = new Path(hdfsURI); final Path directory = new Path(basePath, UUID.randomUUID().toString()); final Path directoryFile = new Path(directory, UUID.randomUUID().toString()); final Path singleFile = new Path(basePath, UUID.randomUUID().toString()); FileSystem fs = basePath.getFileSystem(); fs.mkdirs(directory); byte[] data = "HDFSTest#testDeletePathIfEmpty".getBytes(ConfigConstants.DEFAULT_CHARSET); for (Path file: Arrays.asList(singleFile, directoryFile)) { org.apache.flink.core.fs.FSDataOutputStream outputStream = fs.create(file, FileSystem.WriteMode.OVERWRITE); outputStream.write(data); outputStream.close(); } // verify that the files have been created assertTrue(fs.exists(singleFile)); assertTrue(fs.exists(directoryFile)); // delete the single file assertFalse(FileUtils.deletePathIfEmpty(fs, singleFile)); assertTrue(fs.exists(singleFile)); // try to delete the non-empty directory assertFalse(FileUtils.deletePathIfEmpty(fs, directory)); assertTrue(fs.exists(directory)); // delete the file contained in the directory assertTrue(fs.delete(directoryFile, false)); // now the deletion should work assertTrue(FileUtils.deletePathIfEmpty(fs, directory)); assertFalse(fs.exists(directory)); } /** * Tests that with {@link HighAvailabilityMode#ZOOKEEPER} distributed JARs are recoverable from any * participating BlobServer. */ @Test public void testBlobServerRecovery() throws Exception { org.apache.flink.configuration.Configuration config = new org.apache.flink.configuration.Configuration(); config.setString(HighAvailabilityOptions.HA_MODE, "ZOOKEEPER"); config.setString(CoreOptions.STATE_BACKEND, "ZOOKEEPER"); config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath()); config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, hdfsURI); BlobStoreService blobStoreService = null; try { blobStoreService = BlobUtils.createBlobStoreFromConfig(config); BlobRecoveryITCase.testBlobServerRecovery(config, blobStoreService); } finally { if (blobStoreService != null) { blobStoreService.closeAndCleanupAllData(); } } } abstract static class DopOneTestEnvironment extends ExecutionEnvironment { public static void setAsContext() { final LocalEnvironment le = new LocalEnvironment(); le.setParallelism(1); initializeContextEnvironment(new ExecutionEnvironmentFactory() { @Override public ExecutionEnvironment createExecutionEnvironment() { return le; } }); } public static void unsetAsContext() { resetContextEnvironment(); } } }
/** * <copyright> * </copyright> * * $Id$ */ package orgomg.cwm.analysis.datamining.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; import orgomg.cwm.analysis.datamining.ClusteringSettings; import orgomg.cwm.analysis.datamining.DataminingPackage; import orgomg.cwm.objectmodel.core.CorePackage; import orgomg.cwm.objectmodel.core.provider.Cwm_mipEditPlugin; /** * This is the item provider adapter for a {@link orgomg.cwm.analysis.datamining.ClusteringSettings} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ClusteringSettingsItemProvider extends MiningSettingsItemProvider implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ClusteringSettingsItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addMaxNumberOfClustersPropertyDescriptor(object); addClusterIdAttributeNamePropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Max Number Of Clusters feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addMaxNumberOfClustersPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ClusteringSettings_maxNumberOfClusters_feature"), getString("_UI_PropertyDescriptor_description", "_UI_ClusteringSettings_maxNumberOfClusters_feature", "_UI_ClusteringSettings_type"), DataminingPackage.Literals.CLUSTERING_SETTINGS__MAX_NUMBER_OF_CLUSTERS, true, false, false, ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Cluster Id Attribute Name feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addClusterIdAttributeNamePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ClusteringSettings_clusterIdAttributeName_feature"), getString("_UI_PropertyDescriptor_description", "_UI_ClusteringSettings_clusterIdAttributeName_feature", "_UI_ClusteringSettings_type"), DataminingPackage.Literals.CLUSTERING_SETTINGS__CLUSTER_ID_ATTRIBUTE_NAME, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This returns ClusteringSettings.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/ClusteringSettings")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((ClusteringSettings)object).getName(); return label == null || label.length() == 0 ? getString("_UI_ClusteringSettings_type") : getString("_UI_ClusteringSettings_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(ClusteringSettings.class)) { case DataminingPackage.CLUSTERING_SETTINGS__MAX_NUMBER_OF_CLUSTERS: case DataminingPackage.CLUSTERING_SETTINGS__CLUSTER_ID_ATTRIBUTE_NAME: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } /** * This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) { Object childFeature = feature; Object childObject = child; boolean qualify = childFeature == CorePackage.Literals.NAMESPACE__OWNED_ELEMENT || childFeature == DataminingPackage.Literals.MINING_SETTINGS__ATTRIBUTE_USAGE || childFeature == CorePackage.Literals.CLASSIFIER__FEATURE; if (qualify) { return getString ("_UI_CreateChild_text2", new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) }); } return super.getCreateChildText(owner, feature, child, selection); } /** * Return the resource locator for this item provider's resources. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ResourceLocator getResourceLocator() { return Cwm_mipEditPlugin.INSTANCE; } }
/* * #%L * de.metas.business.rest-api-impl * %% * Copyright (C) 2021 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.rest_api.remittanceadvice.impl; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import de.metas.banking.api.IBPBankAccountDAO; import de.metas.bpartner.BPartnerBankAccountId; import de.metas.bpartner.BPartnerId; import de.metas.bpartner.service.BPartnerQuery; import de.metas.bpartner.service.IBPartnerDAO; import de.metas.common.rest_api.JsonMetasfreshId; import de.metas.common.rest_api.remittanceadvice.JsonCreateRemittanceAdviceRequest; import de.metas.common.rest_api.remittanceadvice.JsonCreateRemittanceAdviceResponse; import de.metas.common.rest_api.remittanceadvice.JsonCreateRemittanceAdviceResponseItem; import de.metas.common.rest_api.remittanceadvice.JsonRemittanceAdvice; import de.metas.common.rest_api.remittanceadvice.JsonRemittanceAdviceLine; import de.metas.currency.CurrencyCode; import de.metas.currency.CurrencyRepository; import de.metas.document.DocTypeId; import de.metas.document.DocTypeQuery; import de.metas.document.IDocTypeDAO; import de.metas.document.sequence.IDocumentNoBuilderFactory; import de.metas.error.AdIssueId; import de.metas.error.IErrorManager; import de.metas.logging.LogManager; import de.metas.money.CurrencyId; import de.metas.organization.IOrgDAO; import de.metas.organization.OrgId; import de.metas.organization.OrgQuery; import de.metas.remittanceadvice.CreateRemittanceAdviceLineRequest; import de.metas.remittanceadvice.CreateRemittanceAdviceRequest; import de.metas.remittanceadvice.RemittanceAdvice; import de.metas.remittanceadvice.RemittanceAdviceId; import de.metas.remittanceadvice.RemittanceAdviceRepository; import de.metas.rest_api.utils.IdentifierString; import de.metas.util.Check; import de.metas.util.Services; import lombok.NonNull; import org.adempiere.ad.trx.api.ITrxManager; import org.adempiere.exceptions.AdempiereException; import org.adempiere.service.ClientId; import org.compiere.model.I_C_BP_BankAccount; import org.compiere.model.I_C_BPartner; import org.compiere.model.X_C_DocType; import org.compiere.util.Env; import org.slf4j.Logger; import org.springframework.stereotype.Service; import javax.annotation.Nullable; import java.math.BigDecimal; import java.time.Instant; import java.util.List; import java.util.Optional; @Service public class CreateRemittanceAdviceService { private static final transient Logger logger = LogManager.getLogger(CreateRemittanceAdviceService.class); private final CurrencyRepository currencyRepository; private final RemittanceAdviceRepository remittanceAdviceRepository; private final IOrgDAO orgDAO = Services.get(IOrgDAO.class); private final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); private final IBPBankAccountDAO bankAccountDAO = Services.get(IBPBankAccountDAO.class); private final IBPartnerDAO bPartnerDAO = Services.get(IBPartnerDAO.class); private final ITrxManager trxManager = Services.get(ITrxManager.class); public CreateRemittanceAdviceService( @NonNull final CurrencyRepository currencyRepository, @NonNull final RemittanceAdviceRepository remittanceAdviceRepository) { this.currencyRepository = currencyRepository; this.remittanceAdviceRepository = remittanceAdviceRepository; } @Nullable public JsonCreateRemittanceAdviceResponse createRemittanceAdviceList(@NonNull final JsonCreateRemittanceAdviceRequest request) { return trxManager.callInNewTrx(() -> createRemittanceInTrx(request)); } private JsonCreateRemittanceAdviceResponse createRemittanceInTrx(@NonNull final JsonCreateRemittanceAdviceRequest request) { final ImmutableList.Builder<RemittanceAdviceId> remittanceAdviceIdList = ImmutableList.builder(); try { final List<JsonRemittanceAdvice> jsonRemittanceAdviceList = request.getRemittanceAdviceList(); for (final JsonRemittanceAdvice jsonRemittanceAdvice : jsonRemittanceAdviceList) { final CreateRemittanceAdviceRequest remittanceAdviceReq = buildRemittanceAdviceRequest(jsonRemittanceAdvice); final RemittanceAdvice remittanceAdvice = remittanceAdviceRepository.createRemittanceAdviceHeader(remittanceAdviceReq); final RemittanceAdviceId remittanceAdviceId = remittanceAdvice.getRemittanceAdviceId(); remittanceAdviceIdList.add(remittanceAdviceId); final List<JsonRemittanceAdviceLine> jsonRemittanceAdviceLines = jsonRemittanceAdvice.getLines(); for (final JsonRemittanceAdviceLine jsonRemittanceAdviceLine : jsonRemittanceAdviceLines) { final CreateRemittanceAdviceLineRequest createRemittanceAdviceLineReq = buildRemittanceAdviceLineRequest( jsonRemittanceAdviceLine, remittanceAdviceId, remittanceAdvice.getOrgId()); remittanceAdviceRepository.createRemittanceAdviceLine(createRemittanceAdviceLineReq); } } final ImmutableList.Builder<JsonCreateRemittanceAdviceResponseItem> ids = ImmutableList.builder(); for (final RemittanceAdviceId remittanceAdviceId : remittanceAdviceIdList.build()) { final JsonMetasfreshId jsonMetasfreshId = JsonMetasfreshId.of(remittanceAdviceId.getRepoId()); final JsonCreateRemittanceAdviceResponseItem item = JsonCreateRemittanceAdviceResponseItem.builder() .remittanceAdviceId(jsonMetasfreshId).build(); ids.add(item); } return JsonCreateRemittanceAdviceResponse.builder() .ids(ids.build()) .build(); } catch (final Exception e) { final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(e); logger.error("Could not save the given model; message={}; AD_Issue_ID={}", e.getLocalizedMessage(), issueId); throw e; } } private CreateRemittanceAdviceRequest buildRemittanceAdviceRequest(@NonNull final JsonRemittanceAdvice jsonRemittanceAdvice) { final ClientId clientId = Env.getClientId(); final BPartnerId sourceBPartnerId = getBPartnerId(IdentifierString.of(jsonRemittanceAdvice.getSenderId())); final BPartnerId destinationBPartnerId = getBPartnerId(IdentifierString.of(jsonRemittanceAdvice.getRecipientId())); final OrgId orgId; if (jsonRemittanceAdvice.getOrgCode() == null) { orgId = jsonRemittanceAdvice.getRemittanceAdviceType().isInbound() ? retrieveOrgIdByBPartnerId(sourceBPartnerId) : retrieveOrgIdByBPartnerId(destinationBPartnerId); } else { orgId = retrieveOrgId(jsonRemittanceAdvice.getOrgCode()); } final BPartnerBankAccountId sourceBPartnerBankAccountId = getBPartnerBankAccountId(sourceBPartnerId); final BPartnerBankAccountId destinationBPartnerBankAccountId = getBPartnerBankAccountId(destinationBPartnerId); final CurrencyId remittedAmountCurrencyId = getCurrencyIdByCurrencyISO(jsonRemittanceAdvice.getRemittanceAmountCurrencyISO()); CurrencyId serviceFeeCurrencyId = null; final BigDecimal serviceFeeAmt = jsonRemittanceAdvice.getServiceFeeAmount(); if (serviceFeeAmt.compareTo(BigDecimal.ZERO) > 0) { final String serviceFeeCurrencyISO = jsonRemittanceAdvice.getServiceFeeCurrencyISO(); if (serviceFeeCurrencyISO == null) { throw new AdempiereException("Missing service fee currency ISO for service fee amount!") .appendParametersToMessage() .setParameter("serviceFeeAmount", jsonRemittanceAdvice.getServiceFeeAmount()); } serviceFeeCurrencyId = getCurrencyIdByCurrencyISO(jsonRemittanceAdvice.getServiceFeeCurrencyISO()); } final DocTypeId targetPaymentDocTypeId = getDocTypeIdByType(jsonRemittanceAdvice.getRemittanceAdviceType().getDocBaseType(), clientId, orgId); final DocTypeId remittanceDocTypeId = getDocTypeIdByType(X_C_DocType.DOCBASETYPE_RemittanceAdvice, clientId, orgId); final String remittanceDocNumber = buildDocumentNo(remittanceDocTypeId); final Instant sendDate = jsonRemittanceAdvice.getSendDate() != null ? Instant.parse(jsonRemittanceAdvice.getSendDate()) : null; final Instant documentDate = jsonRemittanceAdvice.getDocumentDate() != null ? Instant.parse(jsonRemittanceAdvice.getDocumentDate()) : Instant.now(); return CreateRemittanceAdviceRequest.builder() .isImported(Boolean.TRUE) .orgId(orgId) .clientId(clientId) .docTypeId(remittanceDocTypeId) .documentNumber(remittanceDocNumber) .sourceBPartnerId(sourceBPartnerId) .sourceBPartnerBankAccountId(sourceBPartnerBankAccountId) .destinationBPartnerId(destinationBPartnerId) .destinationBPartnerBankAccountId(destinationBPartnerBankAccountId) .externalDocumentNumber(jsonRemittanceAdvice.getDocumentNumber()) .sendDate(sendDate) .documentDate(documentDate) .targetPaymentDocTypeId(targetPaymentDocTypeId) .remittedAmountSum(jsonRemittanceAdvice.getRemittedAmountSum()) .remittedAmountCurrencyId(remittedAmountCurrencyId) .serviceFeeAmount(jsonRemittanceAdvice.getServiceFeeAmount()) .serviceFeeCurrencyId(serviceFeeCurrencyId) .paymentDiscountAmountSum(jsonRemittanceAdvice.getPaymentDiscountAmountSum()) .additionalNotes(jsonRemittanceAdvice.getAdditionalNotes()) .build(); } private CreateRemittanceAdviceLineRequest buildRemittanceAdviceLineRequest( @NonNull final JsonRemittanceAdviceLine jsonRemittanceAdviceLine, @NonNull final RemittanceAdviceId remittanceAdviceId, @NonNull final OrgId orgId) { final BPartnerId bPartnerId = Check.isEmpty(jsonRemittanceAdviceLine.getBpartnerIdentifier()) ? null : getOptionalBPartnerId(IdentifierString.of(jsonRemittanceAdviceLine.getBpartnerIdentifier())).orElse(null); final Instant dateInvoiced = jsonRemittanceAdviceLine.getDateInvoiced() != null ? Instant.parse(jsonRemittanceAdviceLine.getDateInvoiced()) : null; return CreateRemittanceAdviceLineRequest.builder() .remittanceAdviceId(remittanceAdviceId) .orgId(orgId) .invoiceIdentifier(jsonRemittanceAdviceLine.getInvoiceIdentifier()) .remittedAmount(jsonRemittanceAdviceLine.getRemittedAmount()) .dateInvoiced(dateInvoiced) .bpartnerIdentifier(bPartnerId) .externalInvoiceDocBaseType(jsonRemittanceAdviceLine.getInvoiceBaseDocType()) .invoiceGrossAmount(jsonRemittanceAdviceLine.getInvoiceGrossAmount()) .paymentDiscountAmount(jsonRemittanceAdviceLine.getPaymentDiscountAmount()) .serviceFeeAmount(jsonRemittanceAdviceLine.getServiceFeeAmount()) .serviceFeeVatRate(jsonRemittanceAdviceLine.getServiceFeeVatRate()) .build(); } private OrgId retrieveOrgId(@NonNull final String orgCode) { final Optional<OrgId> orgId; final OrgQuery query = OrgQuery.builder() .orgValue(orgCode) .build(); orgId = orgDAO.retrieveOrgIdBy(query); return orgId.orElse(Env.getOrgId()); } private OrgId retrieveOrgIdByBPartnerId(@NonNull final BPartnerId bPartnerId) { final I_C_BPartner bPartner = bPartnerDAO.getById(bPartnerId); return OrgId.ofRepoId(bPartner.getAD_Org_ID()); } @NonNull private BPartnerId getBPartnerId(final IdentifierString identifierString) { final Optional<BPartnerId> optionalBPartnerId = getOptionalBPartnerId(identifierString); return optionalBPartnerId.orElseThrow(() -> new AdempiereException("No BPartner found for IdentifierString") .appendParametersToMessage().setParameter("IdentifierString", identifierString)); } @NonNull private Optional<BPartnerId> getOptionalBPartnerId(@NonNull final IdentifierString identifierString) { final BPartnerQuery query = buildBPartnerQuery(identifierString); return bPartnerDAO.retrieveBPartnerIdBy(query); } @NonNull private CurrencyId getCurrencyIdByCurrencyISO(@NonNull final String currencyISO) { final CurrencyCode convertedToCurrencyCode = CurrencyCode.ofThreeLetterCode(currencyISO); return currencyRepository.getCurrencyIdByCurrencyCode(convertedToCurrencyCode); } @NonNull private BPartnerBankAccountId getBPartnerBankAccountId(@NonNull final BPartnerId bPartnerId) { final I_C_BP_BankAccount sourceBPartnerBankAccount = bankAccountDAO.retrieveDefaultBankAccountInTrx(bPartnerId) .orElseThrow(() -> new AdempiereException("No BPartnerBankAccount found for BPartnerId") .appendParametersToMessage() .setParameter("BPartnerId", bPartnerId)); return BPartnerBankAccountId.ofRepoId(BPartnerId.toRepoId(bPartnerId), sourceBPartnerBankAccount.getC_BP_BankAccount_ID()); } @NonNull private DocTypeId getDocTypeIdByType( @NonNull final String type, @NonNull final ClientId clientId, @NonNull final OrgId orgId) { final DocTypeQuery docTypeQuery = DocTypeQuery.builder() .docBaseType(type) .adClientId(clientId.getRepoId()) .adOrgId(orgId.getRepoId()) .build(); return docTypeDAO.getDocTypeId(docTypeQuery); } private BPartnerQuery buildBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier) { final IdentifierString.Type type = bpartnerIdentifier.getType(); final BPartnerQuery query; switch (type) { case METASFRESH_ID: query = BPartnerQuery.builder() .bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId)) .build(); break; case EXTERNAL_ID: query = BPartnerQuery.builder() .externalId(bpartnerIdentifier.asExternalId()) .build(); break; case GLN: query = BPartnerQuery.builder() .gln(bpartnerIdentifier.asGLN()) .build(); break; case VALUE: query = BPartnerQuery.builder() .bpartnerValue(bpartnerIdentifier.asValue()) .build(); break; default: throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier); } return query; } @VisibleForTesting public String buildDocumentNo(@NonNull final DocTypeId docTypeId) { final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class); final String documentNo = documentNoFactory.forDocType(docTypeId.getRepoId(), /* useDefiniteSequence */false) .setClientId(Env.getClientId()) .setFailOnError(true) .build(); if (documentNo == null) { throw new AdempiereException("Cannot fetch documentNo for " + docTypeId); } return documentNo; } }
package com.endava.service; import com.endava.exception.OrderException; import com.endava.model.ClientOrder; import com.endava.model.Coffee; import com.endava.model.Ingredient; import com.endava.model.Recipe; import com.endava.repository.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CoffeeServiceImpl implements CoffeeService { @Autowired CoffeeRepoImpl coffeeRepo; @Autowired OrderOfUser orderOfUser; @Autowired IngredientRepoImpl ingredientRepo; @Autowired OrderRepository orderRepository; @Autowired RecipeRepository recipeRepository; @Autowired InventoryRepository inventoryRepository; @Override public Coffee createCoffee(List<Ingredient> recipe, String clientName) { double price = 0; for (Ingredient ingredient:recipe){ price += ingredient.getPrice()*ingredient.getAmount(); } return new Coffee(clientName, price, recipe); } @Override public double getPriceByName(String name){ return coffeeRepo.getPriceByName(name); } @Override public Coffee getCoffee(String name){ return coffeeRepo.getCoffee(name); } @Override public String toString() { return coffeeRepo.toString(); } @Override public void addOrder(Coffee beverage, Integer quantity, String customerName, boolean pickup) throws OrderException { List<Ingredient> ingredientList = beverage.getIngredients(); for(Ingredient ingredient: ingredientList){ if (ingredient.getAmount() > inventoryRepository.findByType(ingredient.getName()).getQuantity()) throw new OrderException("Not enough supplies!"); } orderOfUser.addOrder(new ClientOrder(beverage.getName(),customerName,beverage.getPrice(),pickup, quantity)); orderRepository.save(new ClientOrder(beverage.getName(),customerName,beverage.getPrice(),pickup, quantity)); } public void addOrderBrewing(Coffee beverage, Integer quantity, String customerName, boolean pickup) throws OrderException { orderOfUser.addOrder(new ClientOrder(beverage.getName(),customerName,beverage.getPrice(),pickup, quantity)); orderRepository.save(new ClientOrder(beverage.getName(),customerName,beverage.getPrice(),pickup, quantity)); } public List<Recipe> getAllRecipes(){ return (List<Recipe>) recipeRepository.findAll(); } public List<ClientOrder> getAll(){ return orderOfUser.getAll(); } }
package com.mxn.soul.flowingdrawer.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; import com.mxn.soul.flowingdrawer.R; import com.mxn.soul.flowingdrawer.activity.PublishActivity; import com.mxn.soul.flowingdrawer.adapter.MyItemAdapter; import com.mxn.soul.flowingdrawer.enity.Order; import com.mxn.soul.flowingdrawer.enity.User; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.listener.FindListener; /** * 这是首页的fragment * Created by mk on 2017/6/20. */ public class Main0Fragment extends BaseFragment { //(在MainActivity中通过反射机制获得单例对象) public static volatile Main0Fragment instance = null; @BindView(R.id.rvFeed) RecyclerView rvFeed; @BindView(R.id.refreshLayout) SwipeRefreshLayout refreshLayout; @BindView(R.id.imgAdd) ImageView imgAdd; Unbinder unbinder; private List<Order> mLists = new ArrayList<Order>(); private MyItemAdapter myItemAdapter = null; private User user = null; //单例模式 public static Main0Fragment newInstance() { if (instance == null) { synchronized (Main0Fragment.class) { if (instance == null) { instance = new Main0Fragment(); } } } return instance; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main0, null); unbinder = ButterKnife.bind(this, view); query(); return view; } @Override public void initData() { } @Override public void initTitle() { } @Override public void initView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()) { @Override protected int getExtraLayoutSpace(RecyclerView.State state) { return 300; } }; rvFeed.setLayoutManager(linearLayoutManager); myItemAdapter = new MyItemAdapter(mLists,getActivity()); rvFeed.setAdapter(myItemAdapter); } @Override public void setListener() { imgAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (user != null) { PublishActivity.startAction(getActivity()); } else { Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show(); } } }); refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refresh(); } }); rvFeed.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); } }); myItemAdapter.setOnMyClickItemListener(new MyItemAdapter.onMyClickItemListener() { @Override public void clickItem(View view, int position) { Toast.makeText(getActivity(), "点击了" + position, Toast.LENGTH_SHORT).show(); } }); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } public void query() { BmobQuery<Order> queryData = new BmobQuery<Order>(); queryData.setLimit(15); queryData.include("user"); queryData.findObjects(getActivity(), new FindListener<Order>() { @Override public void onSuccess(List<Order> list) { if (list != null) { mLists = list; myItemAdapter.updateItems(mLists); } } @Override public void onError(int i, String s) { Toast.makeText(getActivity(), "查询失败", Toast.LENGTH_SHORT).show(); } }); } public void refresh() { BmobQuery<Order> queryData = new BmobQuery<Order>(); queryData.setLimit(15); queryData.include("user"); queryData.findObjects(getActivity(), new FindListener<Order>() { @Override public void onSuccess(List<Order> list) { if (list != null) { mLists.clear(); mLists.addAll(list); Toast.makeText(getActivity(), "刷新成功", Toast.LENGTH_SHORT).show(); myItemAdapter.updateItems(mLists); refreshLayout.setRefreshing(false); } } @Override public void onError(int i, String s) { Toast.makeText(getActivity(), "网络出错", Toast.LENGTH_SHORT).show(); refreshLayout.setRefreshing(false); } }); } }
package com.lanshiqin.pigeon.server.exception; import com.lanshiqin.pigeon.server.constant.ResultCodeEnum; /** * 业务异常 * * @author 蓝士钦 */ public class BusinessException extends RuntimeException { private Integer resultCode; public BusinessException(String resultMsg) { super(resultMsg); this.resultCode = ResultCodeEnum.BUSINESS_EXCEPTION.getCode(); } public Integer getResultCode() { return resultCode; } }
package softuni.winelovers.data.models.shop; import softuni.winelovers.data.models.base.BaseEntity; import softuni.winelovers.data.models.news.Event; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "addresses") public class Address extends BaseEntity { @Column(name = "country", nullable = false) private String country; @Column(name = "city", nullable = false) private String city; @Column(name = "street", nullable = false) private String street; @Column(name = "number", nullable = false) private String number; @ManyToMany(mappedBy = "eventAddress") private List<Event> events; @OneToOne(mappedBy = "address", cascade = CascadeType.ALL) private Shop shop; public Address() { this.events = new ArrayList<>(); } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public List<Event> getEvents() { return events; } public void setEvents(List<Event> events) { this.events = events; } public Shop getShop() { return shop; } public void setShop(Shop shop) { this.shop = shop; } public void addEvent(Event event){ this.events.add(event); } // TODO: google map locator }
package com.babylonhealth.lit.usbase_java.builders; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; import java.util.stream.Collectors; import scala.math.BigDecimal; import scala.Option; import scala.collection.immutable.Seq; import scala.jdk.javaapi.CollectionConverters; import scala.jdk.javaapi.OptionConverters; import lombok.NonNull; import com.babylonhealth.lit.core.FHIRComponentFieldMeta; import com.babylonhealth.lit.core.FHIRDateTime; import com.babylonhealth.lit.core.FHIRDate; import com.babylonhealth.lit.core.LitSeqJCollector; import com.babylonhealth.lit.core.LitSeq; import com.babylonhealth.lit.core.LitSeq$; import com.babylonhealth.lit.core.NonEmptyLitSeqJCollector; import com.babylonhealth.lit.core.Choice; import com.babylonhealth.lit.core.Choice$; import com.babylonhealth.lit.core.model.*; import com.babylonhealth.lit.hl7.model.*; import com.babylonhealth.lit.usbase.model.*; import com.babylonhealth.lit.core_java.builders.*; import com.babylonhealth.lit.hl7_java.builders.*; import com.babylonhealth.lit.usbase_java.builders.*; import com.babylonhealth.lit.core_java.model.Unions.*; import com.babylonhealth.lit.hl7_java.model.Unions.*; import com.babylonhealth.lit.usbase_java.model.Unions.*; import com.babylonhealth.lit.core.$bslash$div; import com.babylonhealth.lit.core_java.LitUtils; import static com.babylonhealth.lit.core_java.LitUtils.autoSuffix; import static com.babylonhealth.lit.core_java.LitUtils.guard; import static java.util.stream.Collectors.toList; public interface Elementdefinition_maxValueSetBuilder extends ExtensionBuilder { public Elementdefinition_maxValueSet build(); public static Impl init(@NonNull ChoiceCanonicalOrUri value) { return new Impl(value); } public static Impl builder(@NonNull ChoiceCanonicalOrUri value) { return new Impl(value); } public static ChoiceCanonicalOrUri valueCanonical(String s) { return ChoiceCanonicalOrUri.ChoiceCanonicalOrUriCanonical(s); } public static ChoiceCanonicalOrUri valueUri(String s) { return ChoiceCanonicalOrUri.ChoiceCanonicalOrUriUriStr(s); } public class Impl implements Elementdefinition_maxValueSetBuilder { private Optional<String> id = Optional.empty(); private ChoiceCanonicalOrUri value; /** * Required fields for {@link Elementdefinition_maxValueSet} * * @param value - Value of extension - must be one of a constrained set of the data types (see * [Extensibility](http://hl7.org/fhir/extensibility.html) for a list). Field is a 'choice' * field. Type should be one of String. To pass the value in, wrap with one of the * Elementdefinition_maxValueSetBuilder.value static methods */ public Impl(@NonNull ChoiceCanonicalOrUri value) { this.value = value; } /** * @param id - Unique id for the element within a resource (for internal references). This may * be any string value that does not contain spaces. */ public Elementdefinition_maxValueSetBuilder.Impl withId(@NonNull String id) { this.id = Optional.of(id); return this; } public Elementdefinition_maxValueSet build() { return new Elementdefinition_maxValueSet( OptionConverters.toScala(id), value, LitUtils.emptyMetaElMap()); } } }
/******************************************************************************* * * Pentaho Big Data * * Copyright (C) 2002-2014 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.hadoop.shim.mapr31; import org.pentaho.hadoop.shim.common.CommonPigShim; import org.apache.pig.PigServer; import org.apache.pig.tools.grunt.GruntParser; import java.io.IOException; import java.io.StringReader; import java.util.Properties; public class PigShim extends CommonPigShim { @Override public boolean isLocalExecutionSupported() { // Local execution is not supported in MapR return false; } @Override public int[] executeScript( String pigScript, org.pentaho.hadoop.shim.spi.PigShim.ExecutionMode mode, Properties properties ) throws IOException, org.apache.pig.tools.pigscript.parser.ParseException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); try { PigServer pigServer = new PigServer( getExecType( mode ), properties ); GruntParser grunt = new GruntParser( new StringReader( pigScript ) ); grunt.setInteractive( false ); grunt.setParams( pigServer ); return grunt.parseStopOnError( false ); } finally { Thread.currentThread().setContextClassLoader( cl ); } } }
package no.mnemonic.act.platform.api.model.v1; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.UUID; @ApiModel(description = "Represents a Subject inside the system, e.g. a user.") public class Subject { @ApiModelProperty(value = "Uniquely identifies the Subject", example = "123e4567-e89b-12d3-a456-426655440000", required = true) private final UUID id; @ApiModelProperty(value = "Name of the Subject", example = "John Doe", required = true) private final String name; private Subject(UUID id, String name) { this.id = id; this.name = name; } public UUID getId() { return id; } public String getName() { return name; } public Info toInfo() { return new Info(id, name); } public static Builder builder() { return new Builder(); } public static class Builder { private UUID id; private String name; private Builder() { } public Subject build() { return new Subject(id, name); } public Builder setId(UUID id) { this.id = id; return this; } public Builder setName(String name) { this.name = name; return this; } } @ApiModel(value = "SubjectInfo", description = "Short summary of a Subject.") public class Info { @ApiModelProperty(value = "Uniquely identifies the Subject", example = "123e4567-e89b-12d3-a456-426655440000", required = true) private final UUID id; @ApiModelProperty(value = "Name of the Subject", example = "John Doe", required = true) private final String name; private Info(UUID id, String name) { this.id = id; this.name = name; } public UUID getId() { return id; } public String getName() { return name; } } }
package com.sokolov.lang.java.parameter; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ListOfParametersFromString implements IListOfParameters { private final String listOfParams; public ListOfParametersFromString(String listOfParams) { this.listOfParams = listOfParams; } @Override public List<IParameter> asList() { if (listOfParams.isEmpty()) { return Collections.emptyList(); } String[] params; if (listOfParams.contains("<")) { params = getParamsWithGenerics(); } else { params = listOfParams.split(","); } List<IParameter> result = new ArrayList<>(); for (String param : params) { result.add(new ParameterFromString(param)); } return result; } private String[] getParamsWithGenerics() { char[] chars = listOfParams.toCharArray(); List<String> result = new ArrayList<>(); StringBuilder sb = new StringBuilder(); int rubinCount = 0; for (char c : chars) { if (rubinCount == 0 && c == ',') { result.add(sb.toString()); sb = new StringBuilder(); } else if (c == '<') { rubinCount++; sb.append(c); } else if (c == '>') { rubinCount--; sb.append(c); } else { sb.append(c); } } result.add(sb.toString()); return result.toArray(new String[0]); } }
/* * 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.test.context; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.AbstractSpringBootTestWebServerWebEnvironmentTests.AbstractConfig; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.SpringBootTestWebEnvironmentContextHierarchyTests.ChildConfiguration; import org.springframework.boot.test.context.SpringBootTestWebEnvironmentContextHierarchyTests.ParentConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SpringBootTest} configured with {@link WebEnvironment#DEFINED_PORT}. * * @author Phillip Webb * @author Andy Wilkinson */ @RunWith(SpringRunner.class) @DirtiesContext @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT, properties = {"server.port=0", "value=123"}) @ContextHierarchy({@ContextConfiguration(classes = ParentConfiguration.class), @ContextConfiguration(classes = ChildConfiguration.class)}) public class SpringBootTestWebEnvironmentContextHierarchyTests { @Autowired private ApplicationContext context; @Test public void testShouldOnlyStartSingleServer() { ApplicationContext parent = this.context.getParent(); assertThat(this.context).isInstanceOf(WebApplicationContext.class); assertThat(parent).isNotInstanceOf(WebApplicationContext.class); } @Configuration protected static class ParentConfiguration extends AbstractConfig { } @Configuration @EnableWebMvc @RestController protected static class ChildConfiguration extends AbstractConfig { } }
/* * 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.geode.internal.protocol.protobuf.v1.state; import org.apache.geode.internal.protocol.protobuf.v1.BasicTypes; import org.apache.geode.internal.protocol.protobuf.v1.ProtobufOperationContext; import org.apache.geode.internal.protocol.protobuf.v1.state.exception.ConnectionStateException; public class InvalidSecurity implements ConnectionState { @Override public void validateOperation(ProtobufOperationContext operationContext) throws ConnectionStateException { throw new ConnectionStateException(BasicTypes.ErrorCode.AUTHENTICATION_FAILED, "Attempting to authenticate incoming protobuf message using legacy security implementation. This is not supported. Failing authentication."); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package infrastructure; import labapi.FederationProvider; import labapi.LabConstants; import labapi.User; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.concurrent.TimeUnit; public class SeleniumExtensions { private final static Logger LOG = LoggerFactory.getLogger(SeleniumExtensions.class); private SeleniumExtensions() { } public static WebDriver createDefaultWebDriver() { ChromeOptions options = new ChromeOptions(); //no visual rendering, remove when debugging options.addArguments("--headless"); System.setProperty("webdriver.chrome.driver", "C:/Windows/chromedriver.exe"); ChromeDriver driver = new ChromeDriver(options); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); return driver; } public static WebElement waitForElementToBeVisibleAndEnable(WebDriver driver, By by, int timeOutInSeconds) { WebDriverWait webDriverWait = new WebDriverWait(driver, timeOutInSeconds); return webDriverWait.until((dr) -> { try { WebElement elementToBeDisplayed = driver.findElement(by); if (elementToBeDisplayed.isDisplayed() && elementToBeDisplayed.isEnabled()) { return elementToBeDisplayed; } return null; } catch (StaleElementReferenceException e) { return null; } }); } public static WebElement waitForElementToBeVisibleAndEnable(WebDriver driver, By by) { int DEFAULT_TIMEOUT_IN_SEC = 15; return waitForElementToBeVisibleAndEnable(driver, by, DEFAULT_TIMEOUT_IN_SEC); } public static void performADLogin(WebDriver driver, User user) { LOG.info("PerformADLogin"); UserInformationFields fields = new UserInformationFields(user); LOG.info("Loggin in ... Entering username"); driver.findElement(new By.ById(fields.getAadUserNameInputId())).sendKeys(user.getUpn()); LOG.info("Loggin in ... Clicking <Next> after username"); driver.findElement(new By.ById(fields.getAadSignInButtonId())).click(); if (user.getFederationProvider() == FederationProvider.ADFS_2 && !user.getLabName().equals(LabConstants.ARLINGTON_LAB_NAME)) { LOG.info("Loggin in ... ADFS-V2 - Entering the username in ADFSv2 form"); driver.findElement(new By.ById(SeleniumConstants.ADFSV2_WEB_USERNAME_INPUT_ID)). sendKeys(user.getUpn()); } LOG.info("Loggin in ... Entering password"); By by = new By.ById(fields.getPasswordInputId()); waitForElementToBeVisibleAndEnable(driver, by).sendKeys(user.getPassword()); LOG.info("Loggin in ... click submit"); waitForElementToBeVisibleAndEnable(driver, new By.ById(fields.getPasswordSigInButtonId())). click(); try { checkAuthenticationCompletePage(driver); return; } catch (TimeoutException ex) { } LOG.info("Checking optional questions"); try { LOG.info("Are you trying to sign in to ... ? checking"); waitForElementToBeVisibleAndEnable(driver, new By.ById(SeleniumConstants.ARE_YOU_TRYING_TO_SIGN_IN_TO), 3). click(); LOG.info("Are you trying to sign in to ... ? click Continue"); } catch (TimeoutException ex) { } try { LOG.info("Stay signed in? checking"); waitForElementToBeVisibleAndEnable(driver, new By.ById(SeleniumConstants.STAY_SIGN_IN_NO_BUTTON_ID), 3). click(); LOG.info("Stay signed in? click NO"); } catch (TimeoutException ex) { } } private static void checkAuthenticationCompletePage(WebDriver driver) { (new WebDriverWait(driver, 5)).until((ExpectedCondition<Boolean>) d -> { boolean condition = false; WebElement we = d.findElement(new By.ByTagName("body")); if (we != null && we.getText().contains("Authentication complete")) { condition = true; } return condition; }); } public static void performADFS2019Login(WebDriver driver, User user) { LOG.info("PerformADFS2019Login"); UserInformationFields fields = new UserInformationFields(user); LOG.info("Loggin in ... Entering username"); driver.findElement(new By.ById(fields.getADFS2019UserNameInputId())).sendKeys(user.getUpn()); LOG.info("Loggin in ... Entering password"); By by = new By.ById(fields.getPasswordInputId()); waitForElementToBeVisibleAndEnable(driver, by).sendKeys(user.getPassword()); LOG.info("Loggin in ... click submit"); waitForElementToBeVisibleAndEnable(driver, new By.ById(fields.getPasswordSigInButtonId())). click(); } public static void performLocalLogin(WebDriver driver, User user) { LOG.info("PerformLocalLogin"); driver.findElement(new By.ById(SeleniumConstants.B2C_LOCAL_ACCOUNT_ID)).click(); LOG.info("Loggin in ... Entering username"); driver.findElement(new By.ById(SeleniumConstants.B2C_LOCAL_USERNAME_ID)).sendKeys(user.getUpn()); LOG.info("Loggin in ... Entering password"); By by = new By.ById(SeleniumConstants.B2C_LOCAL_PASSWORD_ID); waitForElementToBeVisibleAndEnable(driver, by).sendKeys(user.getPassword()); waitForElementToBeVisibleAndEnable(driver, new By.ById(SeleniumConstants.B2C_LOCAL_SIGN_IN_BUTTON_ID)). click(); } public static void performGoogleLogin(WebDriver driver, User user) { LOG.info("PerformGoogleLogin"); driver.findElement(new By.ById(SeleniumConstants.GOOGLE_ACCOUNT_ID)).click(); LOG.info("Loggin in ... Entering username"); driver.findElement(new By.ById(SeleniumConstants.GOOGLE_USERNAME_ID)).sendKeys(user.getUpn()); LOG.info("Loggin in ... Clicking <Next> after username"); driver.findElement(new By.ById(SeleniumConstants.GOOGLE_NEXT_AFTER_USERNAME_BUTTON)).click(); LOG.info("Loggin in ... Entering password"); By by = new By.ByName(SeleniumConstants.GOOGLE_PASSWORD_ID); waitForElementToBeVisibleAndEnable(driver, by).sendKeys(user.getPassword()); LOG.info("Loggin in ... click submit"); waitForElementToBeVisibleAndEnable(driver, new By.ById(SeleniumConstants.GOOGLE_NEXT_BUTTON_ID)).click(); } public static void performFacebookLogin(WebDriver driver, User user) { LOG.info("PerformFacebookLogin"); driver.findElement(new By.ById(SeleniumConstants.FACEBOOK_ACCOUNT_ID)).click(); LOG.info("Loggin in ... Entering username"); driver.findElement(new By.ById(SeleniumConstants.FACEBOOK_USERNAME_ID)).sendKeys(user.getUpn()); LOG.info("Loggin in ... Entering password"); By by = new By.ById(SeleniumConstants.FACEBOOK_PASSWORD_ID); waitForElementToBeVisibleAndEnable(driver, by).sendKeys(user.getPassword()); waitForElementToBeVisibleAndEnable(driver, new By.ById(SeleniumConstants.FACEBOOK_LOGIN_BUTTON_ID)). click(); } public static void takeScreenShot(WebDriver driver) { String file = System.getenv("BUILD_STAGINGDIRECTORY"); File destination = new File(file + "" + "/SeleniumError.png"); File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(scrFile, destination); LOG.info("Screenshot can be found at: " + destination.getPath()); } catch (Exception exception) { LOG.error("Error taking screenshot: " + exception.getMessage()); } } }
package com.wang.httpparam; import java.lang.annotation.*; /** * Created on 2019/6/28. * Author: bigwang * Description:返回 MultipartBody.Builder */ @Documented @Target({ElementType.TYPE}) @Retention(RetentionPolicy.CLASS) public @interface Body { /** * 方法名称 * @return 名称 */ String name() default "getBody"; /** * 是否替换原有存在相同名称的方法 * @return true 替换 */ boolean replace() default false; /** * 是否需要父类方法返回参数加入到请求体 * @return true 不需要 */ boolean root() default false; }
/* * Licensed to ElasticSearch and Shay Banon 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.index.analysis; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.ngram.NGramTokenizer; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.assistedinject.Assisted; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.Index; import org.elasticsearch.index.settings.IndexSettings; import java.io.Reader; /** * */ public class NGramTokenizerFactory extends AbstractTokenizerFactory { private final int minGram; private final int maxGram; @Inject public NGramTokenizerFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); this.minGram = settings.getAsInt("min_gram", NGramTokenizer.DEFAULT_MIN_NGRAM_SIZE); this.maxGram = settings.getAsInt("max_gram", NGramTokenizer.DEFAULT_MAX_NGRAM_SIZE); } @Override public Tokenizer create(Reader reader) { return new NGramTokenizer(reader, minGram, maxGram); } }
/* Copyright 2020 The Kubernetes 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.kubernetes.client; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.AnythingPattern; import io.kubernetes.client.openapi.ApiClient; import io.kubernetes.client.openapi.ApiException; import io.kubernetes.client.openapi.models.V1ObjectMeta; import io.kubernetes.client.openapi.models.V1Pod; import io.kubernetes.client.util.ClientBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /** Tests for the Copy helper class */ public class CopyTest { private String namespace; private String podName; private String[] cmd; private ApiClient client; private static final int PORT = 8089; @Rule public WireMockRule wireMockRule = new WireMockRule(PORT); @Before public void setup() throws IOException { client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build(); namespace = "default"; podName = "apod"; } @Test public void testUrl() throws IOException, ApiException, InterruptedException { Copy copy = new Copy(client); V1Pod pod = new V1Pod().metadata(new V1ObjectMeta().name(podName).namespace(namespace)); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); Thread t = new Thread( new Runnable() { @Override public void run() { try { InputStream is = copy.copyFileFromPod(pod, "container", "/some/path/to/file"); } catch (IOException | ApiException e) { e.printStackTrace(); } } }); t.start(); Thread.sleep(2000); t.interrupt(); verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .withQueryParam("stdin", equalTo("false")) .withQueryParam("stdout", equalTo("true")) .withQueryParam("stderr", equalTo("true")) .withQueryParam("tty", equalTo("false")) .withQueryParam("command", new AnythingPattern())); } @Test public void testCopyFileToPod() throws IOException, ApiException, InterruptedException { File testFile = File.createTempFile("testfile", null); testFile.deleteOnExit(); Copy copy = new Copy(client); wireMockRule.stubFor( get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); // When attempting to write to the process outputstream in copyFileToPod, the // WebSocketStreamHandler is in a wait state because no websocket is created by mock, which // blocks the main thread. So here we execute the method in a thread. Thread t = new Thread( new Runnable() { public void run() { try { copy.copyFileToPod( namespace, podName, "", testFile.toPath(), Paths.get("/copied-testfile")); } catch (IOException | ApiException ex) { ex.printStackTrace(); } } }); t.start(); Thread.sleep(2000); t.interrupt(); verify( getRequestedFor( urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec")) .withQueryParam("stdin", equalTo("true")) .withQueryParam("stdout", equalTo("true")) .withQueryParam("stderr", equalTo("true")) .withQueryParam("tty", equalTo("false")) .withQueryParam("command", equalTo("sh")) .withQueryParam("command", equalTo("-c")) .withQueryParam("command", equalTo("base64 -d | tar -xmf - -C /"))); } }
package edu.servicios.util; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Mail { private static Properties mailServerProperties; private static Session getMailSession; private static MimeMessage generateMailMessage; private static final String host = "smtp.gmail.com"; private static final String user = "gaha.uefgs.duran@gmail.com"; private static final String password = "adminGAHA2016"; public static void generateAndSendEmail(String lAsunto, String lCuerpo, String copia, String ... lListaEmails) throws AddressException, MessagingException, UnsupportedEncodingException { // Step1 System.out.println("\n1st ===> setup Mail Server Properties.."); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.port", "587"); mailServerProperties.put("mail.smtp.auth", "true"); mailServerProperties.put("mail.smtp.starttls.enable", "true"); System.out.println("Mail Server Properties have been setup successfully.."); // Step2 System.out.println("\n2nd ===> get Mail Session.."); getMailSession = Session.getDefaultInstance(mailServerProperties, null); generateMailMessage = new MimeMessage(getMailSession); InternetAddress[] toAddress = new InternetAddress[lListaEmails.length]; // To get the array of addresses for( int i=0; i < lListaEmails.length; i++ ) { // changed from a while loop toAddress[i] = new InternetAddress(lListaEmails[i]); } for( int i=0; i < toAddress.length; i++) { // changed from a while loop generateMailMessage.addRecipient(Message.RecipientType.TO, toAddress[i]); } //generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(para)); generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(copia)); generateMailMessage.setFrom(new InternetAddress(user, "Unidad Educativa Federico González Suarez")); generateMailMessage.setSubject(lAsunto); String emailBody = lCuerpo; generateMailMessage.setContent(emailBody, "text/html"); System.out.println("Mail Session has been created successfully.."); // Step3 System.out.println("\n3rd ===> Get Session and Send mail"); Transport transport = getMailSession.getTransport("smtp"); // Enter your correct gmail UserID and Password // if you have 2FA enabled then provide App Specific Password a esto me refiero transport.connect(host, user, password); transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients()); transport.close(); } public static void main(String args[]) throws AddressException, MessagingException { try { generateAndSendEmail("Generación de Horarios terminada", "<p style='color:#00008B;'>Estimado admin,</p><br><p style='color:#00008B;text-align:justify;'>El proceso de generación automática de horarios ha finalizado satisfactoriamente. Favor dirigirse al sistema para visualizar la información correspondiente.</p>", "duberjesus@gmail.com", "jeanca93@gmail.com"); System.out.println("\n===> Your Java Program has just sent an Email successfully. Check your email.."); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/* * Copyright 2014 Source Auditor Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.spdx.maven; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.maven.model.License; import org.apache.maven.plugin.logging.Log; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.spdx.rdfparser.InvalidSPDXAnalysisException; import org.spdx.rdfparser.SpdxRdfConstants; import org.spdx.rdfparser.license.AnyLicenseInfo; import org.spdx.rdfparser.license.ConjunctiveLicenseSet; import org.spdx.rdfparser.license.LicenseInfoFactory; import org.spdx.rdfparser.license.SpdxListedLicense; import org.spdx.rdfparser.license.SpdxNoAssertionLicense; /** * Singleton class which maps Maven license objects to SPDX licenses. * <p> * The license mapping uses the JSON file from the spdx.org/licenses/licenses.json file * <p> * If the site spdx.org/licenses is not accessible, then static version of the file will be used * <p> * The seeAlso property of the SPDX file is matched to the Maven license URL. * * @author Gary O'Neall */ public class MavenToSpdxLicenseMapper { private static final String SPDX_LICENSE_URL_PREFIX = "https://spdx.org/licenses/"; private static final String LISTED_LICENSE_JSON_URL = SPDX_LICENSE_URL_PREFIX + "licenses.json"; private static final String LISTED_LICENSE_JSON_PATH = "resources/licenses.json"; static MavenToSpdxLicenseMapper instance; private Map<String, String> urlStringToSpdxLicenseId; private MavenToSpdxLicenseMapper( Log log ) throws LicenseMapperException { // Can not instantiate directly - singleton class InputStream is = null; try { URL listedLicenseJsonUrl = new URL( LISTED_LICENSE_JSON_URL ); is = listedLicenseJsonUrl.openStream(); } catch ( MalformedURLException e ) { if ( log != null ) { log.warn( "Invalid JSON URL for SPDX listed licenses. Using cached version" ); } } catch ( IOException e ) { if ( log != null ) { log.warn( "IO Exception opening web page for JSON for SPDX listed licenses. Using cached version" ); } } if ( is == null ) { // use the cached version is = LicenseManager.class.getClassLoader().getResourceAsStream( LISTED_LICENSE_JSON_PATH ); } InputStreamReader reader = new InputStreamReader( is ); try { initializeUrlMap( reader, log ); } finally { try { reader.close(); } catch ( IOException e ) { if ( log != null ) { log.warn( "IO error closing listed license reader: " + e.getMessage() ); } } } } public static MavenToSpdxLicenseMapper getInstance( Log log ) throws LicenseMapperException { if ( instance == null ) { instance = new MavenToSpdxLicenseMapper( log ); } return instance; } /** * @param url URL string for a license * @return SPDX ID associated with the URL */ public String urlToSpdxId( String url ) { return this.urlStringToSpdxLicenseId.get( url ); } /** * Initialize the urlSTringToSpdxLicense map with the SPDX listed licenses * * @param jsonReader Reader for the JSON input file containing the listed licenses * @param log Optional logger * @throws LicenseMapperException */ private void initializeUrlMap( Reader jsonReader, Log log ) throws LicenseMapperException { JSONParser parser = new JSONParser(); Object parsedObject = null; try { parsedObject = parser.parse( jsonReader ); } catch ( IOException e1 ) { if ( log != null ) { log.error( "I/O error parsing listed licenses JSON file: " + e1.getMessage() ); } throw ( new LicenseMapperException( "I/O Error parsing listed licenses" ) ); } catch ( ParseException e1 ) { if ( log != null ) { log.error( "JSON parsing error parsing listed licenses JSON file: " + e1.getMessage() ); } throw ( new LicenseMapperException( "JSON parsing error parsing listed licenses" ) ); } JSONObject listedLicenseSource = (JSONObject) parsedObject; JSONArray listedLicenses = (JSONArray) listedLicenseSource.get( "licenses" ); urlStringToSpdxLicenseId = new HashMap<>(); List<String> urlsWithMultipleIds = new ArrayList<>(); for ( Object _listedLicense : listedLicenses ) { JSONObject listedLicense = (JSONObject) _listedLicense; String licenseId = (String) listedLicense.get( SpdxRdfConstants.PROP_LICENSE_ID ); this.urlStringToSpdxLicenseId.put( SPDX_LICENSE_URL_PREFIX + licenseId, licenseId ); JSONArray urls = (JSONArray) listedLicense.get( SpdxRdfConstants.RDFS_PROP_SEE_ALSO ); if ( urls != null ) { for ( Object o : urls ) { String url = (String) o; url = url.replaceAll( "https", "http" ); if ( this.urlStringToSpdxLicenseId.containsKey( url ) ) { urlsWithMultipleIds.add( url ); } else { this.urlStringToSpdxLicenseId.put( url, licenseId ); } } } } // Remove any mappings which have ambiguous URL mappings for ( String redundantUrl : urlsWithMultipleIds ) { this.urlStringToSpdxLicenseId.remove( redundantUrl ); } addManualMappings(); } /** * This is a bit of an override on the official SPDX license list Add some specific URL mappings that are commonly * used in SPDX files */ private void addManualMappings() { // TODO: Request these be added to the SPDX license list and remove once they // have been added this.urlStringToSpdxLicenseId.put( "http://www.apache.org/licenses/LICENSE-2.0.txt", "Apache-2.0" ); this.urlStringToSpdxLicenseId.put( "http://www.opensource.org/licenses/cpl1.0.txt", "CPL-1.0" ); this.urlStringToSpdxLicenseId.put( "http://www.opensource.org/licenses/mit-license.php", "MIT" ); // The following is in the listed licenses, but is duplicated in multiple SPDX license ID's // adding it back for the license it was originally targeted for this.urlStringToSpdxLicenseId.put( "http://www.mozilla.org/MPL/MPL-1.0.txt", "MPL-1.0" ); } /** * Map a list of Maven licenses to an SPDX license. If no licenses are supplied, SpdxNoAssertion license is * returned. if a single license is supplied, and a URL can be found matching a listed license, the listed license * is returned. if a single license is supplied, and a URL can not be found matching a listed license, * SpdxNoAssertion is returned. If multiple licenses are supplied, a conjunctive license is returned containing all * mapped SPDX licenses. * * @return * @throws LicenseManagerException */ public AnyLicenseInfo mavenLicenseListToSpdxLicense( List<License> licenseList ) { if ( licenseList == null ) { return new SpdxNoAssertionLicense(); } List<AnyLicenseInfo> spdxLicenses = new ArrayList<>(); for ( License license : licenseList ) { SpdxListedLicense listedLicense = mavenLicenseToSpdxListedLicense( license ); if ( listedLicense != null ) { spdxLicenses.add( listedLicense ); } } if ( spdxLicenses.size() < 1 ) { return new SpdxNoAssertionLicense(); } else if ( spdxLicenses.size() == 1 ) { return spdxLicenses.get( 0 ); } else { AnyLicenseInfo[] licensesInSet = spdxLicenses.toArray( new AnyLicenseInfo[0] ); AnyLicenseInfo conjunctiveLicense = new ConjunctiveLicenseSet( licensesInSet ); return conjunctiveLicense; } } private SpdxListedLicense mavenLicenseToSpdxListedLicense( License license ) { if ( license == null ) { return null; } if ( license.getUrl() == null || license.getUrl().isEmpty() ) { return null; } String spdxId = this.urlStringToSpdxLicenseId.get( license.getUrl().replaceAll( "https", "http" ) ); if ( spdxId == null ) { return null; } try { return LicenseInfoFactory.getListedLicenseById( spdxId ); } catch ( InvalidSPDXAnalysisException e ) { return null; } } /** * @return Map of URL's to listed license ID's */ public Map<String, String> getMap() { return this.urlStringToSpdxLicenseId; } }
package test.com.wirelust.personalapi.api; import javax.inject.Inject; import javax.ws.rs.core.Response; import com.wirelust.personalapi.api.providers.GeneralExceptionMapperProvider; import com.wirelust.personalapi.api.v1.representations.ApiErrorType; import com.wirelust.personalapi.api.v1.representations.EnumErrorCode; import com.wirelust.personalapi.producers.ResourceBundleProducer; import org.jglue.cdiunit.AdditionalClasses; import org.jglue.cdiunit.CdiRunner; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Date: 01-Jun-2016 * * @author T. Curran */ @RunWith(CdiRunner.class) @AdditionalClasses(ResourceBundleProducer.class) public class GeneralExceptionMapperProviderTest { @Inject GeneralExceptionMapperProvider generalExceptionMapperProvider; @Test public void shouldBeAbleToMapException() { Exception exception = new Exception("test exception"); Response response = generalExceptionMapperProvider.toResponse(exception); Assert.assertEquals(EnumErrorCode.GENERIC_ERROR.responseStatus().getStatusCode(), response.getStatus()); Assert.assertTrue(response.getEntity() instanceof ApiErrorType); if (response.getEntity() instanceof ApiErrorType) { ApiErrorType apiError = (ApiErrorType)response.getEntity(); Assert.assertEquals("Generic error", apiError.getText()); } } }
package com.Jeka8833.EasyPacketTCP.listener; import com.Jeka8833.EasyPacketTCP.server.ServerUser; public interface ServerUserJoinListener { void userJoin(final ServerUser user); }
/* * 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.directconnect.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.directconnect.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * LagMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class LagMarshaller { private static final MarshallingInfo<String> CONNECTIONSBANDWIDTH_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("connectionsBandwidth").build(); private static final MarshallingInfo<Integer> NUMBEROFCONNECTIONS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("numberOfConnections").build(); private static final MarshallingInfo<String> LAGID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("lagId").build(); private static final MarshallingInfo<String> OWNERACCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ownerAccount").build(); private static final MarshallingInfo<String> LAGNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("lagName").build(); private static final MarshallingInfo<String> LAGSTATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("lagState").build(); private static final MarshallingInfo<String> LOCATION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("location").build(); private static final MarshallingInfo<String> REGION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("region").build(); private static final MarshallingInfo<Integer> MINIMUMLINKS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("minimumLinks").build(); private static final MarshallingInfo<String> AWSDEVICE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("awsDevice").build(); private static final MarshallingInfo<String> AWSDEVICEV2_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("awsDeviceV2").build(); private static final MarshallingInfo<String> AWSLOGICALDEVICEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("awsLogicalDeviceId").build(); private static final MarshallingInfo<List> CONNECTIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("connections").build(); private static final MarshallingInfo<Boolean> ALLOWSHOSTEDCONNECTIONS_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("allowsHostedConnections").build(); private static final MarshallingInfo<Boolean> JUMBOFRAMECAPABLE_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("jumboFrameCapable").build(); private static final MarshallingInfo<String> HASLOGICALREDUNDANCY_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("hasLogicalRedundancy").build(); private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("tags").build(); private static final MarshallingInfo<String> PROVIDERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("providerName").build(); private static final MarshallingInfo<Boolean> MACSECCAPABLE_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("macSecCapable").build(); private static final MarshallingInfo<String> ENCRYPTIONMODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("encryptionMode").build(); private static final MarshallingInfo<List> MACSECKEYS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("macSecKeys").build(); private static final LagMarshaller instance = new LagMarshaller(); public static LagMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Lag lag, ProtocolMarshaller protocolMarshaller) { if (lag == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(lag.getConnectionsBandwidth(), CONNECTIONSBANDWIDTH_BINDING); protocolMarshaller.marshall(lag.getNumberOfConnections(), NUMBEROFCONNECTIONS_BINDING); protocolMarshaller.marshall(lag.getLagId(), LAGID_BINDING); protocolMarshaller.marshall(lag.getOwnerAccount(), OWNERACCOUNT_BINDING); protocolMarshaller.marshall(lag.getLagName(), LAGNAME_BINDING); protocolMarshaller.marshall(lag.getLagState(), LAGSTATE_BINDING); protocolMarshaller.marshall(lag.getLocation(), LOCATION_BINDING); protocolMarshaller.marshall(lag.getRegion(), REGION_BINDING); protocolMarshaller.marshall(lag.getMinimumLinks(), MINIMUMLINKS_BINDING); protocolMarshaller.marshall(lag.getAwsDevice(), AWSDEVICE_BINDING); protocolMarshaller.marshall(lag.getAwsDeviceV2(), AWSDEVICEV2_BINDING); protocolMarshaller.marshall(lag.getAwsLogicalDeviceId(), AWSLOGICALDEVICEID_BINDING); protocolMarshaller.marshall(lag.getConnections(), CONNECTIONS_BINDING); protocolMarshaller.marshall(lag.getAllowsHostedConnections(), ALLOWSHOSTEDCONNECTIONS_BINDING); protocolMarshaller.marshall(lag.getJumboFrameCapable(), JUMBOFRAMECAPABLE_BINDING); protocolMarshaller.marshall(lag.getHasLogicalRedundancy(), HASLOGICALREDUNDANCY_BINDING); protocolMarshaller.marshall(lag.getTags(), TAGS_BINDING); protocolMarshaller.marshall(lag.getProviderName(), PROVIDERNAME_BINDING); protocolMarshaller.marshall(lag.getMacSecCapable(), MACSECCAPABLE_BINDING); protocolMarshaller.marshall(lag.getEncryptionMode(), ENCRYPTIONMODE_BINDING); protocolMarshaller.marshall(lag.getMacSecKeys(), MACSECKEYS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
package com.sierisimo.introduction.ifelse; import java.util.Scanner; /** * Created by sierisimo on 14/01/16. */ public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String ans = ""; if (n % 2 == 1) ans = "Weird"; else { if (n >= 2 && n <= 5) ans = "Not Weird"; else if (n >= 6 && n <= 20) ans = "Weird"; else if (n > 20) ans = "Not Weird"; } System.out.println(ans); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.eas.window; import com.eas.core.XElement; import com.eas.window.events.ActivateEvent; import com.eas.window.events.ActivateHandler; import com.eas.window.events.BeforeCloseEvent; import com.eas.window.events.BeforeCloseHandler; import com.eas.window.events.ClosedEvent; import com.eas.window.events.ClosedHandler; import com.eas.window.events.DeactivateEvent; import com.eas.window.events.DeactivateHandler; import com.eas.window.events.MaximizeEvent; import com.eas.window.events.MaximizeHandler; import com.eas.window.events.MinimizeEvent; import com.eas.window.events.MinimizeHandler; import com.eas.window.events.MoveEvent; import com.eas.window.events.MoveHandler; import com.eas.window.events.RestoreEvent; import com.eas.window.events.RestoreHandler; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.event.dom.client.MouseDownHandler; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseMoveHandler; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseUpHandler; import com.google.gwt.event.logical.shared.OpenEvent; import com.google.gwt.event.logical.shared.OpenHandler; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasAnimation; import com.google.gwt.user.client.ui.HasHTML; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.dom.client.Document; /** * * @author mg */ public class WindowPanel extends DraggablePanel implements WindowUI, HasAnimation { protected static final String ACTIVE_SUFFIX_NAMNE = "active"; public static class Caption extends HTML { public Caption(String aHtml) { super(); setHTML(aHtml); setStyleName("window-caption"); } } protected Widget captionWidget; protected VerticalPanel verticalPanel; protected JavaScriptObject transitionOnResizer; protected Widget verticalPanelContent; protected boolean animationEnabled = true; protected boolean movable = true; protected boolean maximized; protected boolean minimized; protected boolean active; protected boolean maximizable = true; protected boolean minimizable = true; protected boolean closable = true; public WindowPanel() { super(true); addDomHandler(new MouseDownHandler() { @Override public void onMouseDown(MouseDownEvent event) { focus(); } }, MouseDownEvent.getType()); verticalPanel = new VerticalPanel(); super.setWidget(verticalPanel); setCaptionWidget(new Caption("")); setUndecorated(false); getElement().addClassName("window-panel"); getElement().<XElement> cast().addResizingTransitionEnd(this); getMovableTarget().getElement().<XElement> cast().addResizingTransitionEnd(this); } @Override public HasHTML getCaptionWidget() { if (captionWidget instanceof HasHTML) { return (HasHTML) captionWidget; } else { return null; } } protected HandlerRegistration mdHandler; protected HandlerRegistration muHandler; protected HandlerRegistration mmHandler; protected int mouseScreenX; protected int mouseScreenY; protected int targetScrollLeft; protected int targetScrollTop; protected boolean dragged; @Override public final void setCaptionWidget(HasHTML aCaptionWidget) { if (captionWidget != aCaptionWidget) { if (captionWidget != null) { captionWidget.removeFromParent(); } if (mdHandler != null) { mdHandler.removeHandler(); } if (muHandler != null) { muHandler.removeHandler(); } if (mmHandler != null) { mmHandler.removeHandler(); } if (aCaptionWidget instanceof Widget) { captionWidget = (Widget) aCaptionWidget; } else { captionWidget = new Caption(aCaptionWidget.getHTML()); } if (captionWidget != null) { mdHandler = captionWidget.addDomHandler(new MouseDownHandler() { @Override public void onMouseDown(MouseDownEvent event) { event.preventDefault(); event.stopPropagation(); focus(); if (movable && !maximized) { DOM.setCapture(captionWidget.getElement()); mouseScreenX = event.getScreenX(); mouseScreenY = event.getScreenY(); String tLeft = getMovableTarget().getElement().getStyle().getLeft(); targetScrollLeft = Integer.parseInt(tLeft.substring(0, tLeft.length() - 2)); String tTop = getMovableTarget().getElement().getStyle().getTop(); targetScrollTop = Integer.parseInt(tTop.substring(0, tTop.length() - 2)); } } }, MouseDownEvent.getType()); muHandler = captionWidget.addDomHandler(new MouseUpHandler() { @Override public void onMouseUp(MouseUpEvent event) { dragged = false; event.preventDefault(); event.stopPropagation(); if (movable && !maximized) { DOM.releaseCapture(captionWidget.getElement()); endMoving(); } } }, MouseUpEvent.getType()); mmHandler = captionWidget.addDomHandler(new MouseMoveHandler() { @Override public void onMouseMove(MouseMoveEvent event) { if (movable && !maximized) { if (DOM.getCaptureElement() == captionWidget.getElement()) { event.preventDefault(); event.stopPropagation(); int dx = event.getScreenX() - mouseScreenX; int dy = event.getScreenY() - mouseScreenY; if (!dragged && (dx != 0 || dy != 0)) { dragged = true; beginMoving(); } setPosition(targetScrollLeft + dx >= 0 ? targetScrollLeft + dx : 0, targetScrollTop + dy >= 0 ? targetScrollTop + dy : 0); } } } }, MouseMoveEvent.getType()); verticalPanel.insert(captionWidget, 0); } } } @Override protected void decorate() { super.decorate(); content.setStyleName("content-decor"); if (isActive()) { content.addStyleDependentName(ACTIVE_SUFFIX_NAMNE); } else { content.removeStyleDependentName(ACTIVE_SUFFIX_NAMNE); } if (captionWidget != null) { captionWidget.getElement().getStyle().clearDisplay(); } } @Override protected void undecorate() { super.undecorate(); content.getElement().removeClassName("content-decor"); content.getElement().removeClassName("content-decor-active"); if (captionWidget != null) { captionWidget.getElement().getStyle().setDisplay(Style.Display.NONE); } } @Override public void setWidget(Widget w) { if (verticalPanelContent != null) { verticalPanelContent.getElement().<XElement> cast().removeTransitionEndListener(transitionOnResizer); verticalPanelContent.getElement().removeClassName("window-content"); verticalPanelContent.removeFromParent(); } verticalPanelContent = w; if (verticalPanelContent != null) { transitionOnResizer = verticalPanelContent.getElement().<XElement> cast().addResizingTransitionEnd(this); verticalPanel.add(verticalPanelContent); verticalPanelContent.getElement().addClassName("window-content"); } if (isAttached()) { onResize(); } } @Override public Widget getWidget() { return verticalPanelContent; } @Override protected boolean isNresizable() { return resizable && !maximized && !minimized; } @Override protected boolean isSresizable() { return resizable && !maximized && !minimized; } @Override protected boolean isWresizable() { return resizable && !maximized; } @Override protected boolean isEresizable() { return resizable && !maximized; } @Override public boolean isMinimized() { return minimized; } @Override public boolean isMaximized() { return maximized; } @Override public boolean isMinimizable() { return minimizable; } @Override public void setMinimizable(boolean minimizable) { this.minimizable = minimizable; } @Override public void setClosable(boolean closable) { this.closable = closable; } @Override public boolean isClosable() { return closable; } @Override public boolean isMaximizable() { return maximizable; } @Override public void setMaximizable(boolean maximizable) { this.maximizable = maximizable; } @Override public void maximize() { if (!maximized) { restoreSnapshot(); maximized = true; updateDecorCursors(); snapshotMetrics(); // editing Element movableElement = getMovableTarget().getElement(); Style targetStyle = getWidget().getElement().getStyle(); // content int leftInset = getWidget().getElement().getAbsoluteLeft() - movableElement.getAbsoluteLeft(); int rightInset = movableElement.getAbsoluteRight() - getWidget().getElement().getAbsoluteRight(); int hInsets = leftInset + rightInset; int topInset = getWidget().getElement().getAbsoluteTop() - movableElement.getAbsoluteTop(); int bottomInset = movableElement.getAbsoluteBottom() - getWidget().getElement().getAbsoluteBottom(); int vInsets = topInset + bottomInset; Element parentElement = getMovableTarget().getParent().getElement(); int parentScrollWidth = parentElement.getScrollWidth(); int parentScrollHeight; if (parentElement == Document.get().getBody())// Some browsers // return incorrect // height for body // element { parentScrollHeight = Document.get().getClientHeight(); } else { parentScrollHeight = parentElement.getScrollHeight(); } targetStyle.setWidth(parentScrollWidth - hInsets, Style.Unit.PX); targetStyle.setHeight(parentScrollHeight - vInsets, Style.Unit.PX); // editing targetStyle = movableElement.getStyle(); // window targetStyle.setLeft(0, Style.Unit.PX); targetStyle.setTop(0, Style.Unit.PX); onResize(); MaximizeEvent.<WindowUI> fire(this, this); } } @Override public void setPosition(double aLeft, double aTop) { super.setPosition(aLeft, aTop); MoveEvent.fire(this, this, aLeft, aTop); } @Override public void setSize(double aWidth, double aHeight) { super.setSize(aWidth, aHeight); ResizeEvent.<WindowPanel> fire(this, (int) aWidth, (int) aHeight); } private void snapshotMetrics() throws NumberFormatException { // measurement Style targetStyle = getWidget().getElement().getStyle(); // content String sHeight = targetStyle.getHeight(); contentHeightToRestore = Double.parseDouble(sHeight.substring(0, sHeight.length() - 2)); String sWidth = targetStyle.getWidth(); contentWidthToRestore = Double.parseDouble(sWidth.substring(0, sWidth.length() - 2)); targetStyle = getMovableTarget().getElement().getStyle(); // window String sLeft = targetStyle.getLeft(); leftToRestore = Double.parseDouble(sLeft.substring(0, sLeft.length() - 2)); String sTop = targetStyle.getTop(); topToRestore = Double.parseDouble(sTop.substring(0, sTop.length() - 2)); } protected boolean preMinimizedStateMaximized; protected boolean preMinimzedStateNormal; /** * Minimizes the window. Minimize here is setting zero as height. * Descendants may decide to do something else. minimize does a snapshot of * all window's metrics. So subsequent restore or restoreSnapshot calls will * lead to correct restoration of the window. */ @Override public void minimize() { if (!minimized) { preMinimizedStateMaximized = maximized; preMinimzedStateNormal = !maximized && !minimized; restoreSnapshot(); minimized = true; updateDecorCursors(); // measure snapshotMetrics(); // edit Style targetStyle = getWidget().getElement().getStyle(); // content targetStyle.setHeight(0, Style.Unit.PX); onResize(); MinimizeEvent.<WindowUI> fire(this, this); } } protected Double leftToRestore; protected Double topToRestore; protected Double contentWidthToRestore; protected Double contentHeightToRestore; @Override public void restoreSnapshot() { if (minimized || maximized) { minimized = false; maximized = false; if (leftToRestore != null) { getMovableTarget().getElement().getStyle().setLeft(leftToRestore, Style.Unit.PX); } leftToRestore = null; if (topToRestore != null) { getMovableTarget().getElement().getStyle().setTop(topToRestore, Style.Unit.PX); } topToRestore = null; if (contentWidthToRestore != null) { getWidget().getElement().getStyle().setWidth(contentWidthToRestore, Style.Unit.PX); } contentWidthToRestore = null; if (contentHeightToRestore != null) { getWidget().getElement().getStyle().setHeight(contentHeightToRestore, Style.Unit.PX); } contentHeightToRestore = null; onResize(); RestoreEvent.<WindowUI> fire(this, this); } } @Override public void restore() { if (minimized || maximized) { if (maximized || preMinimzedStateNormal) { restoreSnapshot(); updateDecorCursors(); } else if (preMinimizedStateMaximized) { maximize(); } } } @Override public boolean isActive() { return active; } @Override public void activate() { if (!active) { active = true; if (captionWidget != null) { captionWidget.addStyleDependentName(ACTIVE_SUFFIX_NAMNE); } Widget[] widgets = new Widget[] { n, s, w, e, ne, nw, se, sw, content }; for (Widget _w : widgets) { _w.addStyleDependentName(ACTIVE_SUFFIX_NAMNE); } ActivateEvent.<WindowUI> fire(this, this); } } @Override public void deactivate() { if (active) { active = false; if (captionWidget != null) { captionWidget.removeStyleDependentName(ACTIVE_SUFFIX_NAMNE); } Widget[] widgets = new Widget[] { n, s, w, e, ne, nw, se, sw, content }; for (Widget _w : widgets) { _w.removeStyleDependentName(ACTIVE_SUFFIX_NAMNE); } DeactivateEvent.<WindowUI> fire(this, this); } } public void toFront() { Element selfEl = getMovableTarget().getElement(); Element parentEl = selfEl.getParentElement(); if (parentEl != null) { Node lastChildNode = parentEl.getLastChild(); if (lastChildNode instanceof Element && lastChildNode != selfEl) { parentEl.insertAfter(selfEl, lastChildNode); } } } /** * Activates and brings the window to front. Descandants may focus default * widget in this method. */ @Override public void focus() { activate(); toFront(); } @Override protected void onAttach() { super.onAttach(); onResize(); OpenEvent.<WindowUI> fire(this, this); } protected void fireCloseEvent() { ClosedEvent.<WindowUI> fire(this, this); } @Override public void close() { if (!BeforeCloseEvent.<WindowUI> fire(this, this)) { getMovableTarget().removeFromParent(); fireCloseEvent(); } } @Override public boolean isMovable() { return movable; } @Override public void setMovable(boolean aValue) { movable = aValue; updateCaptionCursor(); } @Override public boolean isAnimationEnabled() { return animationEnabled; } @Override public void setAnimationEnabled(boolean aValue) { if (animationEnabled != aValue) { animationEnabled = aValue; verticalPanelContent.getElement().getStyle().clearProperty("transition"); if (!animationEnabled) { verticalPanelContent.getElement().getStyle().setProperty("transition", "none"); } } } @Override protected void beginResizing() { super.beginResizing(); verticalPanelContent.getElement().getStyle().setProperty("transition", "none"); getMovableTarget().getElement().getStyle().setProperty("transition", "none"); getWidget().getElement().getStyle().setVisibility(Style.Visibility.HIDDEN); } @Override protected void endResizing() { super.endResizing(); getWidget().getElement().getStyle().clearVisibility(); if (animationEnabled) { verticalPanelContent.getElement().getStyle().clearProperty("transition"); getMovableTarget().getElement().getStyle().clearProperty("transition"); } } protected void beginMoving() { getMovableTarget().getElement().getStyle().setProperty("transition", "none"); getWidget().getElement().getStyle().setVisibility(Style.Visibility.HIDDEN); } protected void endMoving() { getWidget().getElement().getStyle().clearVisibility(); if (animationEnabled) { getMovableTarget().getElement().getStyle().clearProperty("transition"); } } protected void updateCaptionCursor() { if (captionWidget != null) { if (movable) { captionWidget.getElement().getStyle().clearCursor(); } else { captionWidget.getElement().getStyle().setCursor(Style.Cursor.DEFAULT); } } } @Override public HandlerRegistration addOpenHandler(OpenHandler<WindowUI> handler) { return addHandler(handler, OpenEvent.getType()); } @Override public HandlerRegistration addClosedHandler(ClosedHandler<WindowUI> handler) { return addHandler(handler, ClosedEvent.getType()); } @Override public HandlerRegistration addBeforeCloseHandler(BeforeCloseHandler<WindowUI> handler) { return addHandler(handler, BeforeCloseEvent.getType()); } @Override public HandlerRegistration addActivateHandler(ActivateHandler<WindowUI> handler) { return addHandler(handler, ActivateEvent.getType()); } @Override public HandlerRegistration addDeactivateHandler(DeactivateHandler<WindowUI> handler) { return addHandler(handler, DeactivateEvent.getType()); } @Override public HandlerRegistration addMinimizeHandler(MinimizeHandler<WindowUI> handler) { return addHandler(handler, MinimizeEvent.getType()); } @Override public HandlerRegistration addMaximizeHandler(MaximizeHandler<WindowUI> handler) { return addHandler(handler, MaximizeEvent.getType()); } @Override public HandlerRegistration addRestoreHandler(RestoreHandler<WindowUI> handler) { return addHandler(handler, RestoreEvent.getType()); } @Override public HandlerRegistration addMoveHandler(MoveHandler<WindowUI> handler) { return addHandler(handler, MoveEvent.getType()); } @Override public HandlerRegistration addResizeHandler(ResizeHandler handler) { return addHandler(handler, ResizeEvent.getType()); } }
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.polyglot.de; import static org.junit.Assert.*; import org.hamcrest.Matcher; import org.hamcrest.core.IsEqual; /** * Werkzeuge für deutsche Integrations-Tests. * * @author Sam Brannen * @since 1.0 */ public final class TestWerkzeuge { public static final boolean jawohl = true; public static final boolean wahr = true; public static final boolean falsch = false; public static <T> void esWirdErwartetDass(T actual, Matcher<? super T> matcher) { assertThat("", actual, matcher); } public static <T> Matcher<T> istGleich(T operand) { return IsEqual.<T> equalTo(operand); } }
/* * 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.beam.runners.dataflow.worker; import static org.apache.beam.runners.dataflow.worker.DataflowMatchers.ByteStringMatcher.byteStringEq; import static org.apache.beam.sdk.testing.SystemNanoTimeSleeper.sleepMillis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import java.io.Closeable; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.apache.beam.runners.core.StateNamespace; import org.apache.beam.runners.core.StateNamespaceForTest; import org.apache.beam.runners.core.StateTag; import org.apache.beam.runners.core.StateTags; import org.apache.beam.runners.dataflow.worker.windmill.Windmill; import org.apache.beam.runners.dataflow.worker.windmill.Windmill.TagBag; import org.apache.beam.runners.dataflow.worker.windmill.Windmill.TagValue; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.coders.VarIntCoder; import org.apache.beam.sdk.state.BagState; import org.apache.beam.sdk.state.CombiningState; import org.apache.beam.sdk.state.GroupingState; import org.apache.beam.sdk.state.ReadableState; import org.apache.beam.sdk.state.ValueState; import org.apache.beam.sdk.state.WatermarkHoldState; import org.apache.beam.sdk.transforms.Sum; import org.apache.beam.sdk.transforms.windowing.TimestampCombiner; import org.apache.beam.sdk.util.CoderUtils; import org.apache.beam.vendor.grpc.v1p21p0.com.google.protobuf.ByteString; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Supplier; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.Futures; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.SettableFuture; import org.hamcrest.Matchers; import org.joda.time.Instant; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; /** Tests for {@link WindmillStateInternals}. */ @RunWith(JUnit4.class) public class WindmillStateInternalsTest { private static final StateNamespace NAMESPACE = new StateNamespaceForTest("ns"); private static final String STATE_FAMILY = "family"; private static final StateTag<CombiningState<Integer, int[], Integer>> COMBINING_ADDR = StateTags.combiningValueFromInputInternal("combining", VarIntCoder.of(), Sum.ofIntegers()); private static final ByteString COMBINING_KEY = key(NAMESPACE, "combining"); private final Coder<int[]> accumCoder = Sum.ofIntegers().getAccumulatorCoder(null, VarIntCoder.of()); private long workToken = 0; @Mock private WindmillStateReader mockReader; private WindmillStateInternals<String> underTest; private WindmillStateInternals<String> underTestNewKey; private WindmillStateCache cache; @Mock private Supplier<Closeable> readStateSupplier; private static ByteString key(StateNamespace namespace, String addrId) { return ByteString.copyFromUtf8(namespace.stringKey() + "+u" + addrId); } private static ByteString systemKey(StateNamespace namespace, String addrId) { return ByteString.copyFromUtf8(namespace.stringKey() + "+s" + addrId); } @Before public void setUp() { MockitoAnnotations.initMocks(this); cache = new WindmillStateCache(); resetUnderTest(); } public void resetUnderTest() { workToken++; underTest = new WindmillStateInternals<>( "dummyKey", STATE_FAMILY, mockReader, false, cache.forComputation("comp").forKey(ByteString.EMPTY, STATE_FAMILY, 17L, workToken), readStateSupplier); underTestNewKey = new WindmillStateInternals<String>( "dummyNewKey", STATE_FAMILY, mockReader, true, cache.forComputation("comp").forKey(ByteString.EMPTY, STATE_FAMILY, 17L, workToken), readStateSupplier); } @After public void tearDown() throws Exception { // Make sure no WindmillStateReader (a per-WorkItem object) escapes into the cache // (a global object). WindmillStateTestUtils.assertNoReference(cache, WindmillStateReader.class); } private <T> void waitAndSet(final SettableFuture<T> future, final T value, final long millis) { new Thread( () -> { try { sleepMillis(millis); } catch (InterruptedException e) { throw new RuntimeException("Interrupted before setting", e); } future.set(value); }) .run(); } private WindmillStateReader.WeightedList<String> weightedList(String... elems) { WindmillStateReader.WeightedList<String> result = new WindmillStateReader.WeightedList<>(new ArrayList<String>(elems.length)); for (String elem : elems) { result.addWeighted(elem, elem.length()); } return result; } @Test public void testBagAddBeforeRead() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); SettableFuture<Iterable<String>> future = SettableFuture.create(); when(mockReader.bagFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of())) .thenReturn(future); bag.readLater(); bag.add("hello"); waitAndSet(future, Arrays.asList("world"), 200); assertThat(bag.read(), Matchers.containsInAnyOrder("hello", "world")); bag.add("goodbye"); assertThat(bag.read(), Matchers.containsInAnyOrder("hello", "world", "goodbye")); } @Test public void testBagClearBeforeRead() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); bag.clear(); bag.add("hello"); assertThat(bag.read(), Matchers.containsInAnyOrder("hello")); // Shouldn't need to read from windmill for this. Mockito.verifyZeroInteractions(mockReader); } @Test public void testBagIsEmptyFalse() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); SettableFuture<Iterable<String>> future = SettableFuture.create(); when(mockReader.bagFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of())) .thenReturn(future); ReadableState<Boolean> result = bag.isEmpty().readLater(); Mockito.verify(mockReader).bagFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of()); waitAndSet(future, Arrays.asList("world"), 200); assertThat(result.read(), Matchers.is(false)); } @Test public void testBagIsEmptyTrue() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); SettableFuture<Iterable<String>> future = SettableFuture.create(); when(mockReader.bagFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of())) .thenReturn(future); ReadableState<Boolean> result = bag.isEmpty().readLater(); Mockito.verify(mockReader).bagFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of()); waitAndSet(future, Arrays.<String>asList(), 200); assertThat(result.read(), Matchers.is(true)); } @Test public void testBagIsEmptyAfterClear() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); bag.clear(); ReadableState<Boolean> result = bag.isEmpty(); Mockito.verify(mockReader, never()) .bagFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of()); assertThat(result.read(), Matchers.is(true)); bag.add("hello"); assertThat(result.read(), Matchers.is(false)); } @Test public void testBagAddPersist() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); bag.add("hello"); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getBagUpdatesCount()); TagBag bagUpdates = commitBuilder.getBagUpdates(0); assertEquals(key(NAMESPACE, "bag"), bagUpdates.getTag()); assertEquals(1, bagUpdates.getValuesCount()); assertEquals("hello", bagUpdates.getValues(0).toStringUtf8()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testBagClearPersist() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); bag.add("hello"); bag.clear(); bag.add("world"); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getBagUpdatesCount()); TagBag tagBag = commitBuilder.getBagUpdates(0); assertEquals(key(NAMESPACE, "bag"), tagBag.getTag()); assertEquals(STATE_FAMILY, tagBag.getStateFamily()); assertTrue(tagBag.getDeleteAll()); assertEquals(1, tagBag.getValuesCount()); assertEquals("world", tagBag.getValues(0).toStringUtf8()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testBagPersistEmpty() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); bag.clear(); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); // 1 bag update = the clear assertEquals(1, commitBuilder.getBagUpdatesCount()); } @Test public void testNewBagNoFetch() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTestNewKey.state(NAMESPACE, addr); assertThat(bag.read(), Matchers.emptyIterable()); // Shouldn't need to read from windmill for this. Mockito.verifyZeroInteractions(mockReader); } @Test @SuppressWarnings("ArraysAsListPrimitiveArray") public void testCombiningAddBeforeRead() throws Exception { GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR); SettableFuture<Iterable<int[]>> future = SettableFuture.create(); when(mockReader.bagFuture(eq(COMBINING_KEY), eq(STATE_FAMILY), Mockito.<Coder<int[]>>any())) .thenReturn(future); value.readLater(); value.add(5); value.add(6); waitAndSet(future, Arrays.asList(new int[] {8}, new int[] {10}), 200); assertThat(value.read(), Matchers.equalTo(29)); // That get "compressed" the combiner. So, the underlying future should change: future.set(Arrays.asList(new int[] {29})); value.add(2); assertThat(value.read(), Matchers.equalTo(31)); } @Test public void testCombiningClearBeforeRead() throws Exception { GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR); value.clear(); value.readLater(); value.add(5); value.add(6); assertThat(value.read(), Matchers.equalTo(11)); value.add(2); assertThat(value.read(), Matchers.equalTo(13)); // Shouldn't need to read from windmill for this because we immediately cleared.. Mockito.verifyZeroInteractions(mockReader); } @Test @SuppressWarnings("ArraysAsListPrimitiveArray") public void testCombiningIsEmpty() throws Exception { GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR); SettableFuture<Iterable<int[]>> future = SettableFuture.create(); when(mockReader.bagFuture(eq(COMBINING_KEY), eq(STATE_FAMILY), Mockito.<Coder<int[]>>any())) .thenReturn(future); ReadableState<Boolean> result = value.isEmpty().readLater(); ArgumentCaptor<ByteString> byteString = ArgumentCaptor.forClass(ByteString.class); // Note that we do expect the third argument - the coder - to be equal to accumCoder, but that // is possibly overspecified and currently trips an issue in the SDK where identical coders are // not #equals(). // // What matters is that a future is created, hence a Windmill RPC sent. Mockito.verify(mockReader) .bagFuture(byteString.capture(), eq(STATE_FAMILY), Mockito.<Coder<int[]>>any()); assertThat(byteString.getValue(), byteStringEq(COMBINING_KEY)); waitAndSet(future, Arrays.asList(new int[] {29}), 200); assertThat(result.read(), Matchers.is(false)); } @Test public void testCombiningIsEmptyAfterClear() throws Exception { GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR); value.clear(); ReadableState<Boolean> result = value.isEmpty(); Mockito.verify(mockReader, never()).bagFuture(COMBINING_KEY, STATE_FAMILY, accumCoder); assertThat(result.read(), Matchers.is(true)); value.add(87); assertThat(result.read(), Matchers.is(false)); } @Test public void testCombiningAddPersist() throws Exception { disableCompactOnWrite(); GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR); value.add(5); value.add(6); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getBagUpdatesCount()); TagBag bagUpdates = commitBuilder.getBagUpdates(0); assertEquals(COMBINING_KEY, bagUpdates.getTag()); assertEquals(1, bagUpdates.getValuesCount()); assertEquals( 11, CoderUtils.decodeFromByteArray(accumCoder, bagUpdates.getValues(0).toByteArray())[0]); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testCombiningAddPersistWithCompact() throws Exception { forceCompactOnWrite(); Mockito.when( mockReader.bagFuture( org.mockito.Matchers.<ByteString>any(), org.mockito.Matchers.<String>any(), org.mockito.Matchers.<Coder<int[]>>any())) .thenReturn( Futures.<Iterable<int[]>>immediateFuture( ImmutableList.of(new int[] {40}, new int[] {60}))); GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR); value.add(5); value.add(6); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getBagUpdatesCount()); TagBag bagUpdates = commitBuilder.getBagUpdates(0); assertEquals(COMBINING_KEY, bagUpdates.getTag()); assertEquals(1, bagUpdates.getValuesCount()); assertTrue(bagUpdates.getDeleteAll()); assertEquals( 111, CoderUtils.decodeFromByteArray(accumCoder, bagUpdates.getValues(0).toByteArray())[0]); } @Test public void testCombiningClearPersist() throws Exception { disableCompactOnWrite(); GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR); value.clear(); value.add(5); value.add(6); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getBagUpdatesCount()); TagBag tagBag = commitBuilder.getBagUpdates(0); assertEquals(COMBINING_KEY, tagBag.getTag()); assertEquals(STATE_FAMILY, tagBag.getStateFamily()); assertTrue(tagBag.getDeleteAll()); assertEquals(1, tagBag.getValuesCount()); assertEquals( 11, CoderUtils.decodeFromByteArray(accumCoder, tagBag.getValues(0).toByteArray())[0]); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testNewCombiningNoFetch() throws Exception { GroupingState<Integer, Integer> value = underTestNewKey.state(NAMESPACE, COMBINING_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); assertThat(value.read(), Matchers.is(Sum.ofIntegers().identity())); assertThat(value.isEmpty().read(), Matchers.is(false)); // Shouldn't need to read from windmill for this. Mockito.verifyZeroInteractions(mockReader); } @Test public void testWatermarkAddBeforeReadEarliest() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState bag = underTest.state(NAMESPACE, addr); SettableFuture<Instant> future = SettableFuture.create(); when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)).thenReturn(future); bag.readLater(); bag.add(new Instant(3000)); waitAndSet(future, new Instant(2000), 200); assertThat(bag.read(), Matchers.equalTo(new Instant(2000))); Mockito.verify(mockReader, times(2)).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); Mockito.verifyNoMoreInteractions(mockReader); // Adding another value doesn't create another future, but does update the result. bag.add(new Instant(1000)); assertThat(bag.read(), Matchers.equalTo(new Instant(1000))); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkAddBeforeReadLatest() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.LATEST); WatermarkHoldState bag = underTest.state(NAMESPACE, addr); SettableFuture<Instant> future = SettableFuture.create(); when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)).thenReturn(future); // Suggesting we will read it later should get a future from the underlying WindmillStateReader bag.readLater(); // Actually reading it will request another future, and get the same one, from // WindmillStateReader bag.add(new Instant(3000)); waitAndSet(future, new Instant(2000), 200); assertThat(bag.read(), Matchers.equalTo(new Instant(3000))); Mockito.verify(mockReader, times(2)).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); Mockito.verifyNoMoreInteractions(mockReader); // Adding another value doesn't create another future, but does update the result. bag.add(new Instant(3000)); assertThat(bag.read(), Matchers.equalTo(new Instant(3000))); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkAddBeforeReadEndOfWindow() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.END_OF_WINDOW); WatermarkHoldState bag = underTest.state(NAMESPACE, addr); SettableFuture<Instant> future = SettableFuture.create(); when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)).thenReturn(future); // Requests a future once bag.readLater(); bag.add(new Instant(3000)); waitAndSet(future, new Instant(3000), 200); // read() requests a future again, receiving the same one assertThat(bag.read(), Matchers.equalTo(new Instant(3000))); Mockito.verify(mockReader, times(2)).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); Mockito.verifyNoMoreInteractions(mockReader); // Adding another value doesn't create another future, but does update the result. bag.add(new Instant(3000)); assertThat(bag.read(), Matchers.equalTo(new Instant(3000))); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkClearBeforeRead() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState bag = underTest.state(NAMESPACE, addr); bag.clear(); assertThat(bag.read(), Matchers.nullValue()); bag.add(new Instant(300)); assertThat(bag.read(), Matchers.equalTo(new Instant(300))); // Shouldn't need to read from windmill because the value is already available. Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkPersistEarliest() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState bag = underTest.state(NAMESPACE, addr); bag.add(new Instant(1000)); bag.add(new Instant(2000)); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getWatermarkHoldsCount()); Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); assertEquals(TimeUnit.MILLISECONDS.toMicros(1000), watermarkHold.getTimestamps(0)); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkPersistLatestEmpty() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.LATEST); WatermarkHoldState hold = underTest.state(NAMESPACE, addr); hold.add(new Instant(1000)); hold.add(new Instant(2000)); when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)) .thenReturn(Futures.<Instant>immediateFuture(null)); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getWatermarkHoldsCount()); Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); assertEquals(TimeUnit.MILLISECONDS.toMicros(2000), watermarkHold.getTimestamps(0)); Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkPersistLatestWindmillWins() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.LATEST); WatermarkHoldState hold = underTest.state(NAMESPACE, addr); hold.add(new Instant(1000)); hold.add(new Instant(2000)); when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)) .thenReturn(Futures.<Instant>immediateFuture(new Instant(4000))); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getWatermarkHoldsCount()); Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); assertEquals(TimeUnit.MILLISECONDS.toMicros(4000), watermarkHold.getTimestamps(0)); Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkPersistLatestLocalAdditionsWin() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.LATEST); WatermarkHoldState hold = underTest.state(NAMESPACE, addr); hold.add(new Instant(1000)); hold.add(new Instant(2000)); when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)) .thenReturn(Futures.<Instant>immediateFuture(new Instant(500))); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getWatermarkHoldsCount()); Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); assertEquals(TimeUnit.MILLISECONDS.toMicros(2000), watermarkHold.getTimestamps(0)); Mockito.verify(mockReader).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkPersistEndOfWindow() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.END_OF_WINDOW); WatermarkHoldState hold = underTest.state(NAMESPACE, addr); hold.add(new Instant(2000)); hold.add(new Instant(2000)); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getWatermarkHoldsCount()); Windmill.WatermarkHold watermarkHold = commitBuilder.getWatermarkHolds(0); assertEquals(key(NAMESPACE, "watermark"), watermarkHold.getTag()); assertEquals(TimeUnit.MILLISECONDS.toMicros(2000), watermarkHold.getTimestamps(0)); // Blind adds should not need to read the future. Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkClearPersist() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState hold = underTest.state(NAMESPACE, addr); hold.add(new Instant(500)); hold.clear(); hold.add(new Instant(1000)); hold.add(new Instant(2000)); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getWatermarkHoldsCount()); Windmill.WatermarkHold clearAndUpdate = commitBuilder.getWatermarkHolds(0); assertEquals(key(NAMESPACE, "watermark"), clearAndUpdate.getTag()); assertEquals(1, clearAndUpdate.getTimestampsCount()); assertEquals(TimeUnit.MILLISECONDS.toMicros(1000), clearAndUpdate.getTimestamps(0)); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testWatermarkPersistEmpty() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState bag = underTest.state(NAMESPACE, addr); bag.add(new Instant(500)); bag.clear(); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); // 1 bag update corresponds to deletion. There shouldn't be a bag update adding items. assertEquals(1, commitBuilder.getWatermarkHoldsCount()); } @Test public void testNewWatermarkNoFetch() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState bag = underTestNewKey.state(NAMESPACE, addr); assertThat(bag.read(), Matchers.nullValue()); // Shouldn't need to read from windmill for this. Mockito.verifyZeroInteractions(mockReader); } @Test public void testValueSetBeforeRead() throws Exception { StateTag<ValueState<String>> addr = StateTags.value("value", StringUtf8Coder.of()); ValueState<String> value = underTest.state(NAMESPACE, addr); value.write("Hello"); assertEquals("Hello", value.read()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testValueClearBeforeRead() throws Exception { StateTag<ValueState<String>> addr = StateTags.value("value", StringUtf8Coder.of()); ValueState<String> value = underTest.state(NAMESPACE, addr); value.clear(); assertEquals(null, value.read()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testValueRead() throws Exception { StateTag<ValueState<String>> addr = StateTags.value("value", StringUtf8Coder.of()); ValueState<String> value = underTest.state(NAMESPACE, addr); SettableFuture<String> future = SettableFuture.create(); when(mockReader.valueFuture(key(NAMESPACE, "value"), STATE_FAMILY, StringUtf8Coder.of())) .thenReturn(future); waitAndSet(future, "World", 200); assertEquals("World", value.read()); } @Test public void testValueSetPersist() throws Exception { StateTag<ValueState<String>> addr = StateTags.value("value", StringUtf8Coder.of()); ValueState<String> value = underTest.state(NAMESPACE, addr); value.write("Hi"); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getValueUpdatesCount()); TagValue valueUpdate = commitBuilder.getValueUpdates(0); assertEquals(key(NAMESPACE, "value"), valueUpdate.getTag()); assertEquals("Hi", valueUpdate.getValue().getData().toStringUtf8()); assertTrue(valueUpdate.isInitialized()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testValueClearPersist() throws Exception { StateTag<ValueState<String>> addr = StateTags.value("value", StringUtf8Coder.of()); ValueState<String> value = underTest.state(NAMESPACE, addr); value.write("Hi"); value.clear(); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(1, commitBuilder.getValueUpdatesCount()); TagValue valueUpdate = commitBuilder.getValueUpdates(0); assertEquals(key(NAMESPACE, "value"), valueUpdate.getTag()); assertEquals(0, valueUpdate.getValue().getData().size()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testValueNoChangePersist() throws Exception { StateTag<ValueState<String>> addr = StateTags.value("value", StringUtf8Coder.of()); underTest.state(NAMESPACE, addr); Windmill.WorkItemCommitRequest.Builder commitBuilder = Windmill.WorkItemCommitRequest.newBuilder(); underTest.persist(commitBuilder); assertEquals(0, commitBuilder.getValueUpdatesCount()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testNewValueNoFetch() throws Exception { StateTag<ValueState<String>> addr = StateTags.value("value", StringUtf8Coder.of()); ValueState<String> value = underTestNewKey.state(NAMESPACE, addr); assertEquals(null, value.read()); // Shouldn't need to read from windmill for this. Mockito.verifyZeroInteractions(mockReader); } @Test public void testCachedValue() throws Exception { StateTag<ValueState<String>> addr = StateTags.value("value", StringUtf8Coder.of()); ValueState<String> value = underTest.state(NAMESPACE, addr); assertEquals(0, cache.getWeight()); value.write("Hi"); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(126, cache.getWeight()); resetUnderTest(); value = underTest.state(NAMESPACE, addr); assertEquals("Hi", value.read()); value.clear(); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(124, cache.getWeight()); resetUnderTest(); value = underTest.state(NAMESPACE, addr); assertEquals(null, value.read()); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testCachedBag() throws Exception { StateTag<BagState<String>> addr = StateTags.bag("bag", StringUtf8Coder.of()); BagState<String> bag = underTest.state(NAMESPACE, addr); assertEquals(0, cache.getWeight()); SettableFuture<Iterable<String>> future = SettableFuture.create(); when(mockReader.bagFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of())) .thenReturn(future); bag.readLater(); assertEquals(0, cache.getWeight()); bag.add("hello"); waitAndSet(future, weightedList("world"), 200); Iterable<String> readResult1 = bag.read(); assertThat(readResult1, Matchers.containsInAnyOrder("hello", "world")); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(134, cache.getWeight()); resetUnderTest(); bag = underTest.state(NAMESPACE, addr); bag.add("goodbye"); // Make sure that cached iterables have not changed after persist+add. assertThat(readResult1, Matchers.containsInAnyOrder("hello", "world")); Iterable<String> readResult2 = bag.read(); assertThat(readResult2, Matchers.containsInAnyOrder("hello", "world", "goodbye")); bag.clear(); // Make sure that cached iterables have not changed after clear. assertThat(readResult2, Matchers.containsInAnyOrder("hello", "world", "goodbye")); bag.add("new"); // Make sure that cached iterables have not changed after clear+add. assertThat(readResult2, Matchers.containsInAnyOrder("hello", "world", "goodbye")); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(127, cache.getWeight()); resetUnderTest(); bag = underTest.state(NAMESPACE, addr); bag.add("new2"); assertThat(bag.read(), Matchers.containsInAnyOrder("new", "new2")); bag.clear(); bag.add("new3"); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(128, cache.getWeight()); resetUnderTest(); bag = underTest.state(NAMESPACE, addr); assertThat(bag.read(), Matchers.containsInAnyOrder("new3")); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); Mockito.verify(mockReader, times(2)) .bagFuture(key(NAMESPACE, "bag"), STATE_FAMILY, StringUtf8Coder.of()); Mockito.verifyNoMoreInteractions(mockReader); } @Test public void testCachedWatermarkHold() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState hold = underTest.state(NAMESPACE, addr); SettableFuture<Instant> future = SettableFuture.create(); when(mockReader.watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY)).thenReturn(future); assertEquals(0, cache.getWeight()); hold.readLater(); hold.add(new Instant(3000)); waitAndSet(future, new Instant(2000), 200); assertThat(hold.read(), Matchers.equalTo(new Instant(2000))); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(132, cache.getWeight()); resetUnderTest(); hold = underTest.state(NAMESPACE, addr); assertThat(hold.read(), Matchers.equalTo(new Instant(2000))); hold.clear(); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(132, cache.getWeight()); resetUnderTest(); hold = underTest.state(NAMESPACE, addr); assertEquals(null, hold.read()); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); Mockito.verify(mockReader, times(2)).watermarkFuture(key(NAMESPACE, "watermark"), STATE_FAMILY); Mockito.verifyNoMoreInteractions(mockReader); } @Test @SuppressWarnings("ArraysAsListPrimitiveArray") public void testCachedCombining() throws Exception { GroupingState<Integer, Integer> value = underTest.state(NAMESPACE, COMBINING_ADDR); SettableFuture<Iterable<int[]>> future = SettableFuture.create(); when(mockReader.bagFuture( eq(key(NAMESPACE, "combining")), eq(STATE_FAMILY), Mockito.<Coder<int[]>>any())) .thenReturn(future); assertEquals(0, cache.getWeight()); value.readLater(); value.add(1); waitAndSet(future, Arrays.asList(new int[] {2}), 200); assertThat(value.read(), Matchers.equalTo(3)); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(125, cache.getWeight()); resetUnderTest(); value = underTest.state(NAMESPACE, COMBINING_ADDR); assertThat(value.read(), Matchers.equalTo(3)); value.add(3); assertThat(value.read(), Matchers.equalTo(6)); value.clear(); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); assertEquals(124, cache.getWeight()); resetUnderTest(); value = underTest.state(NAMESPACE, COMBINING_ADDR); assertThat(value.read(), Matchers.equalTo(0)); underTest.persist(Windmill.WorkItemCommitRequest.newBuilder()); // Note that we do expect the third argument - the coder - to be equal to accumCoder, but that // is possibly overspecified and currently trips an issue in the SDK where identical coders are // not #equals(). // // What matters is the number of futures created, hence Windmill RPCs. Mockito.verify(mockReader, times(2)) .bagFuture(eq(key(NAMESPACE, "combining")), eq(STATE_FAMILY), Mockito.<Coder<int[]>>any()); Mockito.verifyNoMoreInteractions(mockReader); } private void disableCompactOnWrite() { WindmillStateInternals.COMPACT_NOW.set(() -> false); } private void forceCompactOnWrite() { WindmillStateInternals.COMPACT_NOW.set(() -> true); } }
package org.jsoup.nodes; import org.jsoup.helper.StringUtil; import org.jsoup.helper.Validate; import org.jsoup.select.NodeTraversor; import org.jsoup.select.NodeVisitor; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** The base, abstract Node model. Elements, Documents, Comments etc are all Node instances. @author Jonathan Hedley, jonathan@hedley.net */ public abstract class Node { Node parentNode; List<Node> childNodes; Attributes attributes; String baseUri; int siblingIndex; /** Create a new Node. @param baseUri base URI @param attributes attributes (not null, but may be empty) */ protected Node(String baseUri, Attributes attributes) { Validate.notNull(baseUri); Validate.notNull(attributes); childNodes = new ArrayList<Node>(4); this.baseUri = baseUri.trim(); this.attributes = attributes; } protected Node(String baseUri) { this(baseUri, new Attributes()); } /** * Default constructor. Doesn't setup base uri, children, or attributes; use with caution. */ protected Node() { childNodes = Collections.EMPTY_LIST; attributes = null; } /** Get the node name of this node. Use for debugging purposes and not logic switching (for that, use instanceof). @return node name */ public abstract String nodeName(); /** * Get an attribute's value by its key. * <p/> * To get an absolute URL from an attribute that may be a relative URL, prefix the key with <code><b>abs</b></code>, * which is a shortcut to the {@link #absUrl} method. * E.g.: <blockquote><code>String url = a.attr("abs:href");</code></blockquote> * @param attributeKey The attribute key. * @return The attribute, or empty string if not present (to avoid nulls). * @see #attributes() * @see #hasAttr(String) * @see #absUrl(String) */ public String attr(String attributeKey) { Validate.notNull(attributeKey); if (hasAttr(attributeKey)) return attributes.get(attributeKey); else if (attributeKey.toLowerCase().startsWith("abs:")) return absUrl(attributeKey.substring("abs:".length())); else return ""; } /** * Get all of the element's attributes. * @return attributes (which implements iterable, in same order as presented in original HTML). */ public Attributes attributes() { return attributes; } /** * Set an attribute (key=value). If the attribute already exists, it is replaced. * @param attributeKey The attribute key. * @param attributeValue The attribute value. * @return this (for chaining) */ public Node attr(String attributeKey, String attributeValue) { attributes.put(attributeKey, attributeValue); return this; } /** * Test if this element has an attribute. * @param attributeKey The attribute key to check. * @return true if the attribute exists, false if not. */ public boolean hasAttr(String attributeKey) { Validate.notNull(attributeKey); return attributes.hasKey(attributeKey); } /** * Remove an attribute from this element. * @param attributeKey The attribute to remove. * @return this (for chaining) */ public Node removeAttr(String attributeKey) { Validate.notNull(attributeKey); attributes.remove(attributeKey); return this; } /** Get the base URI of this node. @return base URI */ public String baseUri() { return baseUri; } /** Update the base URI of this node. @param baseUri base URI to set */ public void setBaseUri(String baseUri) { Validate.notNull(baseUri); this.baseUri = baseUri; } /** * Get an absolute URL from a URL attribute that may be relative (i.e. an <code>&lt;a href></code> or * <code>&lt;img src></code>). * <p/> * E.g.: <code>String absUrl = linkEl.absUrl("href");</code> * <p/> * If the attribute value is already absolute (i.e. it starts with a protocol, like * <code>http://</code> or <code>https://</code> etc), and it successfully parses as a URL, the attribute is * returned directly. Otherwise, it is treated as a URL relative to the element's {@link #baseUri}, and made * absolute using that. * <p/> * As an alternate, you can use the {@link #attr} method with the <code>abs:</code> prefix, e.g.: * <code>String absUrl = linkEl.attr("abs:href");</code> * * @param attributeKey The attribute key * @return An absolute URL if one could be made, or an empty string (not null) if the attribute was missing or * could not be made successfully into a URL. * @see #attr * @see java.net.URL#URL(java.net.URL, String) */ public String absUrl(String attributeKey) { Validate.notEmpty(attributeKey); String relUrl = attr(attributeKey); if (!hasAttr(attributeKey)) { return ""; // nothing to make absolute with } else { URL base; try { try { base = new URL(baseUri); } catch (MalformedURLException e) { // the base is unsuitable, but the attribute may be abs on its own, so try that URL abs = new URL(relUrl); return abs.toExternalForm(); } URL abs = new URL(base, relUrl); return abs.toExternalForm(); } catch (MalformedURLException e) { return ""; } } } /** Get a child node by index @param index index of child node @return the child node at this index. */ public Node childNode(int index) { return childNodes.get(index); } /** Get this node's children. Presented as an unmodifiable list: new children can not be added, but the child nodes themselves can be manipulated. @return list of children. If no children, returns an empty list. */ public List<Node> childNodes() { return Collections.unmodifiableList(childNodes); } protected Node[] childNodesAsArray() { return childNodes.toArray(new Node[childNodes().size()]); } /** Gets this node's parent node. @return parent node; or null if no parent. */ public Node parent() { return parentNode; } /** * Gets the Document associated with this Node. * @return the Document associated with this Node, or null if there is no such Document. */ public Document ownerDocument() { if (this instanceof Document) return (Document) this; else if (parentNode == null) return null; else return parentNode.ownerDocument(); } /** * Remove (delete) this node from the DOM tree. If this node has children, they are also removed. */ public void remove() { Validate.notNull(parentNode); parentNode.removeChild(this); } /** * Replace this node in the DOM with the supplied node. * @param in the node that will will replace the existing node. */ public void replaceWith(Node in) { Validate.notNull(in); Validate.notNull(parentNode); parentNode.replaceChild(this, in); } protected void setParentNode(Node parentNode) { if (this.parentNode != null) this.parentNode.removeChild(this); this.parentNode = parentNode; } protected void replaceChild(Node out, Node in) { Validate.isTrue(out.parentNode == this); Validate.notNull(in); if (in.parentNode != null) in.parentNode.removeChild(in); Integer index = out.siblingIndex(); childNodes.set(index, in); in.parentNode = this; in.setSiblingIndex(index); out.parentNode = null; } protected void removeChild(Node out) { Validate.isTrue(out.parentNode == this); int index = out.siblingIndex(); childNodes.remove(index); reindexChildren(); out.parentNode = null; } protected void addChildren(Node... children) { //most used. short circuit addChildren(int), which hits reindex children and array copy for (Node child: children) { reparentChild(child); childNodes.add(child); child.setSiblingIndex(childNodes.size()-1); } } protected void addChildren(int index, Node... children) { Validate.noNullElements(children); for (int i = children.length - 1; i >= 0; i--) { Node in = children[i]; reparentChild(in); childNodes.add(index, in); } reindexChildren(); } private void reparentChild(Node child) { if (child.parentNode != null) child.parentNode.removeChild(child); child.setParentNode(this); } private void reindexChildren() { for (int i = 0; i < childNodes.size(); i++) { childNodes.get(i).setSiblingIndex(i); } } /** Retrieves this node's sibling nodes. Effectively, {@link #childNodes() node.parent.childNodes()}. @return node siblings, including this node */ public List<Node> siblingNodes() { return parent().childNodes(); // TODO: should this strip out this node? i.e. not a sibling of self? } /** Get this node's next sibling. @return next sibling, or null if this is the last sibling */ public Node nextSibling() { if (parentNode == null) return null; // root List<Node> siblings = parentNode.childNodes; Integer index = siblingIndex(); Validate.notNull(index); if (siblings.size() > index+1) return siblings.get(index+1); else return null; } /** Get this node's previous sibling. @return the previous sibling, or null if this is the first sibling */ public Node previousSibling() { List<Node> siblings = parentNode.childNodes; Integer index = siblingIndex(); Validate.notNull(index); if (index > 0) return siblings.get(index-1); else return null; } /** * Get the list index of this node in its node sibling list. I.e. if this is the first node * sibling, returns 0. * @return position in node sibling list * @see org.jsoup.nodes.Element#elementSiblingIndex() */ public Integer siblingIndex() { return siblingIndex; } protected void setSiblingIndex(int siblingIndex) { this.siblingIndex = siblingIndex; } /** Get the outer HTML of this node. @return HTML */ public String outerHtml() { StringBuilder accum = new StringBuilder(32*1024); outerHtml(accum); return accum.toString(); } protected void outerHtml(StringBuilder accum) { new NodeTraversor(new OuterHtmlVisitor(accum, getOutputSettings())).traverse(this); } // if this node has no document (or parent), retrieve the default output settings private Document.OutputSettings getOutputSettings() { return ownerDocument() != null ? ownerDocument().outputSettings() : (new Document("")).outputSettings(); } /** Get the outer HTML of this node. @param accum accumulator to place HTML into */ abstract void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out); abstract void outerHtmlTail(StringBuilder accum, int depth, Document.OutputSettings out); public String toString() { return outerHtml(); } protected void indent(StringBuilder accum, int depth, Document.OutputSettings out) { accum.append("\n").append(StringUtil.padding(depth * out.indentAmount())); } @Override public boolean equals(Object o) { if (this == o) return true; // todo: have nodes hold a child index, compare against that and parent (not children) return false; } @Override public int hashCode() { int result = parentNode != null ? parentNode.hashCode() : 0; // not children, or will block stack as they go back up to parent) result = 31 * result / (attributes != null ? attributes.hashCode() : 0); return result; } private static class OuterHtmlVisitor implements NodeVisitor { private StringBuilder accum; private Document.OutputSettings out; OuterHtmlVisitor(StringBuilder accum, Document.OutputSettings out) { this.accum = accum; this.out = out; } public void head(Node node, int depth) { node.outerHtmlHead(accum, depth, out); } public void tail(Node node, int depth) { if (!node.nodeName().equals("#text")) // saves a void hit. node.outerHtmlTail(accum, depth, out); } } }
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.routing.weighting; import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.util.EdgeIteratorState; import com.graphhopper.util.PMap; /** * Calculates the fastest route with distance influence controlled by a new parameter. * <p> * * @author Peter Karich */ public class ShortFastestWeighting extends FastestWeighting { // For now keep parameters local within class private static final String NAME = "short_fastest"; private static final String TIME_FACTOR = "short_fastest.time_factor"; private static final String DISTANCE_FACTOR = "short_fastest.distance_factor"; private final double distanceFactor; private final double timeFactor; public ShortFastestWeighting(FlagEncoder encoder, PMap pMap) { super(encoder); timeFactor = checkBounds(TIME_FACTOR, pMap.getDouble(TIME_FACTOR, 1)); // is it faster to include timeFactor via distanceFactor = tmp / timeFactor? // default value derived from the cost for time e.g. 25€/hour and for distance 0.5€/km distanceFactor = checkBounds(DISTANCE_FACTOR, pMap.getDouble(DISTANCE_FACTOR, 0.07)); if (timeFactor < 1e-5 && distanceFactor < 1e-5) throw new IllegalArgumentException("[" + NAME + "] one of distance_factor or time_factor has to be non-zero"); } public ShortFastestWeighting(FlagEncoder encoder, double distanceFactor) { super(encoder); this.distanceFactor = checkBounds(DISTANCE_FACTOR, distanceFactor); this.timeFactor = 1; } @Override public double getMinWeight(double distance) { return super.getMinWeight(distance * distanceFactor); } @Override public double calcWeight(EdgeIteratorState edge, boolean reverse, int prevOrNextEdgeId) { double time = super.calcWeight(edge, reverse, prevOrNextEdgeId); return time * timeFactor + edge.getDistance() * distanceFactor; } @Override public String getName() { return NAME; } private double checkBounds(String key, double val) { if (val < 0 || val > 10) throw new IllegalArgumentException(key + " has invalid range should be within [0, 10]"); return val; } }
/** * Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.mit.ll.nics.nicsdao.mappers; import edu.mit.ll.jdbc.JoinRowMapper; import edu.mit.ll.nics.common.entity.Form; import edu.mit.ll.nics.common.constants.SADisplayConstants; import java.sql.ResultSet; import java.sql.SQLException; public class FormRowMapper extends JoinRowMapper<Form> { public FormRowMapper() { super("form"); } @Override public Form createRowObject(ResultSet rs, int rowNum) throws SQLException { Form form = new Form(); form.setDistributed(rs.getBoolean(SADisplayConstants.DISTRIBUTED)); form.setFormId(rs.getInt(SADisplayConstants.FORM_ID)); form.setFormtypeid(rs.getInt(SADisplayConstants.FORM_TYPE_ID)); form.setIncidentid(rs.getInt(SADisplayConstants.INCIDENT_ID)); form.setIncidentname(rs.getString(SADisplayConstants.INCIDENT_NAME)); form.setMessage(rs.getString(SADisplayConstants.MESSAGE)); form.setSeqnum(rs.getLong(SADisplayConstants.SEQ_NUM)); form.setSeqtime(rs.getLong(SADisplayConstants.SEQ_TIME)); form.setUsersessionid(rs.getInt(SADisplayConstants.USERSESSION_ID)); return form; } public Integer getKey(ResultSet rs) throws SQLException{ return rs.getInt(SADisplayConstants.FORM_ID); } }
package com.facebook.stetho.inspector.elements; class Document$1 implements Runnable { final /* synthetic */ Document this$0; Document$1(Document this$0) { this.this$0 = this$0; } public void run() { Document.access$102(this.this$0, new ShadowDocument(Document.access$200(this.this$0).getRootElement())); Document.access$300(this.this$0).commit(); Document.access$200(this.this$0).setListener(new Document$ProviderListener(this.this$0, null)); } }
/*=====================================================*/ /* Project Title: Legends: Heroes and Monster */ /* Course Name: GRS CS611 */ /* Semester: Spring '21 */ /* Project Author: Victor Vicente */ /*=====================================================*/ package Game.Creation; import java.util.ArrayList; import Classes.LegendsMonsterClass; import Game.LegendsGame; import Game.LegendsMonster; import Game.Util.Creation.Names; import Game.Util.Monster.LegendsMonsterGameStats; import Game.Util.Monster.LegendsMonsterMonsterStats; import Util.Random; public class MonsterCreation { /* * Static Method to generate a list of monsters of size * (PossibleMonsterClasses.size()*amountOfEach). This list will then be used to * randomly pick Monsters for encounters. * * Each Monster will have a class, and randomly generated statistic relating to * their class and level. */ public static ArrayList<LegendsMonster> generateMonster(int amountOfEach) { ArrayList<LegendsMonster> monsters = new ArrayList<LegendsMonster>(); ArrayList<LegendsMonsterClass> localCopyMonsterClasses = LegendsMonsterClass.POSSIBLE_CLASSES; for (int i = 0; i < amountOfEach; i++) { for (LegendsMonsterClass classType : localCopyMonsterClasses) { monsters.add(new LegendsMonster(LegendsGame.ENTITY_IDS, Names.getName(classType), MonsterCreation.getMonsterStats(classType), new LegendsMonsterGameStats(), classType)); LegendsGame.ENTITY_IDS++; } } return monsters; } /* * Method to generate random Monster Stats based on the Monster Class, all based * around the Monster's level, and following the basic math of the handout given * to us. */ private static LegendsMonsterMonsterStats getMonsterStats(LegendsMonsterClass classType) { int level = Random.randomInt(1, 20); int maxHP = 100 * level; int strength = (int) Math .round(Random.randomInt(50, 150) * (Math.pow(classType.getDamageBoost() + 0.05, level))); int defense = (int) Math.round(Random.randomInt(0, 50) * (Math.pow(classType.getDefenseBoost() + 0.05, level))); double dodge = Math.max(Math .min(Random.randomDouble(0.0, 1.0) * (Math.pow(classType.getDodgeBoost() + 0.05, level)) - 1.0, 0.9), 0.0001); return new LegendsMonsterMonsterStats(maxHP, defense, strength, dodge, level); } }
/** * * @author Theo Sun * */ package org.fornever.swift.models;
package wusc.edu.pay.core.limit.util.impl; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import wusc.edu.pay.core.limit.util.AmountLimitValidator; import wusc.edu.pay.facade.limit.enums.LimitTypeEnum; /** * 交易金额限制验证器工厂 * * @author:zh */ @Component(value = "amountLimitValidatorFactory") public class AmountLimitValidatorFactory { private Map<String, AmountLimitValidator> amountLimitValidatorMap = null; @Autowired private SingleLimitValidator singleLimitValidator; @Autowired private CumulateLimitValidator cumulateLimitValidator; private void initMap(){ Map<String, AmountLimitValidator> initMap = new HashMap<String, AmountLimitValidator>(); initMap.put("SINGLE", singleLimitValidator); initMap.put("CUMULATE_DAILY", cumulateLimitValidator); initMap.put("CUMULATE_PER_MONTH", cumulateLimitValidator); setAmountLimitValidatorMap(initMap); } /** * 获取交易金额限制验证器 * * @param limitTypeEnum * 交易金额限制类型 * @return */ public AmountLimitValidator getAmountLimitValidator( LimitTypeEnum limitTypeEnum) { if(amountLimitValidatorMap == null){ amountLimitValidatorMap = new HashMap<String, AmountLimitValidator>(); initMap(); } if (amountLimitValidatorMap.containsKey(limitTypeEnum.toString())) { return amountLimitValidatorMap.get(limitTypeEnum.toString()); } throw new RuntimeException("根据限制类型未找到对应的交易金额限制验证器[limitTypeEnum=" + limitTypeEnum + "]"); } public void setAmountLimitValidatorMap( Map<String, AmountLimitValidator> amountLimitValidatorMap) { this.amountLimitValidatorMap = amountLimitValidatorMap; } }
package com.github.bot.curiosone.core.nlp; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Represents a Phrase. * A Phrase is a text that can be splitted in different Tokens. * A Phrase can be interpreted as a question or an answer. * Provides methods to create the Phrase and get its information. * @see com.github.bot.curiosone.core.nlp.Token The Token Class */ public class Phrase { /** * Stores the text content of this Phrase. */ private String text; /** * Wether the text ends with a question mark. */ private boolean question; /** * Lists the tokens extracted from this Phrase. * @see com.github.bot.curiosone.core.nlp.Token The Token Class */ private List<Token> tokens = new ArrayList<>(); /** * Constructs a Phrase, using the String provided by the user. * @param str * The phrase to be created */ public Phrase(String str) { text = str; tokens = Token.tokenize(str); question = str.charAt(str.length() - 1) == '?'; } /** * Returns whether this Phrase is a question or not. * @return {@code true} if the content is a question, {@code false} otherwise */ public boolean isQuestion() { return question; } /** * Gets the text of this Phrase. * @return the text content of this Phrase */ public String getText() { return text; } /** * Gets the Tokens of this Phrase. * @return the list of tokens extracted from this Phrase */ public List<Token> getTokens() { return new ArrayList<Token>(tokens); } /** * Returns a String representation of this Phrase. * @return a String representation of this Phrase in the form [text, tokens] */ @Override public String toString() { return "[" + text + ", " + tokens + "]"; } /** * Checks whether this Phrase equals to the given Object. * @param other * the other Phrase to be compared against * @return {@code true} if this Phrase equals the other Phrase; * {@code false} otherwise */ @Override public boolean equals(Object other) { if (other == this) { return true; } if (other == null || other.getClass() != this.getClass()) { return false; } Phrase that = (Phrase) other; return this.text.equals(that.text) && this.tokens.equals(that.tokens); } /** * Calculates the HashCode for this Phrase. * The HashCode depends on the HashCode of the content and its tokens. * @return the HashCode of this Phrase */ @Override public int hashCode() { return Objects.hash(text, tokens); } /** * Extracts phrases from an input text, splitting it by punctuation. * @param input * the text to be splitted in phrases * @return a List containing all the phrases of the given text. */ public static List<Phrase> extract(String input) { List<String> splitted = LangUtils.splitByPuntaction(input); List<Phrase> phrases = new ArrayList<>(splitted.size()); splitted.forEach(s -> phrases.add(new Phrase(s))); return phrases; } }
package com.cyn.gulimall.coupon.dao; import com.cyn.gulimall.coupon.entity.CouponHistoryEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 优惠券领取历史记录 * * @author chenyn * @email 775608598@qq.com * @date 2020-05-19 22:22:22 */ @Mapper public interface CouponHistoryDao extends BaseMapper<CouponHistoryEntity> { }
/* * Created by qingyou.ren on 2019/03/04. * Copyright 2015-2019 Sensors Data Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sensorsdata.analytics.android.sdk; import org.json.JSONObject; public interface SensorsDataTrackEventCallBack { /** * * @param eventName 事件名称 * @param eventProperties 要修改的事件属性 * @return true 表示事件将入库, false 表示事件将被抛弃 */ boolean onTrackEvent(String eventName, JSONObject eventProperties); }
/* * Copyright 2019 MovingBlocks * * 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.terasology.engine.persistence.typeHandling; import org.terasology.gestalt.module.sandbox.API; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks a {@link TypeHandlerFactory} to be automatically registered to the * {@link TypeHandlerLibrary} on environment change. * This can be used to (de)serialize custom components. * <p> * The {@link org.terasology.engine.registry.In} annotation can be used to access objects * in the parent {@link org.terasology.engine.context.Context}. */ @API @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface RegisterTypeHandlerFactory { }
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. 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.wso2.carbon.cassandra.cluster.mgt.operation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.cassandra.cluster.mgt.exception.ClusterDataAdminException; import org.wso2.carbon.cassandra.cluster.mgt.mbean.ClusterMBeanProxy; public class SnapshotHandler implements Runnable { private static Log log = LogFactory.getLog(SnapshotCleaner.class); private String tag; private String keyspace; private String cf; public SnapshotHandler(String tag, String keyspace, String cf) { this.tag = tag; this.keyspace = keyspace; this.cf = cf; } public SnapshotHandler(String tag, String keyspace) { this.tag = tag; this.keyspace = keyspace; } public SnapshotHandler(String tag) { this.tag = tag; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getKeyspace() { return keyspace; } public void setKeyspace(String keyspace) { this.keyspace = keyspace; } public String getCf() { return cf; } public void setCf(String cf) { this.cf = cf; } @Override public void run(){ try { ClusterMBeanProxy.getClusterStorageMBeanService().takeSnapShot(tag,cf,keyspace); } catch (ClusterDataAdminException e) { log.error("Error while taking the snapshot",e); } } }
package org.arquillian.cube.docker.impl.client; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InfoCmd; import com.github.dockerjava.api.model.Info; import org.arquillian.cube.docker.impl.util.AbstractCliInternetAddressResolver; import org.arquillian.cube.docker.impl.util.Boot2Docker; import org.arquillian.cube.docker.impl.util.DefaultDocker; import org.arquillian.cube.docker.impl.util.DockerMachine; import org.arquillian.cube.docker.impl.util.GitHubUtil; import org.arquillian.cube.docker.impl.util.HomeResolverUtil; import org.arquillian.cube.docker.impl.util.Machine; import org.arquillian.cube.docker.impl.util.OperatingSystemFamily; import org.arquillian.cube.docker.impl.util.OperatingSystemInterface; import org.arquillian.cube.docker.impl.util.Top; import org.arquillian.cube.impl.util.Strings; import org.arquillian.cube.impl.util.SystemEnvironmentVariables; import org.arquillian.spacelift.Spacelift; import org.arquillian.spacelift.task.net.DownloadTool; import javax.ws.rs.ProcessingException; import java.io.File; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import static org.arquillian.cube.docker.impl.client.CubeDockerConfigurator.DOCKER_HOST; public class CubeDockerConfigurationResolver { private static final String UNIX_SOCKET_SCHEME = "unix"; private static final String WINDOWS_NAMED_PIPE_SCHEME = "npipe"; private static final String TCP_SCHEME = "tcp"; private static final String HTTP_SCHEME = "http"; private static final String HTTPS_SCHEME = "https"; private static final String DOCKER_TLS_VERIFY = "DOCKER_TLS_VERIFY"; private static final String DOCKER_CERT_PATH = "DOCKER_CERT_PATH"; private static final String DOCKER_MACHINE_NAME = "DOCKER_MACHINE_NAME"; private static Random random = new Random(); private static Logger log = Logger.getLogger(CubeDockerConfigurationResolver.class.getName()); private final Top top; private final DockerMachine dockerMachine; private final Boot2Docker boot2Docker; private final DefaultDocker defaultDocker; private final OperatingSystemInterface operatingSystem; public CubeDockerConfigurationResolver(Top top, DockerMachine dockerMachine, Boot2Docker boot2Docker, DefaultDocker defaultDocker, OperatingSystemInterface operatingSystem) { this.top = top; this.dockerMachine = dockerMachine; this.boot2Docker = boot2Docker; this.operatingSystem = operatingSystem; this.defaultDocker = defaultDocker; } /** * Resolves the configuration. * * @param config The specified configuration. * @return The resolved configuration. */ public Map<String, String> resolve(Map<String, String> config) { config = resolveSystemEnvironmentVariables(config); config = resolveSystemDefaultSetup(config); config = resolveDockerInsideDocker(config); config = resolveDownloadDockerMachine(config); config = resolveAutoStartDockerMachine(config); config = resolveDefaultDockerMachine(config); config = resolveServerUriByOperativeSystem(config); config = resolveServerIp(config); config = resolveTlsVerification(config); return config; } private Map<String, String> resolveDockerInsideDocker(Map<String, String> cubeConfiguration) { // if DIND_RESOLUTION property is not set, since by default is enabled, we need to go inside code. if (!cubeConfiguration.containsKey(CubeDockerConfiguration.DIND_RESOLUTION) || Boolean.parseBoolean( cubeConfiguration.get(CubeDockerConfiguration.DIND_RESOLUTION))) { if (top.isSpinning()) { log.fine(String.format( "Your Cube tests are going to run inside a running Docker container. %s property is replaced to %s", CubeDockerConfiguration.DOCKER_URI, OperatingSystemFamily.DIND.getServerUri())); String serverUri = OperatingSystemFamily.DIND.getServerUri(); cubeConfiguration.put(CubeDockerConfiguration.DOCKER_URI, serverUri); } } return cubeConfiguration; } private Map<String, String> resolveDownloadDockerMachine(Map<String, String> config) { if (config.containsKey(CubeDockerConfiguration.DOCKER_MACHINE_NAME)) { final String cliPathExec = config.get(CubeDockerConfiguration.DOCKER_MACHINE_PATH); if (!dockerMachine.isDockerMachineInstalled(cliPathExec)) { String machineVersion = GitHubUtil.getDockerMachineLatestVersion(); String machineCustomPath = config.get(CubeDockerConfiguration.DOCKER_MACHINE_CUSTOM_PATH); File dockerMachineFile = CubeDockerConfiguration.resolveMachinePath(machineCustomPath, machineVersion); boolean dockerMachineFileExist = dockerMachineFile.exists(); String dockerMachinePath = dockerMachineFile.getPath(); String machineName = config.get(CubeDockerConfiguration.DOCKER_MACHINE_NAME); String machineUrl = CubeDockerConfiguration.resolveUrl(machineVersion); if (!dockerMachineFileExist) { final File parentFile = dockerMachineFile.getParentFile(); if(!parentFile.exists() && !parentFile.mkdirs()){ log.log(Level.SEVERE, "Failed to create directory: " + parentFile); } Spacelift.task(DownloadTool.class) .from(machineUrl) .to(dockerMachineFile) .execute() .await(); config.put(CubeDockerConfiguration.DOCKER_MACHINE_PATH, dockerMachinePath); dockerMachine.grantPermissionToDockerMachine(dockerMachinePath); String machineDriver = config.get(CubeDockerConfiguration.DOCKER_MACHINE_DRIVER); dockerMachine.createMachine(dockerMachinePath, machineDriver, machineName); } else { config.put(CubeDockerConfiguration.DOCKER_MACHINE_PATH, dockerMachinePath); } } } return config; } private Map<String, String> resolveAutoStartDockerMachine(Map<String, String> config) { final String cliPathExec = config.get(CubeDockerConfiguration.DOCKER_MACHINE_PATH); if (dockerMachine.isDockerMachineInstalled(cliPathExec)) { final Set<Machine> allMachines = dockerMachine.list(cliPathExec); Optional<Machine> machine = Optional.empty(); if (config.containsKey(CubeDockerConfiguration.DOCKER_MACHINE_NAME)) { String configuredMachineName = config.get(CubeDockerConfiguration.DOCKER_MACHINE_NAME); machine = allMachines.stream() .filter(m -> configuredMachineName.equals(m.getName())) .filter(m -> "Stopped".equalsIgnoreCase(m.getState())) .findFirst(); } else { if (allMachines.size() == 1 && "Stopped".equalsIgnoreCase(allMachines.iterator().next().getState())) { machine = Optional.of(allMachines.iterator().next()); } } machine.ifPresent(m -> dockerMachine.startDockerMachine(cliPathExec, m.getName())); } return config; } private Map<String, String> resolveDefaultDockerMachine(Map<String, String> config) { // if user has not specified Docker URI host not a docker machine // setting DOCKER_URI to avoid using docker machine although it is installed if (!config.containsKey(CubeDockerConfiguration.DOCKER_URI) && !config.containsKey( CubeDockerConfiguration.DOCKER_MACHINE_NAME)) { log.fine( "No DockerUri or DockerMachine has been set, let's see if there is only one Docker Machine Running."); if (dockerMachine.isDockerMachineInstalled(config.get(CubeDockerConfiguration.DOCKER_MACHINE_PATH))) { // we can inspect if docker machine has one and only one docker machine running, which means that would like to use that one Set<Machine> machines = this.dockerMachine.list(config.get(CubeDockerConfiguration.DOCKER_MACHINE_PATH), "state", "Running"); // if there is only one machine running we can use that one. // if not Cube will resolve the default URI depending on OS (linux socket, boot2docker, ...) if (machines.size() == 1) { log.fine(String.format("One Docker Machine is running (%s) and it is going to be used for tests", machines.iterator().next().getName())); config.put(CubeDockerConfiguration.DOCKER_MACHINE_NAME, getFirstMachine(machines).getName()); } } } return config; } private Machine getFirstMachine(Set<Machine> machines) { return machines.iterator().next(); } private Map<String, String> resolveSystemEnvironmentVariables(Map<String, String> config) { if (!config.containsKey(CubeDockerConfiguration.DOCKER_URI) && isDockerHostSet()) { String dockerHostUri = SystemEnvironmentVariables.getEnvironmentOrPropertyVariable(DOCKER_HOST); config.put(CubeDockerConfiguration.DOCKER_URI, dockerHostUri); } if (!config.containsKey(CubeDockerConfiguration.CERT_PATH) && isDockerCertPathSet()) { String dockerCertPath = SystemEnvironmentVariables.getEnvironmentOrPropertyVariable(DOCKER_CERT_PATH); config.put(CubeDockerConfiguration.CERT_PATH, dockerCertPath); } if (!config.containsKey(CubeDockerConfiguration.DOCKER_MACHINE_NAME) && isDockerMachineNameSet()) { String dockerMachineName = SystemEnvironmentVariables.getEnvironmentOrPropertyVariable(DOCKER_MACHINE_NAME); config.put(CubeDockerConfiguration.DOCKER_MACHINE_NAME, dockerMachineName); } if (!config.containsKey(CubeDockerConfiguration.TLS_VERIFY) && isDockerTlsVerifySet()) { config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.TRUE.toString()); } return config; } private Map<String, String> resolveSystemDefaultSetup(Map<String, String> config) { if (!config.containsKey(CubeDockerConfiguration.DOCKER_URI)) { final String defaultUri = operatingSystem.getDefaultFamily().getServerUri(); URI uri = URI.create(defaultUri); if (Files.exists(FileSystems.getDefault().getPath(uri.getPath()))){ DockerClient client = defaultDocker.getDefaultDockerClient(defaultUri); InfoCmd cmd = client.infoCmd(); try { Info info = cmd.exec(); config.put(CubeDockerConfiguration.DOCKER_URI, defaultUri); log.info(String.format("Connected to docker (%s) using default settings version: %s kernel: %s", info.getName(), info.getServerVersion(), info.getKernelVersion())); } catch (ProcessingException e){ log.info(String.format("Could not connect to default socket %s. Go on with ", operatingSystem.getDefaultFamily().getServerUri())); } } } return config; } private Map<String, String> resolveServerIp(Map<String, String> config) { String dockerServerUri = config.get(CubeDockerConfiguration.DOCKER_URI); if (containsDockerHostTag(dockerServerUri)) { if (isDockerMachineSet(config)) { dockerServerUri = resolveDockerMachine(dockerServerUri, config.get(CubeDockerConfiguration.DOCKER_MACHINE_NAME), config.get(CubeDockerConfiguration.DOCKER_MACHINE_PATH)); } else { dockerServerUri = resolveBoot2Docker(dockerServerUri, config.get(CubeDockerConfiguration.BOOT2DOCKER_PATH)); } if (!config.containsKey(CubeDockerConfiguration.TLS_VERIFY)) { config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.toString(true)); } } config.put(CubeDockerConfiguration.DOCKER_URI, dockerServerUri); resolveDockerServerIp(config, dockerServerUri); return config; } private Map<String, String> resolveTlsVerification(Map<String, String> config) { URI serverUri = URI.create(config.get(CubeDockerConfiguration.DOCKER_URI)); String scheme = serverUri.getScheme(); if (!config.containsKey(CubeDockerConfiguration.CERT_PATH)) { config.put(CubeDockerConfiguration.CERT_PATH, HomeResolverUtil.resolveHomeDirectoryChar(getDefaultTlsDirectory(config))); } if (scheme.equals(HTTP_SCHEME)) { config.remove(CubeDockerConfiguration.TLS_VERIFY); } if (scheme.equals(HTTPS_SCHEME)) { config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.toString(true)); } if (scheme.equals(HTTP_SCHEME) || scheme.equals(HTTPS_SCHEME) || scheme.equals(TCP_SCHEME)) { if (!config.containsKey(CubeDockerConfiguration.TLS_VERIFY)) { config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.toString(scheme.equals(HTTPS_SCHEME))); } try { // docker-java supports only tcp and unix schemes serverUri = new URI(TCP_SCHEME, serverUri.getSchemeSpecificPart(), serverUri.getFragment()); config.put(CubeDockerConfiguration.DOCKER_URI, serverUri.toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } if (scheme.equals("unix") || scheme.equals("npipe")){ config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.toString(false)); } if (!config.containsKey(CubeDockerConfiguration.TLS_VERIFY)) { config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.toString(true)); if (operatingSystem.getFamily() == OperatingSystemFamily.LINUX) { String dockerServerIp = config.get(CubeDockerConfiguration.DOCKER_SERVER_IP); if (isDockerMachineSet(config)) { if (InetAddress.getLoopbackAddress().getHostAddress().equals(dockerServerIp) || InetAddress.getLoopbackAddress().getHostName().equals(dockerServerIp)) { config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.toString(false)); } else { config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.toString(true)); } } else { config.put(CubeDockerConfiguration.TLS_VERIFY, Boolean.toString(false)); } } } if (Boolean.FALSE.toString().equals(config.get(CubeDockerConfiguration.TLS_VERIFY))) { config.remove(CubeDockerConfiguration.CERT_PATH); } return config; } private boolean containsDockerHostTag(String dockerServerUri) { return dockerServerUri.contains(AbstractCliInternetAddressResolver.DOCKERHOST_TAG); } private void resolveDockerServerIp(Map<String, String> config, String dockerServerUri) { URI serverUri = URI.create(dockerServerUri); String serverIp = UNIX_SOCKET_SCHEME.equalsIgnoreCase(serverUri.getScheme()) || WINDOWS_NAMED_PIPE_SCHEME.equalsIgnoreCase(serverUri.getScheme()) ? "localhost" : serverUri.getHost(); config.put(CubeDockerConfiguration.DOCKER_SERVER_IP, serverIp); } private boolean isDockerHostSet() { return Strings.isNotNullOrEmpty(SystemEnvironmentVariables.getEnvironmentOrPropertyVariable(DOCKER_HOST)); } private boolean isDockerCertPathSet() { return Strings.isNotNullOrEmpty(SystemEnvironmentVariables.getEnvironmentOrPropertyVariable(DOCKER_CERT_PATH)); } private boolean isDockerTlsVerifySet() { return Strings.isNotNullOrEmpty(SystemEnvironmentVariables.getEnvironmentOrPropertyVariable(DOCKER_TLS_VERIFY)); } private boolean isDockerMachineNameSet() { return Strings.isNotNullOrEmpty(SystemEnvironmentVariables.getEnvironmentOrPropertyVariable(DOCKER_MACHINE_NAME)); } private boolean isDockerMachineSet(Map<String, String> config) { return config.containsKey(CubeDockerConfiguration.DOCKER_MACHINE_NAME); } private String resolveDockerMachine(String tag, String machineName, String dockerMachinePath) { dockerMachine.setMachineName(machineName); return tag.replaceAll(AbstractCliInternetAddressResolver.DOCKERHOST_TAG, dockerMachine.ip(dockerMachinePath, false)); } private String resolveBoot2Docker(String tag, String boot2DockerPath) { return tag.replaceAll(AbstractCliInternetAddressResolver.DOCKERHOST_TAG, boot2Docker.ip(boot2DockerPath, false)); } private String getDefaultTlsDirectory(Map<String, String> config) { if (isDockerMachineSet(config)) { return "~" + File.separator + ".docker" + File.separator + "machine" + File.separator + "machines" + File.separator + config.get(CubeDockerConfiguration.DOCKER_MACHINE_NAME); } else { return "~" + File.separator + ".boot2docker" + File.separator + "certs" + File.separator + "boot2docker-vm"; } } private boolean containsCertPath(Map<String, String> cubeConfiguration) { return cubeConfiguration.containsKey(CubeDockerConfiguration.CERT_PATH); } private Map<String, String> resolveServerUriByOperativeSystem(Map<String, String> cubeConfiguration) { if (!cubeConfiguration.containsKey(CubeDockerConfiguration.DOCKER_URI)) { if (isDockerMachineSet(cubeConfiguration)) { String serverUri = OperatingSystemFamily.MACHINE.getServerUri(); cubeConfiguration.put(CubeDockerConfiguration.DOCKER_URI, serverUri); } else { String serverUri = operatingSystem.getFamily().getServerUri(); cubeConfiguration.put(CubeDockerConfiguration.DOCKER_URI, serverUri); } } return cubeConfiguration; } }
/* * 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.syncope.common.rest.api.beans; public class RemediationQuery extends AbstractQuery { private static final long serialVersionUID = 4000880445378096031L; public static class Builder extends AbstractQuery.Builder<RemediationQuery, Builder> { @Override protected RemediationQuery newInstance() { return new RemediationQuery(); } } }
package com.springservice.clientone; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ClientoneApplication { public static void main(String[] args) { SpringApplication.run(ClientoneApplication.class, args); } }
/* * #%L * de.metas.util.web * %% * Copyright (C) 2021 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.util.web.audit.dto; import com.fasterxml.jackson.core.JsonProcessingException; import de.metas.JsonObjectMapperHolder; import lombok.NonNull; import lombok.experimental.UtilityClass; import org.adempiere.exceptions.AdempiereException; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.util.ContentCachingResponseWrapper; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @UtilityClass public class ApiResponseMapper { @NonNull public ApiResponse map(@NonNull final ContentCachingResponseWrapper responseWrapper) { return new ApiResponse(responseWrapper.getStatus(), getHeaders(responseWrapper), getBody(responseWrapper)); } @NonNull public ApiResponse map(final int statusCode, @Nullable final HttpHeaders httpHeaders, @Nullable final String bodyCandidate) { return new ApiResponse(statusCode, httpHeaders, getBody(httpHeaders, bodyCandidate)); } @NonNull private HttpHeaders getHeaders(@NonNull final ContentCachingResponseWrapper responseWrapper) { final HttpHeaders responseHeaders = new HttpHeaders(); if (responseWrapper.getHeaderNames() == null || responseWrapper.getHeaderNames().isEmpty()) { return responseHeaders; } responseWrapper.getHeaderNames() .forEach(headerName -> responseHeaders.addAll(headerName, new ArrayList<>(responseWrapper.getHeaders(headerName)))); return responseHeaders; } @Nullable private Object getBody(@NonNull final ContentCachingResponseWrapper responseWrapper) { if (responseWrapper.getContentSize() <= 0 || !responseWrapper.getContentType().contains(APPLICATION_JSON_VALUE)) { return null; } try { return JsonObjectMapperHolder.sharedJsonObjectMapper() .readValue(responseWrapper.getContentAsByteArray(), Object.class); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e); } } @Nullable private Object getBody(@Nullable final HttpHeaders httpHeaders, @Nullable final String bodyCandidate) { final boolean isJsonBody = bodyCandidate != null && httpHeaders != null && httpHeaders.getContentType() != null && httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON); if (!isJsonBody) { return null; } try { return JsonObjectMapperHolder.sharedJsonObjectMapper() .readValue(bodyCandidate, Object.class); } catch (final JsonProcessingException e) { throw AdempiereException.wrapIfNeeded(e); } } }
package org.thoughtcrime.securesms.conversation; import android.content.Context; import android.database.ContentObserver; import androidx.annotation.NonNull; import androidx.paging.DataSource; import androidx.paging.PositionalDataSource; import org.thoughtcrime.securesms.database.DatabaseContentProviders; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.MmsSmsDatabase; import org.thoughtcrime.securesms.database.model.MessageRecord; import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.util.Util; import org.thoughtcrime.securesms.util.concurrent.SignalExecutors; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.Executor; /** * Core data source for loading an individual conversation. */ class ConversationDataSource extends PositionalDataSource<MessageRecord> { private static final String TAG = Log.tag(ConversationDataSource.class); public static final Executor EXECUTOR = SignalExecutors.newFixedLifoThreadExecutor("signal-conversation", 1, 1); private final Context context; private final long threadId; private final DataUpdatedCallback dataUpdateCallback; private ConversationDataSource(@NonNull Context context, long threadId, @NonNull Invalidator invalidator, @NonNull DataUpdatedCallback dataUpdateCallback) { this.context = context; this.threadId = threadId; this.dataUpdateCallback = dataUpdateCallback; ContentObserver contentObserver = new ContentObserver(null) { @Override public void onChange(boolean selfChange) { invalidate(); context.getContentResolver().unregisterContentObserver(this); } }; invalidator.observe(this::invalidate); context.getContentResolver().registerContentObserver(DatabaseContentProviders.Conversation.getUriForThread(threadId), true, contentObserver); } @Override public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<MessageRecord> callback) { long start = System.currentTimeMillis(); MmsSmsDatabase db = DatabaseFactory.getMmsSmsDatabase(context); List<MessageRecord> records = new ArrayList<>(params.requestedLoadSize); int totalCount = db.getConversationCount(threadId); int effectiveCount = params.requestedStartPosition; try (MmsSmsDatabase.Reader reader = db.readerFor(db.getConversation(threadId, params.requestedStartPosition, params.requestedLoadSize))) { MessageRecord record; while ((record = reader.getNext()) != null && effectiveCount < totalCount && !isInvalid()) { records.add(record); effectiveCount++; } } records = ensureMultipleOfPageSize(records, params.pageSize, totalCount); callback.onResult(records, params.requestedStartPosition, totalCount); Util.runOnMain(dataUpdateCallback::onDataUpdated); Log.d(TAG, "[Initial Load] " + (System.currentTimeMillis() - start) + " ms" + (isInvalid() ? " -- invalidated" : "")); } @Override public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<MessageRecord> callback) { long start = System.currentTimeMillis(); MmsSmsDatabase db = DatabaseFactory.getMmsSmsDatabase(context); List<MessageRecord> records = new ArrayList<>(params.loadSize); try (MmsSmsDatabase.Reader reader = db.readerFor(db.getConversation(threadId, params.startPosition, params.loadSize))) { MessageRecord record; while ((record = reader.getNext()) != null && !isInvalid()) { records.add(record); } } callback.onResult(records); Util.runOnMain(dataUpdateCallback::onDataUpdated); Log.d(TAG, "[Update] " + (System.currentTimeMillis() - start) + " ms" + (isInvalid() ? " -- invalidated" : "")); } private static @NonNull List<MessageRecord> ensureMultipleOfPageSize(@NonNull List<MessageRecord> records, int pageSize, int total) { if (records.size() != total && records.size() > pageSize && records.size() % pageSize != 0) { int overflow = records.size() % pageSize; return records.subList(0, records.size() - overflow); } else { return records; } } interface DataUpdatedCallback { void onDataUpdated(); } static class Invalidator { private Runnable callback; synchronized void invalidate() { if (callback != null) { callback.run(); } } private synchronized void observe(@NonNull Runnable callback) { this.callback = callback; } } static class Factory extends DataSource.Factory<Integer, MessageRecord> { private final Context context; private final long threadId; private final Invalidator invalidator; private final DataUpdatedCallback callback; Factory(Context context, long threadId, @NonNull Invalidator invalidator, @NonNull DataUpdatedCallback callback) { this.context = context; this.threadId = threadId; this.invalidator = invalidator; this.callback = callback; } @Override public @NonNull DataSource<Integer, MessageRecord> create() { return new ConversationDataSource(context, threadId, invalidator, callback); } } }
package com.bookstore.event; public class CheckReviewEvent { private final String reviewerEmail; public CheckReviewEvent(String reviewerEmail) { this.reviewerEmail = reviewerEmail; } public String getReviewerEmail() { return reviewerEmail; } }
package com.smatechnologies.msazure.storage.enums; public enum InformationTask { containers, blobs; }
/******************************************************************************* * Copyright (c) 2011 Kevin Sawicki * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.github.avatar.ui; import org.eclipse.jface.viewers.ColumnViewer; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; /** * Avatar label provider class. * * @author Kevin Sawicki (kevin@github.com) */ public class AvatarLabelProvider extends LabelProvider implements ITableLabelProvider { /** * DEFAULT_IMAGE_SIZE */ public static final int DEFAULT_IMAGE_SIZE = 32; private AvatarStore store = AvatarPlugin.getDefault().getAvatars(); private ColumnViewer viewer; private int imageSize = DEFAULT_IMAGE_SIZE; /** * Create avatar label provider for viewer * * @param viewer */ public AvatarLabelProvider(ColumnViewer viewer) { this.viewer = viewer; } /** * Set image size * * @param size * @return this label provider */ public AvatarLabelProvider setImageSize(int size) { this.imageSize = Math.max(1, size); return this; } /** * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) */ public Image getImage(final Object element) { Image scaled = null; String hash = this.store.getAdaptedHash(element); Avatar avatar = this.store.getAvatarByHash(hash); if (avatar != null) scaled = new AvatarImage(avatar).getScaledImage(this.imageSize); else store.loadAvatarByHash(hash, new AvatarDisplayCallback( new AvatarCallbackAdapter() { public void loaded(Avatar avatar) { if (!viewer.getControl().isDisposed()) viewer.refresh(true); } })); return scaled; } /** * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, * int) */ public Image getColumnImage(Object element, int columnIndex) { return columnIndex == 0 ? getImage(element) : null; } /** * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, * int) */ public String getColumnText(Object element, int columnIndex) { return columnIndex == 0 ? getText(element) : ""; //$NON-NLS-1$ } }
/* * Copyright 2012-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 sample.atmosphere; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.atmosphere.config.managed.Decoder; import org.atmosphere.config.managed.Encoder; import org.atmosphere.config.service.Disconnect; import org.atmosphere.config.service.ManagedService; import org.atmosphere.config.service.Ready; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.AtmosphereResourceEvent; import java.io.IOException; @ManagedService(path = "/chat") public class ChatService { private final Log logger = LogFactory.getLog(ChatService.class); @Ready public void onReady(AtmosphereResource resource) { this.logger.info("Connected " + resource.uuid()); } @Disconnect public void onDisconnect(AtmosphereResourceEvent event) { this.logger.info("Client " + event.getResource().uuid() + " disconnected [" + (event.isCancelled() ? "cancelled" : "closed") + "]"); } @org.atmosphere.config.service.Message(encoders = JacksonEncoderDecoder.class, decoders = JacksonEncoderDecoder.class) public Message onMessage(Message message) throws IOException { this.logger.info("Author " + message.getAuthor() + " sent message " + message.getMessage()); return message; } public static class JacksonEncoderDecoder implements Encoder<Message, String>, Decoder<String, Message> { private final ObjectMapper mapper = new ObjectMapper(); @Override public String encode(Message m) { try { return this.mapper.writeValueAsString(m); } catch (IOException ex) { throw new IllegalStateException(ex); } } @Override public Message decode(String s) { try { return this.mapper.readValue(s, Message.class); } catch (IOException ex) { throw new IllegalStateException(ex); } } } }
package hu.restumali.gamekeystore.service; import hu.restumali.gamekeystore.model.CouponEntity; import hu.restumali.gamekeystore.model.CouponEntityDTO; import hu.restumali.gamekeystore.repository.CouponRepository; import lombok.SneakyThrows; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; @Service @Transactional public class CouponService { @Autowired private CouponRepository couponRepository; public void save(CouponEntity couponEntity) { couponRepository.save(couponEntity); } public List<CouponEntity> findAll() { return couponRepository.findAll(); } public void deleteOneById(Long id) { CouponEntity managedEntity = couponRepository.findOneById(id); managedEntity.setDeleted(true); couponRepository.save(managedEntity); } public CouponEntity findById(Long id){ return couponRepository.findOneById(id); } public List<CouponEntity> findAllNotDeleted() { return couponRepository.findAllByDeleted(false); } @SneakyThrows public void createCouponEntity(CouponEntityDTO newCoupon){ CouponEntity coupon = new CouponEntity(); coupon.setDiscount(newCoupon.getDiscount()); coupon.setName(newCoupon.getName()); coupon.setValidUntil(new SimpleDateFormat("yyyy-MM-dd").parse(newCoupon.getValidUntil()).getTime()); coupon.setDeleted(false); couponRepository.save(coupon); } @SneakyThrows public void updateCouponById(Long id, CouponEntityDTO newCoupon){ CouponEntity managedCoupon = couponRepository.findOneById(id); managedCoupon.setName(newCoupon.getName()); managedCoupon.setDiscount(newCoupon.getDiscount()); managedCoupon.setValidUntil(new SimpleDateFormat("yyyy-MM-dd").parse(newCoupon.getValidUntil()).getTime()); couponRepository.save(managedCoupon); } }
/******************************************************************************* * <copyright> * * Copyright (c) 2014 Eteration A.S. * 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. * * * Derivative Works * Parts of this program are derived from content from Eclipse Foundation * that are made available under the terms of the Eclipse Public License v1.0. * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Naci Dai, Eteration A.S. - initial API, implementation and documentation * * </copyright> * *******************************************************************************/ package org.glassmaker.ui.views; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TreeMap; import org.eclipse.draw2d.geometry.Point; import org.eclipse.gef.EditPart; import org.eclipse.gef.Tool; import org.eclipse.gef.palette.PaletteDrawer; import org.eclipse.gef.palette.PaletteRoot; import org.eclipse.gef.palette.ToolEntry; import org.eclipse.gef.ui.palette.PaletteViewer; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.text.templates.Template; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.glassmaker.ui.GlassmakerUIPlugin; import org.glassmaker.ui.editor.CardEditor; public class PaletteView extends ViewPart { private PaletteViewer viewer; private TreeMap<String, List<IPaletteItem>> items = new TreeMap<String, List<IPaletteItem>>(); private HashMap<HTMLPaletteEntry, IPaletteItem> tools = new HashMap<HTMLPaletteEntry, IPaletteItem>(); public PaletteView() { Template[] templates = GlassmakerUIPlugin.getDefault().getTemplateStore().getTemplates(); ImageRegistry imageRegistry = GlassmakerUIPlugin.getDefault().getImageRegistry(); for(Template t: templates){ String imageId = "org.glassmaker.ui.templates."+t.getName().replace(" ", "").toLowerCase(); addPaletteItem("Card Types",new DefaultPaletteItem(t.getName(), imageRegistry.getDescriptor(imageId), t.getPattern())); } } /** * create controls and apply configurations. */ public void createPartControl(Composite parent) { viewer = new PaletteViewer(); viewer.createControl(parent); PaletteRoot root = new PaletteRoot(); String[] category = getCategories(); for(int i=0;i<category.length;i++){ PaletteDrawer group = new PaletteDrawer(category[i]); IPaletteItem[] items = getPaletteItems(category[i]); for(int j=0;j<items.length;j++){ HTMLPaletteEntry entry = new HTMLPaletteEntry(items[j].getLabel(),null,items[j].getImageDescriptor()); tools.put(entry,items[j]); group.add(entry); } root.add(group); } viewer.setPaletteRoot(root); viewer.getControl().addMouseListener(new MouseAdapter(){ @Override public void mouseDoubleClick(MouseEvent e) { // IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); // IEditorPart editorPart = page.getActiveEditor(); // if(editorPart!=null){ // editorPart.setFocus(); // } if (e.button == 1) { EditPart part = PaletteView.this.viewer.findObjectAt(new Point(e.x, e.y)); IPaletteItem item = null; if (part != null) { if (part.getModel() instanceof HTMLPaletteEntry) item = tools.get(part.getModel()); } if (item != null) insert(item); } } }); } private void insert(IPaletteItem item) { if(item == null) return; IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IEditorPart editorPart = page.getActiveEditor(); // execute processing of the palette item if(editorPart!=null){ if(editorPart instanceof CardEditor){ item.execute((CardEditor)editorPart); } else if(editorPart instanceof IPaletteTarget){ item.execute(((IPaletteTarget)editorPart).getPaletteTarget()); } } } /** * Adds PaletteItem to the specified category. * * @param category the category * @param item the item */ private void addPaletteItem(String category,IPaletteItem item){ if(items.get(category)==null){ List<IPaletteItem> list = new ArrayList<IPaletteItem>(); items.put(category,list); } List<IPaletteItem> list = items.get(category); list.add(item); } /** * Returns PaletteItems which are contained by the specified category. * * @param category the category * @return the array of items which are contained by the category */ private IPaletteItem[] getPaletteItems(String category){ List<IPaletteItem> list = items.get(category); if(list==null){ return new IPaletteItem[0]; } return list.toArray(new IPaletteItem[list.size()]); } /** * Returns all categories. * * @return the array which contains all categories */ private String[] getCategories(){ return items.keySet().toArray(new String[0]); } public void setFocus() { viewer.getControl().setFocus(); } /** ToolEntry for HTML tag palette */ private class HTMLPaletteEntry extends ToolEntry { public HTMLPaletteEntry(String label, String shortDescription, ImageDescriptor icon) { super(label, shortDescription, icon, icon); } public Tool createTool() { return null; } } }
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * 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. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.action.admin.cluster.snapshots.status; import org.opensearch.LegacyESVersion; import org.opensearch.common.Strings; import org.opensearch.common.io.stream.StreamInput; import org.opensearch.common.io.stream.StreamOutput; import org.opensearch.common.io.stream.Writeable; import org.opensearch.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.xcontent.ToXContent; import org.opensearch.common.xcontent.ToXContentObject; import org.opensearch.common.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentParserUtils; import java.io.IOException; public class SnapshotStats implements Writeable, ToXContentObject { private long startTime; private long time; private int incrementalFileCount; private int totalFileCount; private int processedFileCount; private long incrementalSize; private long totalSize; private long processedSize; SnapshotStats() {} SnapshotStats(StreamInput in) throws IOException { startTime = in.readVLong(); time = in.readVLong(); incrementalFileCount = in.readVInt(); processedFileCount = in.readVInt(); incrementalSize = in.readVLong(); processedSize = in.readVLong(); if (in.getVersion().onOrAfter(LegacyESVersion.V_6_4_0)) { totalFileCount = in.readVInt(); totalSize = in.readVLong(); } else { totalFileCount = incrementalFileCount; totalSize = incrementalSize; } } SnapshotStats( long startTime, long time, int incrementalFileCount, int totalFileCount, int processedFileCount, long incrementalSize, long totalSize, long processedSize ) { this.startTime = startTime; this.time = time; assert time >= 0 : "Tried to initialize snapshot stats with negative total time [" + time + "]"; this.incrementalFileCount = incrementalFileCount; this.totalFileCount = totalFileCount; this.processedFileCount = processedFileCount; this.incrementalSize = incrementalSize; this.totalSize = totalSize; this.processedSize = processedSize; } /** * Returns time when snapshot started */ public long getStartTime() { return startTime; } /** * Returns snapshot running time */ public long getTime() { return time; } /** * Returns incremental file count of the snapshot */ public int getIncrementalFileCount() { return incrementalFileCount; } /** * Returns total number of files in the snapshot */ public int getTotalFileCount() { return totalFileCount; } /** * Returns number of files in the snapshot that were processed so far */ public int getProcessedFileCount() { return processedFileCount; } /** * Return incremental files size of the snapshot */ public long getIncrementalSize() { return incrementalSize; } /** * Returns total size of files in the snapshot */ public long getTotalSize() { return totalSize; } /** * Returns total size of files in the snapshot that were processed so far */ public long getProcessedSize() { return processedSize; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(startTime); out.writeVLong(time); out.writeVInt(incrementalFileCount); out.writeVInt(processedFileCount); out.writeVLong(incrementalSize); out.writeVLong(processedSize); if (out.getVersion().onOrAfter(LegacyESVersion.V_6_4_0)) { out.writeVInt(totalFileCount); out.writeVLong(totalSize); } } static final class Fields { static final String STATS = "stats"; static final String INCREMENTAL = "incremental"; static final String PROCESSED = "processed"; static final String TOTAL = "total"; static final String FILE_COUNT = "file_count"; static final String SIZE = "size"; static final String SIZE_IN_BYTES = "size_in_bytes"; static final String START_TIME_IN_MILLIS = "start_time_in_millis"; static final String TIME_IN_MILLIS = "time_in_millis"; static final String TIME = "time"; } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); { builder.startObject(Fields.INCREMENTAL); { builder.field(Fields.FILE_COUNT, getIncrementalFileCount()); builder.humanReadableField(Fields.SIZE_IN_BYTES, Fields.SIZE, new ByteSizeValue(getIncrementalSize())); } builder.endObject(); if (getProcessedFileCount() != getIncrementalFileCount()) { builder.startObject(Fields.PROCESSED); { builder.field(Fields.FILE_COUNT, getProcessedFileCount()); builder.humanReadableField(Fields.SIZE_IN_BYTES, Fields.SIZE, new ByteSizeValue(getProcessedSize())); } builder.endObject(); } builder.startObject(Fields.TOTAL); { builder.field(Fields.FILE_COUNT, getTotalFileCount()); builder.humanReadableField(Fields.SIZE_IN_BYTES, Fields.SIZE, new ByteSizeValue(getTotalSize())); } builder.endObject(); // timings stats builder.field(Fields.START_TIME_IN_MILLIS, getStartTime()); builder.humanReadableField(Fields.TIME_IN_MILLIS, Fields.TIME, new TimeValue(getTime())); } return builder.endObject(); } public static SnapshotStats fromXContent(XContentParser parser) throws IOException { // Parse this old school style instead of using the ObjectParser since there's an impedance mismatch between how the // object has historically been written as JSON versus how it is structured in Java. XContentParser.Token token = parser.currentToken(); if (token == null) { token = parser.nextToken(); } XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); long startTime = 0; long time = 0; int incrementalFileCount = 0; int totalFileCount = 0; int processedFileCount = 0; long incrementalSize = 0; long totalSize = 0; long processedSize = 0; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); String currentName = parser.currentName(); token = parser.nextToken(); if (currentName.equals(Fields.INCREMENTAL)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); String innerName = parser.currentName(); token = parser.nextToken(); if (innerName.equals(Fields.FILE_COUNT)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); incrementalFileCount = parser.intValue(); } else if (innerName.equals(Fields.SIZE_IN_BYTES)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); incrementalSize = parser.longValue(); } else { // Unknown sub field, skip if (token == XContentParser.Token.START_OBJECT || token == XContentParser.Token.START_ARRAY) { parser.skipChildren(); } } } } else if (currentName.equals(Fields.PROCESSED)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); String innerName = parser.currentName(); token = parser.nextToken(); if (innerName.equals(Fields.FILE_COUNT)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); processedFileCount = parser.intValue(); } else if (innerName.equals(Fields.SIZE_IN_BYTES)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); processedSize = parser.longValue(); } else { // Unknown sub field, skip if (token == XContentParser.Token.START_OBJECT || token == XContentParser.Token.START_ARRAY) { parser.skipChildren(); } } } } else if (currentName.equals(Fields.TOTAL)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); String innerName = parser.currentName(); token = parser.nextToken(); if (innerName.equals(Fields.FILE_COUNT)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); totalFileCount = parser.intValue(); } else if (innerName.equals(Fields.SIZE_IN_BYTES)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); totalSize = parser.longValue(); } else { // Unknown sub field, skip if (token == XContentParser.Token.START_OBJECT || token == XContentParser.Token.START_ARRAY) { parser.skipChildren(); } } } } else if (currentName.equals(Fields.START_TIME_IN_MILLIS)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); startTime = parser.longValue(); } else if (currentName.equals(Fields.TIME_IN_MILLIS)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); time = parser.longValue(); } else { // Unknown field, skip if (token == XContentParser.Token.START_OBJECT || token == XContentParser.Token.START_ARRAY) { parser.skipChildren(); } } } return new SnapshotStats( startTime, time, incrementalFileCount, totalFileCount, processedFileCount, incrementalSize, totalSize, processedSize ); } /** * Add stats instance to the total * @param stats Stats instance to add * @param updateTimestamps Whether or not start time and duration should be updated */ void add(SnapshotStats stats, boolean updateTimestamps) { incrementalFileCount += stats.incrementalFileCount; totalFileCount += stats.totalFileCount; processedFileCount += stats.processedFileCount; incrementalSize += stats.incrementalSize; totalSize += stats.totalSize; processedSize += stats.processedSize; if (startTime == 0) { // First time here startTime = stats.startTime; time = stats.time; } else if (updateTimestamps) { // The time the last snapshot ends long endTime = Math.max(startTime + time, stats.startTime + stats.time); // The time the first snapshot starts startTime = Math.min(startTime, stats.startTime); // Update duration time = endTime - startTime; } assert time >= 0 : "Update with [" + Strings.toString(stats) + "][" + updateTimestamps + "] resulted in negative total time [" + time + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SnapshotStats that = (SnapshotStats) o; if (startTime != that.startTime) return false; if (time != that.time) return false; if (incrementalFileCount != that.incrementalFileCount) return false; if (totalFileCount != that.totalFileCount) return false; if (processedFileCount != that.processedFileCount) return false; if (incrementalSize != that.incrementalSize) return false; if (totalSize != that.totalSize) return false; return processedSize == that.processedSize; } @Override public int hashCode() { int result = (int) (startTime ^ (startTime >>> 32)); result = 31 * result + (int) (time ^ (time >>> 32)); result = 31 * result + incrementalFileCount; result = 31 * result + totalFileCount; result = 31 * result + processedFileCount; result = 31 * result + (int) (incrementalSize ^ (incrementalSize >>> 32)); result = 31 * result + (int) (totalSize ^ (totalSize >>> 32)); result = 31 * result + (int) (processedSize ^ (processedSize >>> 32)); return result; } }
/* * Copyright 2016 Open Networking Laboratory * * 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.onosproject.store.primitives.resources.impl; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multiset; import com.google.common.collect.Sets; import io.atomix.copycat.server.Commit; import io.atomix.copycat.server.Snapshottable; import io.atomix.copycat.server.StateMachineExecutor; import io.atomix.copycat.server.session.ServerSession; import io.atomix.copycat.server.session.SessionListener; import io.atomix.copycat.server.storage.snapshot.SnapshotReader; import io.atomix.copycat.server.storage.snapshot.SnapshotWriter; import io.atomix.resource.ResourceStateMachine; import org.onlab.util.CountDownCompleter; import org.onlab.util.Match; import org.onosproject.store.service.Versioned; import org.slf4j.Logger; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.EnumSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.Clear; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.ContainsEntry; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.ContainsKey; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.ContainsValue; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.Entries; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.Get; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.IsEmpty; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.KeySet; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.Keys; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.MultiRemove; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.MultimapCommand; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.Put; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.RemoveAll; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.Replace; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.Size; import static org.onosproject.store.primitives.resources.impl.AsyncConsistentMultimapCommands.Values; import static org.slf4j.LoggerFactory.getLogger; /** * State Machine for {@link AsyncConsistentSetMultimap} resource. */ public class AsyncConsistentSetMultimapState extends ResourceStateMachine implements SessionListener, Snapshottable { private final Logger log = getLogger(getClass()); private final AtomicLong globalVersion = new AtomicLong(1); //TODO Add listener map here private final Map<String, MapEntryValue> backingMap = Maps.newHashMap(); public AsyncConsistentSetMultimapState(Properties properties) { super(properties); } @Override public void snapshot(SnapshotWriter writer) { } @Override public void install(SnapshotReader reader) { } @Override protected void configure(StateMachineExecutor executor) { executor.register(Size.class, this::size); executor.register(IsEmpty.class, this::isEmpty); executor.register(ContainsKey.class, this::containsKey); executor.register(ContainsValue.class, this::containsValue); executor.register(ContainsEntry.class, this::containsEntry); executor.register(Clear.class, this::clear); executor.register(KeySet.class, this::keySet); executor.register(Keys.class, this::keys); executor.register(Values.class, this::values); executor.register(Entries.class, this::entries); executor.register(Get.class, this::get); executor.register(RemoveAll.class, this::removeAll); executor.register(MultiRemove.class, this::multiRemove); executor.register(Put.class, this::put); executor.register(Replace.class, this::replace); } @Override public void delete() { super.delete(); } /** * Handles a Size commit. * * @param commit Size commit * @return number of unique key value pairs in the multimap */ protected int size(Commit<? extends Size> commit) { try { return backingMap.values() .stream() .map(valueCollection -> valueCollection.values().size()) .collect(Collectors.summingInt(size -> size)); } finally { commit.close(); } } /** * Handles an IsEmpty commit. * * @param commit IsEmpty commit * @return true if the multimap contains no key-value pairs, else false */ protected boolean isEmpty(Commit<? extends IsEmpty> commit) { try { return backingMap.isEmpty(); } finally { commit.close(); } } /** * Handles a contains key commit. * * @param commit ContainsKey commit * @return returns true if the key is in the multimap, else false */ protected boolean containsKey(Commit<? extends ContainsKey> commit) { try { return backingMap.containsKey(commit.operation().key()); } finally { commit.close(); } } /** * Handles a ContainsValue commit. * * @param commit ContainsValue commit * @return true if the value is in the multimap, else false */ protected boolean containsValue(Commit<? extends ContainsValue> commit) { try { if (backingMap.values().isEmpty()) { return false; } Match<byte[]> match = Match.ifValue(commit.operation().value()); return backingMap .values() .stream() .anyMatch(valueList -> valueList .values() .stream() .anyMatch(byteValue -> match.matches(byteValue))); } finally { commit.close(); } } /** * Handles a ContainsEntry commit. * * @param commit ContainsEntry commit * @return true if the key-value pair exists, else false */ protected boolean containsEntry(Commit<? extends ContainsEntry> commit) { try { MapEntryValue entryValue = backingMap.get(commit.operation().key()); if (entryValue == null) { return false; } else { Match valueMatch = Match.ifValue(commit.operation().value()); return entryValue .values() .stream() .anyMatch(byteValue -> valueMatch.matches(byteValue)); } } finally { commit.close(); } } /** * Handles a Clear commit. * * @param commit Clear commit */ protected void clear(Commit<? extends Clear> commit) { try { backingMap.clear(); } finally { commit.close(); } } /** * Handles a KeySet commit. * * @param commit KeySet commit * @return a set of all keys in the multimap */ protected Set<String> keySet(Commit<? extends KeySet> commit) { try { return ImmutableSet.copyOf(backingMap.keySet()); } finally { commit.close(); } } /** * Handles a Keys commit. * * @param commit Keys commit * @return a multiset of keys with each key included an equal number of * times to the total key-value pairs in which that key participates */ protected Multiset<String> keys(Commit<? extends Keys> commit) { try { Multiset keys = HashMultiset.create(); backingMap.forEach((key, mapEntryValue) -> { keys.add(key, mapEntryValue.values().size()); }); return keys; } finally { commit.close(); } } /** * Handles a Values commit. * * @param commit Values commit * @return the set of values in the multimap with duplicates included */ protected Multiset<byte[]> values(Commit<? extends Values> commit) { try { return backingMap .values() .stream() .collect(new HashMultisetValueCollector()); } finally { commit.close(); } } /** * Handles an Entries commit. * * @param commit Entries commit * @return a set of all key-value pairs in the multimap */ protected Collection<Map.Entry<String, byte[]>> entries( Commit<? extends Entries> commit) { try { return backingMap .entrySet() .stream() .collect(new EntrySetCollector()); } finally { commit.close(); } } /** * Handles a Get commit. * * @param commit Get commit * @return the collection of values associated with the key or an empty * list if none exist */ protected Versioned<Collection<? extends byte[]>> get( Commit<? extends Get> commit) { try { MapEntryValue mapEntryValue = backingMap.get(commit.operation().key()); return toVersioned(backingMap.get(commit.operation().key())); } finally { commit.close(); } } /** * Handles a removeAll commit, and returns the previous mapping. * * @param commit removeAll commit * @return collection of removed values */ protected Versioned<Collection<? extends byte[]>> removeAll( Commit<? extends RemoveAll> commit) { if (!backingMap.containsKey(commit.operation().key())) { commit.close(); return new Versioned<>(Sets.newHashSet(), -1); } else { return backingMap.get(commit.operation().key()).addCommit(commit); } } /** * Handles a multiRemove commit, returns true if the remove results in any * change. * @param commit multiRemove commit * @return true if any change results, else false */ protected boolean multiRemove(Commit<? extends MultiRemove> commit) { if (!backingMap.containsKey(commit.operation().key())) { commit.close(); return false; } else { return (backingMap .get(commit.operation().key()) .addCommit(commit)) != null; } } /** * Handles a put commit, returns true if any change results from this * commit. * @param commit a put commit * @return true if this commit results in a change, else false */ protected boolean put(Commit<? extends Put> commit) { if (commit.operation().values().isEmpty()) { return false; } if (!backingMap.containsKey(commit.operation().key())) { backingMap.put(commit.operation().key(), new NonTransactionalCommit(1)); } return backingMap .get(commit.operation().key()) .addCommit(commit) != null; } protected Versioned<Collection<? extends byte[]>> replace( Commit<? extends Replace> commit) { if (!backingMap.containsKey(commit.operation().key())) { backingMap.put(commit.operation().key(), new NonTransactionalCommit(1)); } return backingMap.get(commit.operation().key()).addCommit(commit); } @Override public void register(ServerSession session) { super.register(session); } @Override public void unregister(ServerSession session) { super.unregister(session); } @Override public void expire(ServerSession session) { super.expire(session); } @Override public void close(ServerSession session) { super.close(session); } private interface MapEntryValue { /** * Returns the list of raw {@code byte[]'s}. * * @return list of raw values */ Collection<? extends byte[]> values(); /** * Returns the version of the value. * * @return version */ long version(); /** * Discards the value by invoke appropriate clean up actions. */ void discard(); /** * Add a new commit and modifies the set of values accordingly. * In the case of a replace or removeAll it returns the set of removed * values. In the case of put or multiRemove it returns null for no * change and a set of the added or removed values respectively if a * change resulted. * * @param commit the commit to be added */ Versioned<Collection<? extends byte[]>> addCommit( Commit<? extends MultimapCommand> commit); } private class NonTransactionalCommit implements MapEntryValue { private long version; private final TreeMap<byte[], CountDownCompleter<Commit>> valueCountdownMap = Maps.newTreeMap(new ByteArrayComparator()); /*This is a mapping of commits that added values to the commits * removing those values, they will not be circular because keys will * be exclusively Put and Replace commits and values will be exclusively * Multiremove commits, each time a Put or replace is removed it should * as part of closing go through and countdown each of the remove * commits depending on it.*/ private final HashMultimap<Commit, CountDownCompleter<Commit>> additiveToRemovalCommits = HashMultimap.create(); public NonTransactionalCommit( long version) { //Set the version to current it will only be updated once this is // populated this.version = globalVersion.get(); } @Override public Collection<? extends byte[]> values() { return ImmutableSet.copyOf(valueCountdownMap.keySet()); } @Override public long version() { return version; } @Override public void discard() { valueCountdownMap.values().forEach(completer -> completer.object().close()); } @Override public Versioned<Collection<? extends byte[]>> addCommit( Commit<? extends MultimapCommand> commit) { Preconditions.checkNotNull(commit); Preconditions.checkNotNull(commit.operation()); Versioned<Collection<? extends byte[]>> retVersion; if (commit.operation() instanceof Put) { //Using a treeset here sanitizes the input, removing duplicates Set<byte[]> valuesToAdd = Sets.newTreeSet(new ByteArrayComparator()); ((Put) commit.operation()).values().forEach(value -> { if (!valueCountdownMap.containsKey(value)) { valuesToAdd.add(value); } }); if (valuesToAdd.isEmpty()) { //Do not increment or add the commit if no change resulted commit.close(); return null; } //When all values from a commit have been removed decrement all //removal commits relying on it and remove itself from the //mapping of additive commits to the commits removing the //values it added. (Only multiremoves will be dependent) CountDownCompleter<Commit> completer = new CountDownCompleter<>(commit, valuesToAdd.size(), c -> { if (additiveToRemovalCommits.containsKey(c)) { additiveToRemovalCommits. get(c). forEach(countdown -> countdown.countDown()); additiveToRemovalCommits.removeAll(c); } c.close(); }); retVersion = new Versioned<>(valuesToAdd, version); valuesToAdd.forEach(value -> valueCountdownMap.put(value, completer)); version++; return retVersion; } else if (commit.operation() instanceof Replace) { //Will this work?? Need to check before check-in! Set<byte[]> removedValues = Sets.newHashSet(); removedValues.addAll(valueCountdownMap.keySet()); retVersion = new Versioned<>(removedValues, version); valueCountdownMap.values().forEach(countdown -> countdown.countDown()); valueCountdownMap.clear(); Set<byte[]> valuesToAdd = Sets.newTreeSet(new ByteArrayComparator()); ((Replace) commit.operation()).values().forEach(value -> { valuesToAdd.add(value); }); if (valuesToAdd.isEmpty()) { version = globalVersion.incrementAndGet(); backingMap.remove(((Replace) commit.operation()).key()); //Order is important here, the commit must be closed last //(or minimally after all uses) commit.close(); return retVersion; } CountDownCompleter<Commit> completer = new CountDownCompleter<>(commit, valuesToAdd.size(), c -> { if (additiveToRemovalCommits .containsKey(c)) { additiveToRemovalCommits. get(c). forEach(countdown -> countdown.countDown()); additiveToRemovalCommits. removeAll(c); } c.close(); }); valuesToAdd.forEach(value -> valueCountdownMap.put(value, completer)); version = globalVersion.incrementAndGet(); return retVersion; } else if (commit.operation() instanceof RemoveAll) { Set<byte[]> removed = Sets.newHashSet(); //We can assume here that values only appear once and so we //do not need to sanitize the return for duplicates. removed.addAll(valueCountdownMap.keySet()); retVersion = new Versioned<>(removed, version); valueCountdownMap.values().forEach(countdown -> countdown.countDown()); valueCountdownMap.clear(); //In the case of a removeAll all commits will be removed and //unlike the multiRemove case we do not need to consider //dependencies among additive and removal commits. //Save the key for use after the commit is closed String key = ((RemoveAll) commit.operation()).key(); commit.close(); version = globalVersion.incrementAndGet(); backingMap.remove(key); return retVersion; } else if (commit.operation() instanceof MultiRemove) { //Must first calculate how many commits the removal depends on. //At this time we also sanitize the removal set by adding to a //set with proper handling of byte[] equality. Set<byte[]> removed = Sets.newHashSet(); Set<Commit> commitsRemovedFrom = Sets.newHashSet(); ((MultiRemove) commit.operation()).values().forEach(value -> { if (valueCountdownMap.containsKey(value)) { removed.add(value); commitsRemovedFrom .add(valueCountdownMap.get(value).object()); } }); //If there is nothing to be removed no action should be taken. if (removed.isEmpty()) { //Do not increment or add the commit if no change resulted commit.close(); return null; } //When all additive commits this depends on are closed this can //be closed as well. CountDownCompleter<Commit> completer = new CountDownCompleter<>(commit, commitsRemovedFrom.size(), c -> c.close()); commitsRemovedFrom.forEach(commitRemovedFrom -> { additiveToRemovalCommits.put(commitRemovedFrom, completer); }); //Save key in case countdown results in closing the commit. String removedKey = ((MultiRemove) commit.operation()).key(); removed.forEach(removedValue -> { valueCountdownMap.remove(removedValue).countDown(); }); //The version is updated locally as well as globally even if //this object will be removed from the map in case any other //party still holds a reference to this object. retVersion = new Versioned<>(removed, version); version = globalVersion.incrementAndGet(); if (valueCountdownMap.isEmpty()) { backingMap .remove(removedKey); } return retVersion; } else { throw new IllegalArgumentException(); } } } /** * A collector that creates MapEntryValues and creates a multiset of all * values in the map an equal number of times to the number of sets in * which they participate. */ private class HashMultisetValueCollector implements Collector<MapEntryValue, HashMultiset<byte[]>, HashMultiset<byte[]>> { private HashMultiset<byte[]> multiset = null; @Override public Supplier<HashMultiset<byte[]>> supplier() { return new Supplier<HashMultiset<byte[]>>() { @Override public HashMultiset<byte[]> get() { if (multiset == null) { multiset = HashMultiset.create(); } return multiset; } }; } @Override public BiConsumer<HashMultiset<byte[]>, MapEntryValue> accumulator() { return (multiset, mapEntryValue) -> multiset.addAll(mapEntryValue.values()); } @Override public BinaryOperator<HashMultiset<byte[]>> combiner() { return (setOne, setTwo) -> { setOne.addAll(setTwo); return setOne; }; } @Override public Function<HashMultiset<byte[]>, HashMultiset<byte[]>> finisher() { return (unused) -> multiset; } @Override public Set<Characteristics> characteristics() { return EnumSet.of(Characteristics.UNORDERED); } } /** * A collector that creates Entries of {@code <String, MapEntryValue>} and * creates a set of entries all key value pairs in the map. */ private class EntrySetCollector implements Collector<Map.Entry<String, MapEntryValue>, Set<Map.Entry<String, byte[]>>, Set<Map.Entry<String, byte[]>>> { private Set<Map.Entry<String, byte[]>> set = null; @Override public Supplier<Set<Map.Entry<String, byte[]>>> supplier() { return new Supplier<Set<Map.Entry<String, byte[]>>>() { @Override public Set<Map.Entry<String, byte[]>> get() { if (set == null) { set = Sets.newHashSet(); } return set; } }; } @Override public BiConsumer<Set<Map.Entry<String, byte[]>>, Map.Entry<String, MapEntryValue>> accumulator() { return (set, entry) -> { entry .getValue() .values() .forEach(byteValue -> set.add(Maps.immutableEntry(entry.getKey(), byteValue))); }; } @Override public BinaryOperator<Set<Map.Entry<String, byte[]>>> combiner() { return (setOne, setTwo) -> { setOne.addAll(setTwo); return setOne; }; } @Override public Function<Set<Map.Entry<String, byte[]>>, Set<Map.Entry<String, byte[]>>> finisher() { return (unused) -> set; } @Override public Set<Characteristics> characteristics() { return EnumSet.of(Characteristics.UNORDERED); } } /** * Utility for turning a {@code MapEntryValue} to {@code Versioned}. * @param value map entry value * @return versioned instance or an empty list versioned -1 if argument is * null */ private Versioned<Collection<? extends byte[]>> toVersioned( MapEntryValue value) { return value == null ? new Versioned<>(Lists.newArrayList(), -1) : new Versioned<>(value.values(), value.version()); } private class ByteArrayComparator implements Comparator<byte[]> { @Override public int compare(byte[] o1, byte[] o2) { if (Arrays.equals(o1, o2)) { return 0; } else { for (int i = 0; i < o1.length && i < o2.length; i++) { if (o1[i] < o2[i]) { return -1; } else if (o1[i] > o2[i]) { return 1; } } return o1.length > o2.length ? 1 : -1; } } } }
/******************************************************************************* * Copyright 2013 Thomas Letsch (contact@thomas-letsch.de) * * 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.moserp.inventory.domain; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import org.moserp.common.domain.EntityWithAuditInfo; import java.util.ArrayList; import java.util.List; @NoArgsConstructor @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class Delivery extends EntityWithAuditInfo { @Getter private List<DeliveryItem> items = new ArrayList<>(); public void add(DeliveryItem item) { items.add(item); } }
/* * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.apimgt.common.gateway.analytics.collectors.impl.fault; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.common.gateway.analytics.collectors.AnalyticsDataProvider; import org.wso2.carbon.apimgt.common.gateway.analytics.exceptions.AnalyticsException; import org.wso2.carbon.apimgt.common.gateway.analytics.publishers.RequestDataPublisher; import org.wso2.carbon.apimgt.common.gateway.analytics.publishers.dto.Application; import org.wso2.carbon.apimgt.common.gateway.analytics.publishers.dto.Event; import org.wso2.carbon.apimgt.common.gateway.analytics.publishers.dto.enums.FaultCategory; import org.wso2.carbon.apimgt.common.gateway.analytics.publishers.impl.FaultyRequestDataPublisher; /** * Faulty data collector for un classified request */ public class UnclassifiedFaultDataCollector extends AbstractFaultDataCollector { private static final Log log = LogFactory.getLog(UnclassifiedFaultDataCollector.class); private AnalyticsDataProvider provider; public UnclassifiedFaultDataCollector(AnalyticsDataProvider provider, FaultCategory subType, RequestDataPublisher processor) { super(provider, subType, processor); } public UnclassifiedFaultDataCollector(AnalyticsDataProvider provider) { this(provider, FaultCategory.OTHER, new FaultyRequestDataPublisher()); this.provider = provider; } @Override public void collectFaultData(Event faultyEvent) throws AnalyticsException { log.debug("handling unclassified failure analytics events"); Application application; if (provider.isAuthenticated()) { if (provider.isAnonymous()) { application = getAnonymousApp(); } else { application = provider.getApplication(); } } else { application = getUnknownApp(); } faultyEvent.setApplication(application); this.processRequest(faultyEvent); } }
/* * 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.pdfbox.examples.pdmodel; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont; /** * This is an example that creates a simple document * with a ttf-font. * * @author <a href="mailto:m.g.n@gmx.de">Michael Niedermair</a> * @version $Revision: 1.2 $ */ public class HelloWorldTTF { /** * create the second sample document from the PDF file format specification. * * @param file The file to write the PDF to. * @param message The message to write in the file. * @param fontfile The ttf-font file. * * @throws IOException If there is an error writing the data. */ public void doIt(final String file, final String message, final String fontfile) throws IOException { // the document PDDocument doc = null; try { doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDFont font = PDTrueTypeFont.loadTTF(doc, fontfile); PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700); contentStream.drawString(message); contentStream.endText(); contentStream.close(); doc.save(file); System.out.println(file + " created!"); } finally { if (doc != null) { doc.close(); } } } /** * This will create a hello world PDF document * with a ttf-font. * <br /> * see usage() for commandline * * @param args Command line arguments. */ public static void main(String[] args) { HelloWorldTTF app = new HelloWorldTTF(); try { if (args.length != 3) { app.usage(); } else { app.doIt(args[0], args[1], args[2]); } } catch (Exception e) { e.printStackTrace(); } } /** * This will print out a message telling how to use this example. */ private void usage() { System.err.println("usage: " + this.getClass().getName() + " <output-file> <Message> <ttf-file>"); } }
/********************************************************************************* * * * The MIT License (MIT) * * * * Copyright (c) 2015-2020 aoju.org and other 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.aoju.bus.http.accord; import org.aoju.bus.http.Builder; import javax.net.ssl.*; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ProtocolException; import java.net.UnknownServiceException; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.List; /** * 处理连接规范回退策略:当安全套接字连接由于握手/协议问题而失败时, * 可能会使用不同的协议重试连接。实例是有状态的,应该创建并用于单个连接尝试 * * @author Kimi Liu * @version 6.0.1 * @since JDK 1.8+ */ public final class ConnectionSelector { private final List<ConnectionSuite> connectionSuites; private int nextModeIndex; private boolean isFallbackPossible; private boolean isFallback; public ConnectionSelector(List<ConnectionSuite> connectionSuites) { this.nextModeIndex = 0; this.connectionSuites = connectionSuites; } /** * 根据{@link SSLSocket} 配置连接到指定的主机的信息{@link ConnectionSuite} * 返回{@link ConnectionSuite},不会返回{@code null} * * @param sslSocket ssl套接字 * @return 套接字连接的配置 * @throws IOException 如果套接字不支持任何可用的TLS模式 */ public ConnectionSuite configureSecureSocket(SSLSocket sslSocket) throws IOException { ConnectionSuite tlsConfiguration = null; for (int i = nextModeIndex, size = connectionSuites.size(); i < size; i++) { ConnectionSuite connectionSuite = connectionSuites.get(i); if (connectionSuite.isCompatible(sslSocket)) { tlsConfiguration = connectionSuite; nextModeIndex = i + 1; break; } } if (tlsConfiguration == null) { // 这可能是第一次尝试连接,而套接字不支持任何必需的协议 // 或者可能是重试(但此套接字支持的协议比先前的套接字所建议的少) throw new UnknownServiceException( "Unable to find acceptable protocols. isFallback=" + isFallback + ", modes=" + connectionSuites + ", supported protocols=" + Arrays.toString(sslSocket.getEnabledProtocols())); } isFallbackPossible = isFallbackPossible(sslSocket); Builder.instance.apply(tlsConfiguration, sslSocket, isFallback); return tlsConfiguration; } /** * 报告连接失败。确定下一个要尝试的{@link ConnectionSuite}(如果有的话) * * @param ex 异常信息 * @return 如果需要使用 {@link #configureSecureSocket(SSLSocket)} 或{@code false}重试连接, * 则为{@code true};如果不需要重试连接,则为{@link #configureSecureSocket(SSLSocket)}或{@code false} */ public boolean connectionFailed(IOException ex) { // 未来使用此策略进行连接的任何尝试都将是一次回退尝试 isFallback = true; if (!isFallbackPossible) { return false; } // 如果有协议问题,不会恢复. if (ex instanceof ProtocolException) { return false; } // 如果出现中断或超时(SocketTimeoutException),则不进行恢复。对于套接字连接超时情况, // 我们不会使用不同的ConnectionSpec尝试相同的主机:认为通讯是不可到达的 if (ex instanceof InterruptedIOException) { return false; } // 查找已知的客户端或协商错误,这些错误不太可能通过再次尝试使用不同的连接规范来修复 if (ex instanceof SSLHandshakeException) { // 如果问题是来自X509TrustManager的一个证书异常,那么不会重试. if (ex.getCause() instanceof CertificateException) { return false; } } if (ex instanceof SSLPeerUnverifiedException) { // 例如,证书未经许可的错误. return false; } // 在Android上,SSLProtocolExceptions可能由TLS_FALLBACK_SCSV失败引起, // 这意味着我们在可能不应该重试的时候重试 return (ex instanceof SSLHandshakeException || ex instanceof SSLProtocolException || ex instanceof SSLException); } /** * 如果根据提供的{@link SSLSocket},回退策略中的任何后面的{@link ConnectionSuite} * 看起来都是可能的,则返回{@code true}。假设具有与提供的套接字相同的功能 */ private boolean isFallbackPossible(SSLSocket socket) { for (int i = nextModeIndex; i < connectionSuites.size(); i++) { if (connectionSuites.get(i).isCompatible(socket)) { return true; } } return false; } }
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.skipper.server.index; import org.springframework.cloud.skipper.domain.PackageMetadata; import org.springframework.cloud.skipper.server.controller.PackageController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.server.RepresentationModelProcessor; import org.springframework.stereotype.Component; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; /** * @author Mark Pollack * @author Ilayaperumal Gopinathan */ @Component public class PackageMetadataResourceProcessor implements RepresentationModelProcessor<EntityModel<PackageMetadata>> { @Override public EntityModel<PackageMetadata> process(EntityModel<PackageMetadata> packageMetadataResource) { Link installLink = linkTo( methodOn(PackageController.class).install(packageMetadataResource.getContent().getId(), null)) .withRel("install"); packageMetadataResource.add(installLink); return packageMetadataResource; } }
/******************************************************************************* * Copyright -2018 @Emotome * * 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.tjs.common.validation; import java.util.HashMap; import java.util.Map; import com.tjs.common.enums.EnumType; /** * Types of data type. * @author Nirav.Shah * @since 09/08/2018 */ public enum DataType implements EnumType{ INT(1, "Int") , STRING(2, "String"), DATE(3, "Date"), FLOAT(5, "Float"), LONG(6, "Long"), TIME(7, "Time"), BOOLEAN(8,"Boolean"); private final int id; private final String name; private static Map<Integer, DataType> MAP = new HashMap<>(); DataType(int id, String name) { this.id = id; this.name = name; } static{ for(DataType dataType : values()){ MAP.put(dataType.getId(), dataType); } } @Override public int getId() { return id; } @Override public String getName() { return name; } /** * This methods is used to fetch Enum base on given id. * @param id enum key * @return DataType enum */ public static DataType getFromId(int id) { return MAP.get(id); } }
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php * * 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.android.ide.eclipse.adt.internal.editors.layout.gle2; import static com.android.SdkConstants.ANDROID_LAYOUT_RESOURCE_PREFIX; import static com.android.SdkConstants.ANDROID_URI; import static com.android.SdkConstants.ATTR_CLASS; import static com.android.SdkConstants.ATTR_NAME; import static com.android.SdkConstants.LAYOUT_RESOURCE_PREFIX; import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutMetadata.KEY_FRAGMENT_LAYOUT; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.ide.eclipse.adt.AdtPlugin; import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate; import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode; import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper; import com.android.ide.eclipse.adt.internal.resources.CyclicDependencyValidator; import com.android.ide.eclipse.adt.internal.ui.ResourceChooser; import com.android.resources.ResourceType; import com.android.utils.Pair; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.Separator; import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Menu; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.util.ArrayList; import java.util.List; /** * Fragment context menu allowing a layout to be chosen for previewing in the fragment frame. */ public class FragmentMenu extends SubmenuAction { private static final String R_LAYOUT_RESOURCE_PREFIX = "R.layout."; //$NON-NLS-1$ private static final String ANDROID_R_PREFIX = "android.R.layout"; //$NON-NLS-1$ /** Associated canvas */ private final LayoutCanvas mCanvas; /** * Creates a "Preview Fragment" menu * * @param canvas associated canvas */ public FragmentMenu(LayoutCanvas canvas) { super("Fragment Layout"); mCanvas = canvas; } @Override protected void addMenuItems(Menu menu) { IAction action = new PickLayoutAction("Choose Layout..."); new ActionContributionItem(action).fill(menu, -1); SelectionManager selectionManager = mCanvas.getSelectionManager(); List<SelectionItem> selections = selectionManager.getSelections(); if (selections.size() == 0) { return; } SelectionItem first = selections.get(0); UiViewElementNode node = first.getViewInfo().getUiViewNode(); if (node == null) { return; } Element element = (Element) node.getXmlNode(); String selected = getSelectedLayout(); if (selected != null) { if (selected.startsWith(ANDROID_LAYOUT_RESOURCE_PREFIX)) { selected = selected.substring(ANDROID_LAYOUT_RESOURCE_PREFIX.length()); } } String fqcn = getFragmentClass(element); if (fqcn != null) { // Look up the corresponding activity class and try to figure out // which layouts it is referring to and list these here as reasonable // guesses IProject project = mCanvas.getEditorDelegate().getEditor().getProject(); String source = null; try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); IType type = javaProject.findType(fqcn); if (type != null) { source = type.getSource(); } } catch (CoreException e) { AdtPlugin.log(e, null); } // Find layouts. This is based on just skimming the Fragment class and looking // for layout references of the form R.layout.*. if (source != null) { String self = mCanvas.getLayoutResourceName(); // Pair of <title,layout> to be displayed to the user List<Pair<String, String>> layouts = new ArrayList<Pair<String, String>>(); if (source.contains("extends ListFragment")) { //$NON-NLS-1$ layouts.add(Pair.of("list_content", //$NON-NLS-1$ "@android:layout/list_content")); //$NON-NLS-1$ } int index = 0; while (true) { index = source.indexOf(R_LAYOUT_RESOURCE_PREFIX, index); if (index == -1) { break; } else { index += R_LAYOUT_RESOURCE_PREFIX.length(); int end = index; while (end < source.length()) { char c = source.charAt(end); if (!Character.isJavaIdentifierPart(c)) { break; } end++; } if (end > index) { String title = source.substring(index, end); String layout; // Is this R.layout part of an android.R.layout? int len = ANDROID_R_PREFIX.length() + 1; // prefix length to check if (index > len && source.startsWith(ANDROID_R_PREFIX, index - len)) { layout = ANDROID_LAYOUT_RESOURCE_PREFIX + title; } else { layout = LAYOUT_RESOURCE_PREFIX + title; } if (!self.equals(title)) { layouts.add(Pair.of(title, layout)); } } } index++; } if (layouts.size() > 0) { new Separator().fill(menu, -1); for (Pair<String, String> layout : layouts) { action = new SetFragmentLayoutAction(layout.getFirst(), layout.getSecond(), selected); new ActionContributionItem(action).fill(menu, -1); } } } } if (selected != null) { new Separator().fill(menu, -1); action = new SetFragmentLayoutAction("Clear", null, null); new ActionContributionItem(action).fill(menu, -1); } } /** * Returns the class name of the fragment associated with the given {@code <fragment>} * element. * * @param element the element for the fragment tag * @return the fully qualified fragment class name, or null */ @Nullable public static String getFragmentClass(@NonNull Element element) { String fqcn = element.getAttribute(ATTR_CLASS); if (fqcn == null || fqcn.length() == 0) { fqcn = element.getAttributeNS(ANDROID_URI, ATTR_NAME); } if (fqcn != null && fqcn.length() > 0) { return fqcn; } else { return null; } } /** * Returns the layout to be shown for the given {@code <fragment>} node. * * @param node the node corresponding to the {@code <fragment>} element * @return the resource path to a layout to render for this fragment, or null */ @Nullable public static String getFragmentLayout(@NonNull Node node) { String layout = LayoutMetadata.getProperty( node, LayoutMetadata.KEY_FRAGMENT_LAYOUT); if (layout != null) { return layout; } return null; } /** Returns the name of the currently displayed layout in the fragment, or null */ @Nullable private String getSelectedLayout() { SelectionManager selectionManager = mCanvas.getSelectionManager(); for (SelectionItem item : selectionManager.getSelections()) { UiViewElementNode node = item.getViewInfo().getUiViewNode(); if (node != null) { String layout = getFragmentLayout(node.getXmlNode()); if (layout != null) { return layout; } } } return null; } /** * Set the given layout as the new fragment layout * * @param layout the layout resource name to show in this fragment */ public void setNewLayout(@Nullable String layout) { LayoutEditorDelegate delegate = mCanvas.getEditorDelegate(); GraphicalEditorPart graphicalEditor = delegate.getGraphicalEditor(); SelectionManager selectionManager = mCanvas.getSelectionManager(); for (SelectionItem item : selectionManager.getSnapshot()) { UiViewElementNode node = item.getViewInfo().getUiViewNode(); if (node != null) { Node xmlNode = node.getXmlNode(); LayoutMetadata.setProperty(delegate.getEditor(), xmlNode, KEY_FRAGMENT_LAYOUT, layout); } } // Refresh graphicalEditor.recomputeLayout(); mCanvas.redraw(); } /** Action to set the given layout as the new layout in a fragment */ private class SetFragmentLayoutAction extends Action { private final String mLayout; public SetFragmentLayoutAction(String title, String layout, String selected) { super(title, IAction.AS_RADIO_BUTTON); mLayout = layout; if (layout != null && layout.equals(selected)) { setChecked(true); } } @Override public void run() { if (isChecked()) { setNewLayout(mLayout); } } } /** * Action which brings up the "Create new XML File" wizard, pre-selected with the * animation category */ private class PickLayoutAction extends Action { public PickLayoutAction(String title) { super(title, IAction.AS_PUSH_BUTTON); } @Override public void run() { LayoutEditorDelegate delegate = mCanvas.getEditorDelegate(); IFile file = delegate.getEditor().getInputFile(); GraphicalEditorPart editor = delegate.getGraphicalEditor(); ResourceChooser dlg = ResourceChooser.create(editor, ResourceType.LAYOUT) .setInputValidator(CyclicDependencyValidator.create(file)) .setInitialSize(85, 10) .setCurrentResource(getSelectedLayout()); int result = dlg.open(); if (result == ResourceChooser.CLEAR_RETURN_CODE) { setNewLayout(null); } else if (result == Window.OK) { String newType = dlg.getCurrentResource(); setNewLayout(newType); } } } }
package org.folio.circulation.domain; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.folio.circulation.domain.RequestFulfilmentPreference.DELIVERY; import static org.folio.circulation.domain.RequestFulfilmentPreference.HOLD_SHELF; import static org.folio.circulation.domain.RequestStatus.CLOSED_CANCELLED; import static org.folio.circulation.domain.RequestStatus.CLOSED_FILLED; import static org.folio.circulation.domain.RequestStatus.CLOSED_PICKUP_EXPIRED; import static org.folio.circulation.domain.RequestStatus.CLOSED_UNFILLED; import static org.folio.circulation.domain.RequestStatus.OPEN_AWAITING_PICKUP; import static org.folio.circulation.domain.RequestStatus.OPEN_IN_TRANSIT; import static org.folio.circulation.domain.RequestStatus.OPEN_NOT_YET_FILLED; import static org.folio.circulation.domain.representations.RequestProperties.CANCELLATION_ADDITIONAL_INFORMATION; import static org.folio.circulation.domain.representations.RequestProperties.CANCELLATION_REASON_ID; import static org.folio.circulation.domain.representations.RequestProperties.CANCELLATION_REASON_NAME; import static org.folio.circulation.domain.representations.RequestProperties.CANCELLATION_REASON_PUBLIC_DESCRIPTION; import static org.folio.circulation.domain.representations.RequestProperties.HOLD_SHELF_EXPIRATION_DATE; import static org.folio.circulation.domain.representations.RequestProperties.ITEM_ID; import static org.folio.circulation.domain.representations.RequestProperties.POSITION; import static org.folio.circulation.domain.representations.RequestProperties.REQUEST_DATE; import static org.folio.circulation.domain.representations.RequestProperties.REQUEST_EXPIRATION_DATE; import static org.folio.circulation.domain.representations.RequestProperties.REQUEST_TYPE; import static org.folio.circulation.domain.representations.RequestProperties.STATUS; import static org.folio.circulation.support.json.JsonPropertyFetcher.getDateTimeProperty; import static org.folio.circulation.support.json.JsonPropertyFetcher.getIntegerProperty; import static org.folio.circulation.support.json.JsonPropertyFetcher.getProperty; import static org.folio.circulation.support.json.JsonPropertyWriter.write; import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import io.vertx.core.json.JsonObject; import lombok.AllArgsConstructor; @AllArgsConstructor public class Request implements ItemRelatedRecord, UserRelatedRecord { private final JsonObject requestRepresentation; private final JsonObject cancellationReasonRepresentation; private final Item item; private final User requester; private final User proxy; private final AddressType addressType; private final Loan loan; private final ServicePoint pickupServicePoint; private boolean changedPosition; private Integer previousPosition; public static Request from(JsonObject representation) { return new Request(representation, null, null, null, null, null, null, null, false, null); } public Request withRequestJsonRepresentation(JsonObject representation) { return new Request(representation, cancellationReasonRepresentation, getItem(), getRequester(), getProxy(), getAddressType(), getLoan(), getPickupServicePoint(), hasChangedPosition(), getPreviousPosition()); } public Request withCancellationReasonJsonRepresentation(JsonObject representation) { return new Request(requestRepresentation, representation, getItem(), getRequester(), getProxy(), getAddressType(), getLoan(), getPickupServicePoint(), hasChangedPosition(), getPreviousPosition()); } public JsonObject asJson() { return requestRepresentation.copy(); } boolean isFulfillable() { return getFulfilmentPreference() == HOLD_SHELF || getFulfilmentPreference() == DELIVERY; } public boolean isOpen() { return isAwaitingPickup() || isNotYetFilled() || isInTransit(); } private boolean isInTransit() { return getStatus() == OPEN_IN_TRANSIT; } private boolean isNotYetFilled() { return getStatus() == OPEN_NOT_YET_FILLED; } boolean isCancelled() { return getStatus() == CLOSED_CANCELLED; } private boolean isFulfilled() { return getStatus() == CLOSED_FILLED; } private boolean isUnfilled() { return getStatus() == CLOSED_UNFILLED; } private boolean isPickupExpired() { return getStatus() == CLOSED_PICKUP_EXPIRED; } public boolean isClosed() { return isCancelled() || isFulfilled() || isUnfilled() || isPickupExpired(); } boolean isAwaitingPickup() { return getStatus() == OPEN_AWAITING_PICKUP; } boolean isFor(User user) { return StringUtils.equals(getUserId(), user.getId()); } @Override public String getItemId() { return requestRepresentation.getString(ITEM_ID); } public Request withItem(Item newItem) { // NOTE: this is null in RequestsAPIUpdatingTests.replacingAnExistingRequestRemovesItemInformationWhenItemDoesNotExist test if (newItem.getItemId() != null) { requestRepresentation.put(ITEM_ID, newItem.getItemId()); } return new Request(requestRepresentation, cancellationReasonRepresentation, newItem, requester, proxy, addressType, loan == null ? null : loan.withItem(newItem), pickupServicePoint, changedPosition, previousPosition); } public Request withRequester(User newRequester) { return new Request(requestRepresentation, cancellationReasonRepresentation, item, newRequester, proxy, addressType, loan, pickupServicePoint, changedPosition, previousPosition); } public Request withProxy(User newProxy) { return new Request(requestRepresentation, cancellationReasonRepresentation, item, requester, newProxy, addressType, loan, pickupServicePoint, changedPosition, previousPosition); } public Request withAddressType(AddressType addressType) { return new Request(requestRepresentation, cancellationReasonRepresentation, item, requester, proxy, addressType, loan, pickupServicePoint, changedPosition, previousPosition); } public Request withLoan(Loan newLoan) { return new Request(requestRepresentation, cancellationReasonRepresentation, item, requester, proxy, addressType, newLoan, pickupServicePoint, changedPosition, previousPosition); } public Request withPickupServicePoint(ServicePoint newPickupServicePoint) { return new Request(requestRepresentation, cancellationReasonRepresentation, item, requester, proxy, addressType, loan, newPickupServicePoint, changedPosition, previousPosition ); } @Override public String getUserId() { return requestRepresentation.getString("requesterId"); } @Override public String getProxyUserId() { return requestRepresentation.getString("proxyUserId"); } private String getFulfilmentPreferenceName() { return requestRepresentation.getString("fulfilmentPreference"); } public RequestFulfilmentPreference getFulfilmentPreference() { return RequestFulfilmentPreference.from(getFulfilmentPreferenceName()); } public String getId() { return requestRepresentation.getString("id"); } public RequestType getRequestType() { return RequestType.from(getProperty(requestRepresentation, REQUEST_TYPE)); } boolean allowedForItem() { return RequestTypeItemStatusWhiteList.canCreateRequestForItem(getItem().getStatus(), getRequestType()); } LoanAction actionOnCreateOrUpdate() { return getRequestType().toLoanAction(); } public RequestStatus getStatus() { return RequestStatus.from(requestRepresentation.getString(STATUS)); } void changeStatus(RequestStatus status) { status.writeTo(requestRepresentation); } Request withRequestType(RequestType type) { requestRepresentation.put(REQUEST_TYPE, type.getValue()); return this; } public Item getItem() { return item; } public Loan getLoan() { return loan; } public User getRequester() { return requester; } public JsonObject getRequesterFromRepresentation() { return requestRepresentation.getJsonObject("requester"); } public String getRequesterBarcode() { return getRequesterFromRepresentation().getString("barcode", EMPTY); } public User getProxy() { return proxy; } public AddressType getAddressType() { return addressType; } public String getPickupServicePointId() { return requestRepresentation.getString("pickupServicePointId"); } public ServicePoint getPickupServicePoint() { return pickupServicePoint; } void changePosition(Integer newPosition) { Integer prevPosition = getPosition(); if (!Objects.equals(prevPosition, newPosition)) { previousPosition = prevPosition; write(requestRepresentation, POSITION, newPosition); changedPosition = true; } } void removePosition() { previousPosition = getPosition(); requestRepresentation.remove(POSITION); changedPosition = true; } public Integer getPosition() { return getIntegerProperty(requestRepresentation, POSITION, null); } public boolean hasChangedPosition() { return changedPosition; } public Integer getPreviousPosition() { return previousPosition; } ItemStatus checkedInItemStatus() { return getFulfilmentPreference().toCheckedInItemStatus(); } public String getDeliveryAddressTypeId() { return requestRepresentation.getString("deliveryAddressTypeId"); } void changeHoldShelfExpirationDate(DateTime holdShelfExpirationDate) { write(requestRepresentation, HOLD_SHELF_EXPIRATION_DATE, holdShelfExpirationDate); } void removeHoldShelfExpirationDate() { requestRepresentation.remove(HOLD_SHELF_EXPIRATION_DATE); } public DateTime getRequestDate() { return getDateTimeProperty(requestRepresentation, REQUEST_DATE); } public DateTime getHoldShelfExpirationDate() { return getDateTimeProperty(requestRepresentation, HOLD_SHELF_EXPIRATION_DATE); } public DateTime getRequestExpirationDate() { return getDateTimeProperty(requestRepresentation, REQUEST_EXPIRATION_DATE); } public String getCancellationAdditionalInformation() { return getProperty(requestRepresentation, CANCELLATION_ADDITIONAL_INFORMATION); } public String getCancellationReasonId() { return getProperty(requestRepresentation, CANCELLATION_REASON_ID); } public String getCancellationReasonName() { return getProperty(cancellationReasonRepresentation, CANCELLATION_REASON_NAME); } public String getCancellationReasonPublicDescription() { return getProperty(cancellationReasonRepresentation, CANCELLATION_REASON_PUBLIC_DESCRIPTION); } public Request copy() { return withRequestJsonRepresentation(requestRepresentation.copy()); } public String getPatronComments() { return getProperty(requestRepresentation, "patronComments"); } }
package com.sjet.auracascade.client.particles.pumptransferparticle; import net.minecraft.client.particle.IAnimatedSprite; import net.minecraft.client.particle.IParticleRenderType; import net.minecraft.client.particle.SpriteTexturedParticle; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; public class PumpTransferParticle extends SpriteTexturedParticle { private double sourceX; private double sourceY; private double sourceZ; private double targetX; private double targetY; private double targetZ; private IAnimatedSprite spriteSet; public PumpTransferParticle(World world, double sourceX, double sourceY, double sourceZ, double targetX, double targetY, double targetZ, double xSpeed, double ySpeed, double zSpeed, float size, float maxAge, IAnimatedSprite spriteSet) { super(world, sourceX, sourceY, sourceZ); motionX = xSpeed * 0.14; motionY = ySpeed * 0.14; motionZ = zSpeed * 0.14; setColor(0.3F, 0.8F, 1F); particleGravity = 0; this.maxAge = Math.round(maxAge); this.particleScale = size; setSize(size, size); prevPosX = posX; prevPosY = posY; prevPosZ = posZ; this.sourceX = sourceX; this.sourceY = sourceY; this.sourceZ = sourceZ; this.targetX = targetX; this.targetY = targetY; this.targetZ = targetZ; this.canCollide = false; this.spriteSet = spriteSet; } @Override public IParticleRenderType getRenderType() { return IParticleRenderType.PARTICLE_SHEET_TRANSLUCENT; } @Override public void tick() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; //Get the current position and target of the particle Vec3d particlePosition = new Vec3d(this.posX, this.posY, this.posZ); Vec3d targetPosition = new Vec3d(targetX, targetY, targetZ); //The total distance between the particle and target double totalDistance = targetPosition.distanceTo(particlePosition); if (this.age++ >= this.maxAge) { this.setExpired(); } else if (totalDistance < 0.2) { this.setExpired(); } else { this.move(this.motionX, this.motionY, this.motionZ); //randomly age the particle this.age += (rand.nextFloat() > 0.5 ? 0 : 1); } } }
package com.ducetech.shiro; import java.util.List; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.ducetech.framework.model.User; import com.ducetech.framework.service.UserService; public class AuthRealm extends AuthorizingRealm { private static Logger logger = LoggerFactory.getLogger(AuthRealm.class); @Autowired private UserService userService; // 调用业务系统的Service,按登录名查询某个用户User // 授权 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 获取当前用户 User curUser = (User) principals.fromRealm(getName()).iterator().next(); // 获取当前用户的权限串 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); List<String> permissions = userService.getUserPermission(curUser.getUserId()); authorizationInfo.addStringPermissions(permissions); // 直接添加List<String> return authorizationInfo; } // 认证 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 拿到用户录入的用户名密码 // 调用userService的方法,获取当前对象 UsernamePasswordToken userToken = (UsernamePasswordToken) token; User _user = userService.getUserByLoginName(userToken.getUsername()); if (_user == null) { logger.info("User为空!"); return null; } else { // getName,shiro可以有多个realm,告诉底层具体是哪一个realm AuthenticationInfo info = new SimpleAuthenticationInfo(_user,_user.getPassword(), getName()); return info; // 登录成功 } } }
package sz.automat.core.support.scheduler; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import sz.automat.core.exception.BusinessException; import sz.automat.core.support.scheduler.TaskScheduled.JobType; import sz.automat.core.support.scheduler.TaskScheduled.TaskType; import sz.automat.core.support.scheduler.job.BaseJob; import sz.automat.core.support.scheduler.job.StatefulJob; import sz.automat.core.util.DataUtil; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.JobListener; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.Trigger.TriggerState; import org.quartz.TriggerBuilder; import org.quartz.TriggerKey; import org.quartz.impl.matchers.GroupMatcher; import org.springframework.beans.factory.InitializingBean; /** * 默认的定时任务管理器 * * @author * @version 2016年5月27日 上午10:28:26 */ public class SchedulerManager implements InitializingBean { private Logger logger = LogManager.getLogger(this.getClass()); private Scheduler scheduler; private List<JobListener> jobListeners; public void setScheduler(Scheduler scheduler) { this.scheduler = scheduler; } public void setJobListeners(List<JobListener> jobListeners) { this.jobListeners = jobListeners; } public void afterPropertiesSet() throws Exception { if (this.jobListeners != null && this.jobListeners.size() > 0) { if (logger.isInfoEnabled()) { logger.info("Initing task scheduler[" + this.scheduler.getSchedulerName() + "] , add listener size :" + this.jobListeners.size()); } for (JobListener listener : this.jobListeners) { if (logger.isInfoEnabled()) { logger.info("Add JobListener : " + listener.getName()); } this.scheduler.getListenerManager().addJobListener(listener); } } } public List<TaskScheduled> getAllJobDetail() { List<TaskScheduled> result = new LinkedList<TaskScheduled>(); try { GroupMatcher<JobKey> matcher = GroupMatcher.jobGroupContains(""); Set<JobKey> jobKeys = scheduler.getJobKeys(matcher); for (JobKey jobKey : jobKeys) { JobDetail jobDetail = scheduler.getJobDetail(jobKey); List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey); for (Trigger trigger : triggers) { TaskScheduled job = new TaskScheduled(); job.setTaskName(jobKey.getName()); job.setTaskGroup(jobKey.getGroup()); TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); job.setStatus(triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger)trigger; String cronExpression = cronTrigger.getCronExpression(); job.setTaskCron(cronExpression); } job.setPreviousFireTime(trigger.getPreviousFireTime()); job.setNextFireTime(trigger.getNextFireTime()); JobDataMap jobDataMap = trigger.getJobDataMap(); job.setTaskType(jobDataMap.getString("taskType")); job.setTargetSystem(jobDataMap.getString("targetSystem")); job.setTargetObject(jobDataMap.getString("targetObject")); job.setTargetMethod(jobDataMap.getString("targetMethod")); job.setContactName(jobDataMap.getString("contactName")); job.setContactEmail(jobDataMap.getString("contactEmail")); job.setTaskDesc(jobDetail.getDescription()); String jobClass = jobDetail.getJobClass().getSimpleName(); if (jobClass.equals("StatefulJob")) { job.setJobType("statefulJob"); } else if (jobClass.equals("DefaultJob")) { job.setJobType("job"); } result.add(job); } } } catch (Exception e) { logger.error("Try to load All JobDetail cause error : ", e); } return result; } public JobDetail getJobDetailByTriggerName(Trigger trigger) { try { return this.scheduler.getJobDetail(trigger.getJobKey()); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; } /** * 新增job * * @param inputObject * @param outputObject * @throws Exception */ public boolean updateTask(TaskScheduled taskScheduled) { String jobGroup = taskScheduled.getTaskGroup(); if (DataUtil.isEmpty(jobGroup)) { jobGroup = "ds_job"; } String jobName = taskScheduled.getTaskName(); if (DataUtil.isEmpty(jobName)) { jobName = String.valueOf(System.currentTimeMillis()); } String cronExpression = taskScheduled.getTaskCron(); String targetObject = taskScheduled.getTargetObject(); String targetMethod = taskScheduled.getTargetMethod(); String jobDescription = taskScheduled.getTaskDesc(); String jobType = taskScheduled.getJobType(); String taskType = taskScheduled.getTaskType(); JobDataMap jobDataMap = new JobDataMap(); if (TaskType.dubbo.equals(taskType)) { jobDataMap.put("targetSystem", taskScheduled.getTargetSystem()); } jobDataMap.put("targetObject", targetObject); jobDataMap.put("targetMethod", targetMethod); jobDataMap.put("taskType", taskType); jobDataMap.put("contactName", taskScheduled.getContactName()); jobDataMap.put("contactEmail", taskScheduled.getContactEmail()); JobBuilder jobBuilder = null; if (JobType.job.equals(jobType)) { jobBuilder = JobBuilder.newJob(BaseJob.class); } else if (JobType.statefulJob.equals(jobType)) { jobBuilder = JobBuilder.newJob(StatefulJob.class); } if (jobBuilder != null) { JobDetail jobDetail = jobBuilder.withIdentity(jobName, jobGroup).withDescription(jobDescription) .storeDurably(true).usingJobData(jobDataMap).build(); Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) .withIdentity(jobName, jobGroup).withDescription(jobDescription).forJob(jobDetail) .usingJobData(jobDataMap).build(); try { JobDetail detail = scheduler.getJobDetail(new JobKey(jobName, jobGroup)); if (detail == null) { scheduler.scheduleJob(jobDetail, trigger); } else { scheduler.addJob(jobDetail, true); scheduler.rescheduleJob(new TriggerKey(jobName, jobGroup), trigger); } return true; } catch (SchedulerException e) { logger.error("SchedulerException", "SchedulerException", e); throw new BusinessException(e); } } return false; } /** * 暂停所有触发器 * * @return */ public void pauseAllTrigger() { try { scheduler.standby(); } catch (SchedulerException e) { logger.error("SchedulerException", "SchedulerException", e); throw new BusinessException(e); } } /** * 启动所有触发器 * * @return */ public void startAllTrigger() { try { if (scheduler.isInStandbyMode()) { scheduler.start(); } } catch (SchedulerException e) { logger.error("SchedulerException", "SchedulerException", e); throw new BusinessException(e); } } // 暂停任务 public void stopJob(TaskScheduled scheduleJob) { try { JobKey jobKey = JobKey.jobKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup()); scheduler.pauseJob(jobKey); } catch (Exception e) { logger.error("Try to stop Job cause error : ", e); throw new BusinessException(e); } } // 启动任务 public void resumeJob(TaskScheduled scheduleJob) { try { JobKey jobKey = JobKey.jobKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup()); scheduler.resumeJob(jobKey); } catch (Exception e) { logger.error("Try to resume Job cause error : ", e); throw new BusinessException(e); } } // 执行任务 public void runJob(TaskScheduled scheduleJob) { try { JobKey jobKey = JobKey.jobKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup()); scheduler.triggerJob(jobKey); } catch (Exception e) { logger.error("Try to resume Job cause error : ", e); throw new BusinessException(e); } } // 删除任务 public void delJob(TaskScheduled scheduleJob) { try { JobKey jobKey = JobKey.jobKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup()); TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup()); scheduler.pauseTrigger(triggerKey);// 停止触发器 scheduler.unscheduleJob(triggerKey);// 移除触发器 scheduler.deleteJob(jobKey);// 删除任务 } catch (Exception e) { logger.error("Try to resume Job cause error : ", e); throw new BusinessException(e); } } }
package com.hhl.library; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Rect; import android.util.AttributeSet; import android.util.SparseBooleanArray; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 流式标签布局 * 原理:重写{@link ViewGroup#onMeasure(int, int)} * 和{@link ViewGroup#onLayout(boolean, int, int, int, int)} * 方法 * Created by HanHailong on 15/10/19. */ public class FlowTagLayout extends ViewGroup { private static final String TAG = FlowTagLayout.class.getSimpleName(); /** * FlowLayout not support checked */ public static final int FLOW_TAG_CHECKED_NONE = 0; /** * FlowLayout support single-select */ public static final int FLOW_TAG_CHECKED_SINGLE = 1; /** * FlowLayout support multi-select */ public static final int FLOW_TAG_CHECKED_MULTI = 2; /** * Should be used by subclasses to listen to changes in the dataset */ AdapterDataSetObserver mDataSetObserver; /** * The adapter containing the data to be displayed by this view */ ListAdapter mAdapter; /** * the tag click event callback */ OnTagClickListener mOnTagClickListener; /** * the tag select event callback */ OnTagSelectListener mOnTagSelectListener; /** * 标签流式布局选中模式,默认是不支持选中的 */ private int mTagCheckMode = FLOW_TAG_CHECKED_NONE; /** * 存储选中的tag */ private SparseBooleanArray mCheckedTagArray = new SparseBooleanArray(); /** * 用来保存计算好的子view的位置 */ List<Rect> mChildrenBounds = new ArrayList<>(); public FlowTagLayout(Context context) { super(context); } public FlowTagLayout(Context context, AttributeSet attrs) { super(context, attrs); } public FlowTagLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //获取Padding // 获得它的父容器为它设置的测量模式和大小 int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec); //FlowLayout最终的宽度和高度值 int resultWidth = 0; int resultHeight = 0; //测量时每一行的宽度 int lineWidth = 0; //测量时每一行的高度,加起来就是FlowLayout的高度 int lineHeight = 0; //遍历每个子元素 for (int i = 0, childCount = getChildCount(); i < childCount; i++) { View childView = getChildAt(i); //测量每一个子view的宽和高 measureChildWithMargins(childView, widthMeasureSpec, 0, heightMeasureSpec, resultHeight); //获取到测量的宽和高 int childWidth = childView.getMeasuredWidth(); int childHeight = childView.getMeasuredHeight(); Rect childBound; if (mChildrenBounds.size() <= i) { childBound = new Rect(); mChildrenBounds.add(childBound); } else { childBound = mChildrenBounds.get(i); } //如果当前一行的宽度加上要加入的子view的宽度大于父容器给的宽度,就换行 if ((lineWidth + childWidth) > sizeWidth) { childBound.set(0, resultHeight, childWidth, resultHeight + childHeight); //换行 resultWidth = Math.max(lineWidth, childWidth); resultHeight += childHeight; //换行了,lineWidth和lineHeight重新算 lineWidth = childWidth; lineHeight = childHeight; } else { //不换行,直接相加 lineWidth += childWidth; //每一行的高度取二者最大值 lineHeight = Math.max(lineHeight, childHeight); resultWidth = Math.max(lineWidth, resultWidth); //遍历第一个的时候,肯定走的是不换行 resultHeight = Math.max(lineHeight, resultHeight); childBound.set(lineWidth - childWidth, resultHeight - childHeight, lineWidth, resultHeight); } } setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : resultWidth, modeHeight == MeasureSpec.EXACTLY ? sizeHeight : resultHeight); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); Rect childBounds = mChildrenBounds.get(i); child.layout(childBounds.left, childBounds.top, childBounds.right, childBounds.bottom); } } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } public ListAdapter getAdapter() { return mAdapter; } class AdapterDataSetObserver extends DataSetObserver { @Override public void onChanged() { super.onChanged(); reloadData(); } @Override public void onInvalidated() { super.onInvalidated(); } } /** * 重新加载刷新数据 */ private void reloadData() { removeAllViews(); boolean isSetted = false; for (int i = 0; i < mAdapter.getCount(); i++) { final int j = i; mCheckedTagArray.put(i, false); final View childView = mAdapter.getView(i, null, this); // addView(childView, // new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));//这个构造方法所然能使用但是编译器会报错 addView(childView, new MarginLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))); if (mAdapter instanceof OnInitSelectedPosition) { boolean isSelected = ((OnInitSelectedPosition) mAdapter).isSelectedPosition(i); //判断一下模式 if (mTagCheckMode == FLOW_TAG_CHECKED_SINGLE) { //单选只有第一个起作用 if (isSelected && !isSetted) { mCheckedTagArray.put(i, true); childView.setSelected(true); isSetted = true; } } else if (mTagCheckMode == FLOW_TAG_CHECKED_MULTI) { if (isSelected) { mCheckedTagArray.put(i, true); childView.setSelected(true); } } } childView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mTagCheckMode == FLOW_TAG_CHECKED_NONE) { if (mOnTagClickListener != null) { mOnTagClickListener.onItemClick(FlowTagLayout.this, childView, j); } } else if (mTagCheckMode == FLOW_TAG_CHECKED_SINGLE) { //判断状态 if (mCheckedTagArray.get(j)) { mCheckedTagArray.put(j, false); childView.setSelected(false); if (mOnTagSelectListener != null) { mOnTagSelectListener.onItemSelect(FlowTagLayout.this, new ArrayList<Integer>()); } return; } for (int k = 0; k < mAdapter.getCount(); k++) { mCheckedTagArray.put(k, false); getChildAt(k).setSelected(false); } mCheckedTagArray.put(j, true); childView.setSelected(true); if (mOnTagSelectListener != null) { mOnTagSelectListener.onItemSelect(FlowTagLayout.this, Arrays.asList(j)); } } else if (mTagCheckMode == FLOW_TAG_CHECKED_MULTI) { if (mCheckedTagArray.get(j)) { mCheckedTagArray.put(j, false); childView.setSelected(false); } else { mCheckedTagArray.put(j, true); childView.setSelected(true); } //回调 if (mOnTagSelectListener != null) { List<Integer> list = new ArrayList<Integer>(); for (int k = 0; k < mAdapter.getCount(); k++) { if (mCheckedTagArray.get(k)) { list.add(k); } } mOnTagSelectListener.onItemSelect(FlowTagLayout.this, list); } } } }); } } /** * 清除所有被选择的选项 * * @author https://github.com/wanyt * * @time 2016年11月13日16:07:23 * */ public void clearAllOption(){ for (int i = 0; i < mAdapter.getCount(); i++) { if (mCheckedTagArray.get(i)) { getChildAt(i).setSelected(false); } } } public void setOnTagClickListener(OnTagClickListener onTagClickListener) { this.mOnTagClickListener = onTagClickListener; } public void setOnTagSelectListener(OnTagSelectListener onTagSelectListener) { this.mOnTagSelectListener = onTagSelectListener; } /** * 像ListView、GridView一样使用FlowLayout * * @param adapter */ public void setAdapter(ListAdapter adapter) { if (mAdapter != null && mDataSetObserver != null) { mAdapter.unregisterDataSetObserver(mDataSetObserver); } //清除现有的数据 removeAllViews(); mAdapter = adapter; if (mAdapter != null) { mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); } reloadData(); } /** * 获取标签模式 * * @return */ public int getmTagCheckMode() { return mTagCheckMode; } /** * 设置标签选中模式 * * @param tagMode */ public void setTagCheckedMode(int tagMode) { this.mTagCheckMode = tagMode; } }