text
stringlengths
7
1.01M
package me.neznamy.tab.shared; import java.util.*; import io.netty.channel.Channel; import me.neznamy.tab.api.ArmorStandManager; import me.neznamy.tab.api.Property; import me.neznamy.tab.api.ProtocolVersion; import me.neznamy.tab.api.TabFeature; import me.neznamy.tab.api.TabPlayer; import me.neznamy.tab.api.chat.IChatBaseComponent; import me.neznamy.tab.api.protocol.*; import me.neznamy.tab.api.protocol.PacketPlayOutChat.ChatMessageType; import me.neznamy.tab.api.team.TeamManager; import me.neznamy.tab.shared.event.impl.PlayerLoadEventImpl; import org.geysermc.floodgate.api.FloodgateApi; /** * The core class for player */ public abstract class ITabPlayer implements TabPlayer { protected final Object player; private final String name; private final UUID uniqueId; private String world; private String server; private String permissionGroup = GroupManager.DEFAULT_GROUP; private String temporaryGroup; private String teamName; private String teamNameNote; private final boolean bedrockPlayer; private final Map<String, Property> properties = new HashMap<>(); private ArmorStandManager armorStandManager; protected ProtocolVersion version; protected Channel channel; private boolean previewingNameTag; private boolean onJoinFinished; private final List<String> registeredTeams = new ArrayList<>(); private final List<String> registeredObjectives = new ArrayList<>(); protected ITabPlayer(Object player, UUID uniqueId, String name, String server, String world) { this.player = player; this.uniqueId = uniqueId; this.name = name; this.server = server; this.world = world; bedrockPlayer = TAB.getInstance().isFloodgateInstalled() && FloodgateApi.getInstance() != null && FloodgateApi.getInstance().isFloodgatePlayer(uniqueId); setGroup(TAB.getInstance().getGroupManager().detectPermissionGroup(this), false); } @Override public void sendMessage(String message, boolean translateColors) { if (message == null || message.length() == 0) return; IChatBaseComponent component; if (translateColors) { component = IChatBaseComponent.fromColoredText(message); } else { component = new IChatBaseComponent(message); } sendCustomPacket(new PacketPlayOutChat(component, ChatMessageType.CHAT)); } @Override public void sendMessage(IChatBaseComponent message) { sendCustomPacket(new PacketPlayOutChat(message, ChatMessageType.CHAT)); } @Override public String getName() { return name; } @Override public UUID getUniqueId() { return uniqueId; } @Override public UUID getTablistUUID() { return uniqueId; } @Override public void forceRefresh() { TAB.getInstance().getFeatureManager().refresh(this, true); } @Override public ProtocolVersion getVersion() { return version; } @Override public String getWorld() { return world; } @Override public String getServer() { return server; } @Override public synchronized void sendCustomPacket(TabPacket packet) { if (packet == null) return; //avoiding BungeeCord bug kicking all players if (packet instanceof PacketPlayOutScoreboardTeam) { String team = ((PacketPlayOutScoreboardTeam) packet).getName(); int method = ((PacketPlayOutScoreboardTeam) packet).getMethod(); if (method == 0) { if (registeredTeams.contains(team)) { TAB.getInstance().getErrorManager().printError("Tried to register duplicated team " + team + " to player " + getName()); return; } registeredTeams.add(team); } else if (method == 1) { registeredTeams.remove(team); } } //avoiding BungeeCord bug kicking all players if (packet instanceof PacketPlayOutScoreboardObjective) { String objective = ((PacketPlayOutScoreboardObjective) packet).getObjectiveName(); int method = ((PacketPlayOutScoreboardObjective) packet).getMethod(); if (method == 0) { if (registeredObjectives.contains(objective)) { TAB.getInstance().getErrorManager().printError("Tried to register duplicated objective " + objective + " to player " + getName()); return; } registeredObjectives.add(objective); } else if (method == 1) { registeredObjectives.remove(objective); } } //avoiding console spam from geyser /* if (packet instanceof PacketPlayOutScoreboardScore) { String objective = ((PacketPlayOutScoreboardScore) packet).getObjectiveName(); String player = ((PacketPlayOutScoreboardScore) packet).getPlayer(); if (!registeredObjectives.contains(objective)) { TAB.getInstance().getErrorManager().printError("Tried to update score (" + player + ") without the existence of its requested objective '" + objective + "' to player " + getName()); return; } }*/ try { sendPacket(TAB.getInstance().getPlatform().getPacketBuilder().build(packet, getVersion())); } catch (Exception e) { TAB.getInstance().getErrorManager().printError("An error occurred when creating " + packet.getClass().getSimpleName(), e); } } @Override public void sendCustomPacket(TabPacket packet, TabFeature feature) { sendCustomPacket(packet); if (feature != null) TAB.getInstance().getCPUManager().packetSent(feature.getFeatureName()); } @Override public void sendCustomPacket(TabPacket packet, String feature) { sendCustomPacket(packet); if (feature != null) TAB.getInstance().getCPUManager().packetSent(feature); } @Override public void sendPacket(Object nmsPacket, TabFeature feature) { sendPacket(nmsPacket); if (feature != null) TAB.getInstance().getCPUManager().packetSent(feature.getFeatureName()); } @Override public void sendPacket(Object packet, String feature) { sendPacket(packet); if (feature != null) TAB.getInstance().getCPUManager().packetSent(feature); } @Override public Property getProperty(String name) { return properties.get(name); } @Override public String getGroup() { return temporaryGroup != null ? temporaryGroup : permissionGroup; } @Override public void toggleNametagPreview() { if (armorStandManager == null) throw new IllegalStateException("Unlimited NameTag mode is not enabled"); if (previewingNameTag) { armorStandManager.destroy(this); sendMessage(TAB.getInstance().getConfiguration().getMessages().getNametagPreviewOff(), true); } else { armorStandManager.spawn(this); sendMessage(TAB.getInstance().getConfiguration().getMessages().getNametagPreviewOn(), true); } previewingNameTag = !previewingNameTag; } @Override public boolean isPreviewingNametag() { return previewingNameTag; } @Override public Channel getChannel() { return channel; } @Override public boolean isLoaded() { return onJoinFinished; } @Override public boolean loadPropertyFromConfig(TabFeature feature, String property) { return loadPropertyFromConfig(feature, property, ""); } @Override public boolean loadPropertyFromConfig(TabFeature feature, String property, String ifNotSet) { String[] value = TAB.getInstance().getConfiguration().getUsers().getProperty(getName(), property, server, world); if (value.length == 0) { value = TAB.getInstance().getConfiguration().getUsers().getProperty(getUniqueId().toString(), property, server, world); } if (value.length == 0) { value = TAB.getInstance().getConfiguration().getGroups().getProperty(getGroup(), property, server, world); } if (value.length > 0) { return setProperty(feature, property, value[0], value[1]); } return setProperty(feature, property, ifNotSet, "None"); } @Override public ArmorStandManager getArmorStandManager() { return armorStandManager; } @Override public void setArmorStandManager(ArmorStandManager armorStandManager) { this.armorStandManager = armorStandManager; } @Override public String getTeamName() { TeamManager teams = TAB.getInstance().getTeamManager(); if (teams != null && teams.getForcedTeamName(this) != null) return teams.getForcedTeamName(this); return teamName; } @Override public String getTeamNameNote() { return teamNameNote; } @Override public boolean isBedrockPlayer() { return bedrockPlayer; } @Override public boolean setProperty(TabFeature feature, String identifier, String rawValue) { return setProperty(feature, identifier, rawValue, null); } private boolean setProperty(TabFeature feature, String identifier, String rawValue, String source) { PropertyImpl p = (PropertyImpl) getProperty(identifier); if (p == null) { properties.put(identifier, new PropertyImpl(feature, this, rawValue, source)); return true; } else { if (!p.getOriginalRawValue().equals(rawValue)) { p.changeRawValue(rawValue); p.setSource(source); return true; } return false; } } public void setTeamNameNote(String note) { teamNameNote = note; } public void setTeamName(String name) { teamName = name; } public void markAsLoaded(boolean join) { onJoinFinished = true; if (TAB.getInstance().getEventBus() != null) TAB.getInstance().getEventBus().fire(new PlayerLoadEventImpl(this, join)); TAB.getInstance().getPlatform().callLoadEvent(this); } public void setGroup(String permissionGroup, boolean refreshIfChanged) { if (this.permissionGroup.equals(permissionGroup)) return; if (permissionGroup != null) { this.permissionGroup = permissionGroup; } else { this.permissionGroup = GroupManager.DEFAULT_GROUP; } if (refreshIfChanged) { forceRefresh(); } } public void setWorld(String name) { world = name; } public void setServer(String name) { server = name; } public void clearRegisteredObjectives() { registeredTeams.clear(); registeredObjectives.clear(); } public void setTemporaryGroup(String group) { if (Objects.equals(group, temporaryGroup)) return; temporaryGroup = group; forceRefresh(); } public boolean hasTemporaryGroup() { return temporaryGroup != null; } public void resetTemporaryGroup() { setTemporaryGroup(null); } }
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package org.jsimpledb.kv; import com.google.common.base.Preconditions; import org.jsimpledb.util.CloseableIterator; /** * General API into a key/value store where the keys are sorted lexicographically as unsigned bytes. * * <p> * Implementations are not required to support accessing keys that start with {@code 0xff}, * and if not may throw {@link IllegalArgumentException} if such keys are accessed. * * <p><b>Thread Safety</b></p> * * <p> * Instances must be thread safe, with the exception of the {@link java.util.Iterator} returned by {@link #getRange getRange()}. * * <p><b>Lock-free Counters</b></p> * * <p> * Implementations are encouraged to include support for encoding a 64 bit counter in a key/value pair such that the counter * can be efficiently {@linkplain #adjustCounter adjusted} by concurrent transactions without conflict. * In practice this means no locking is required to increment or decrement the counter by some amount, as long as * it's not necessary to actually directly read or write the counter value in the same transaction. * Whether counter adjustments are actually lock-free is implementation dependent, however, the counter methods * {@link #encodeCounter encodeCounter()}, {@link #decodeCounter decodeCounter()}, and {@link #adjustCounter adjustCounter()} * must function correctly as specified in all cases. * * <p> * How counters are encoded is specific to the implementation. Clients needing to read or write counter values directly * should use {@link #decodeCounter decodeCounter()} and {@link #encodeCounter encodeCounter()}, respectively. * Counters are removed using the normal methods (i.e., {@link #remove remove()} and {@link #removeRange removeRange()}). */ public interface KVStore { /** * Get the value associated with the given key, if any. * * <p> * Modifications to the returned {@code byte[]} array do not affect this instance. * * @param key key * @return value associated with key, or null if not found * @throws IllegalArgumentException if {@code key} starts with {@code 0xff} and such keys are not supported * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable * @throws NullPointerException if {@code key} is null */ byte[] get(byte[] key); /** * Get the key/value pair having the smallest key greater than or equal to the given minimum, if any. * * <p> * An optional (exclusive) maximum key may also be specified; if {@code maxKey} is null, there is no upper bound; * if {@code maxKey <= minKey}, null is always returned. * * <p> * If keys starting with {@code 0xff} are not supported by this instance, and {@code minKey} starts with {@code 0xff}, * then this method returns null. * * <p> * Modifications to the returned {@code byte[]} arrays do not affect this instance. * * @param minKey minimum key (inclusive), or null for no minimum (get the smallest key) * @param maxKey maximum key (exclusive), or null for no maximum (no upper bound) * @return smallest key/value pair with {@code key >= minKey} and {@code key < maxKey}, or null if none exists * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable */ KVPair getAtLeast(byte[] minKey, byte[] maxKey); /** * Get the key/value pair having the largest key strictly less than the given maximum, if any. * * <p> * An optional (inclusive) minimum key may also be specified; if {@code minKey} is null, there is no lower bound * (equivalent to a lower bound of the empty byte array); if {@code minKey >= maxKey}, null is always returned. * * <p> * If keys starting with {@code 0xff} are not supported by this instance, and {@code maxKey} starts with {@code 0xff}, * then this method behaves as if {@code maxKey} were null. * * <p> * Modifications to the returned {@code byte[]} arrays do not affect this instance. * * @param maxKey maximum key (exclusive), or null for no maximum (get the largest key) * @param minKey minimum key (inclusive), or null for no minimum (no lower bound) * @return largest key/value pair with {@code key < maxKey} and {@code key >= minKey}, or null if none exists * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable */ KVPair getAtMost(byte[] maxKey, byte[] minKey); /** * Iterate the key/value pairs in the specified range. The returned {@link java.util.Iterator}'s * {@link java.util.Iterator#remove remove()} method must be supported and should have the same effect as * invoking {@link #remove remove()} on the corresponding key. * * <p> * If keys starting with {@code 0xff} are not supported by this instance, and {@code minKey} starts with {@code 0xff}, * then this method returns an empty iteration. * * <p> * If keys starting with {@code 0xff} are not supported by this instance, and {@code maxKey} starts with {@code 0xff}, * then this method behaves as if {@code maxKey} were null. * * <p> * The returned {@link java.util.Iterator} must not throw {@link java.util.ConcurrentModificationException}; * however, whether or not a "live" {@link java.util.Iterator} reflects any modifications made after its creation is * implementation dependent. Implementations that do make post-creation updates visible in the {@link java.util.Iterator}, * even if the update occurs after some delay, must preserve the order in which the modifications actually occurred. * * <p> * The returned {@link java.util.Iterator} itself is not guaranteed to be thread safe. * * <p> * Invokers of this method are encouraged to {@link java.io.Closeable#close close()} the returned iterators, * though this is not required for correct behavior. * * <p> * Modifications to the returned {@link KVPair} key and value {@code byte[]} arrays do not affect this instance. * * @param minKey minimum key (inclusive), or null for no minimum (start at the smallest key) * @param maxKey maximum key (exclusive), or null for no maximum (end at the largest key) * @param reverse true to return key/value pairs in reverse order (i.e., keys descending) * @return iteration of key/value pairs in the range {@code minKey} (inclusive) to {@code maxKey} (exclusive) * @throws IllegalArgumentException if {@code minKey > maxKey} * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable */ CloseableIterator<KVPair> getRange(byte[] minKey, byte[] maxKey, boolean reverse); /** * Iterate the key/value pairs in the specified range in the forward direction. * * <p> * This is a convenience method, equivalent to: * {@link #getRange(byte[], byte[], boolean) getRange}{@code (minKey, maxKey, false)}. * * @param minKey minimum key (inclusive), or null for no minimum (start at the smallest key) * @param maxKey maximum key (exclusive), or null for no maximum (end at the largest key) * @return iteration of key/value pairs in the range {@code minKey} (inclusive) to {@code maxKey} (exclusive) * @throws IllegalArgumentException if {@code minKey > maxKey} * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable */ default CloseableIterator<KVPair> getRange(byte[] minKey, byte[] maxKey) { return this.getRange(minKey, maxKey, false); } /** * Iterate the key/value pairs in the specified range in the forward direction. * * <p> * This is a convenience method, equivalent to: * {@link #getRange(byte[], byte[], boolean) getRange}{@code (range.getMin(), range.getMax(), false)}. * * @param range range of keys to iterate * @return iteration of key/value pairs in {@code range} * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable * @throws IllegalArgumentException if {@code range} is null */ default CloseableIterator<KVPair> getRange(KeyRange range) { Preconditions.checkArgument(range != null, "null range"); return this.getRange(range.getMin(), range.getMax(), false); } /** * Set the value associated with the given key. * * @param key key * @param value value * @throws IllegalArgumentException if {@code key} starts with {@code 0xff} and such keys are not supported * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable * @throws NullPointerException if {@code key} or {@code value} is null */ void put(byte[] key, byte[] value); /** * Remove the key/value pair with the given key, if it exists. * * @param key key * @throws IllegalArgumentException if {@code key} starts with {@code 0xff} and such keys are not supported * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable * @throws NullPointerException if {@code key} is null */ void remove(byte[] key); /** * Remove all key/value pairs whose keys are in a given range. * * <p> * The {@code minKey} must be less than or equal to {@code maxKey}; if they equal (and not null) * then nothing happens; if they are both null then all entries are deleted. * * <p> * If keys starting with {@code 0xff} are not supported by this instance, then: * <ul> * <li>If {@code minKey} starts with {@code 0xff}, then no change occurs</li> * <li>If {@code maxKey} starts with {@code 0xff}, then this method behaves as if {@code maxKey} were null</li> * </ul> * * @param minKey minimum key (inclusive), or null for no minimum * @param maxKey maximum key (exclusive), or null for no maximum * @throws IllegalArgumentException if {@code minKey > maxKey} * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable */ void removeRange(byte[] minKey, byte[] maxKey); /** * Remove all key/value pairs whose keys are in a given range. * * <p> * Equivalent to: {@link #removeRange removeRange}{@code (range.getMin(), range.getMax())}. * * @param range range to remove * @throws IllegalArgumentException if {@code range} is null * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable */ default void removeRange(KeyRange range) { Preconditions.checkArgument(range != null, "null range"); this.removeRange(range.getMin(), range.getMax()); } /** * Encode a counter value into a {@code byte[]} value suitable for use with {@link #decodeCounter decodeCounter()} * and/or {@link #adjustCounter adjustCounter()}. * * @param value desired counter value * @return encoded counter value * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable */ byte[] encodeCounter(long value); /** * Decode a counter value previously encoded by {@link #encodeCounter encodeCounter()}. * * @param value encoded counter value * @return decoded counter value * @throws IllegalArgumentException if {@code value} is not a valid counter value * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable * @throws NullPointerException if {@code value} is null */ long decodeCounter(byte[] value); /** * Adjust the counter at the given key by the given amount. * * <p> * Ideally this operation should behave in a lock-free manner, so that concurrent transactions can invoke it without * conflict. However, when lock-free behavior occurs (if at all) depends on the implementation. * * <p> * If there is no value associated with {@code key}, or {@code key}'s value is not a valid counter encoding as * would be acceptable to {@link #decodeCounter decodeCounter()}, then how this operation affects {@code key}'s * value is undefined. * * @param key key * @param amount amount to adjust counter value by * @throws StaleTransactionException if an underlying transaction is no longer usable * @throws RetryTransactionException if an underlying transaction must be retried and is no longer usable * @throws NullPointerException if {@code key} is null */ void adjustCounter(byte[] key, long amount); }
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates. * * 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.kie.kogito.grafana.utils; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.kie.kogito.grafana.utils.GrafanaDashboardUtils.DISABLED_DOMAIN_DASHBOARDS; import static org.kie.kogito.grafana.utils.GrafanaDashboardUtils.DISABLED_OPERATIONAL_DASHBOARDS; class GrafanaDashboardUtilsTest { @Test void isOperationDashboardEnabled() { Map<String, String> propertiesMap = new HashMap<>(); assertTrue(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Loan")); assertTrue(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Hello")); propertiesMap.put(DISABLED_OPERATIONAL_DASHBOARDS, ""); assertTrue(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Loan")); assertTrue(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Hello")); String values = "Hello"; propertiesMap.put(DISABLED_OPERATIONAL_DASHBOARDS, values); assertTrue(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Loan")); assertFalse(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Hello")); values = "Hello,Loan"; propertiesMap.put(DISABLED_OPERATIONAL_DASHBOARDS, values); assertTrue(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Traffic")); assertFalse(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Loan")); assertFalse(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Hello")); values = " Hello, Loan "; propertiesMap.put(DISABLED_OPERATIONAL_DASHBOARDS, values); assertTrue(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Traffic")); assertFalse(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Loan")); assertFalse(GrafanaDashboardUtils.isOperationDashboardEnabled(propertiesMap, "Hello")); } @Test void isDomainDashboardEnabled() { Map<String, String> propertiesMap = new HashMap<>(); assertTrue(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Loan")); assertTrue(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Hello")); propertiesMap.put(DISABLED_DOMAIN_DASHBOARDS, ""); assertTrue(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Loan")); assertTrue(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Hello")); String values = "Hello"; propertiesMap.put(DISABLED_DOMAIN_DASHBOARDS, values); assertTrue(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Loan")); assertFalse(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Hello")); values = "Hello,Loan"; propertiesMap.put(DISABLED_DOMAIN_DASHBOARDS, values); assertTrue(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Traffic")); assertFalse(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Loan")); assertFalse(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Hello")); values = " Hello, Loan "; propertiesMap.put(DISABLED_DOMAIN_DASHBOARDS, values); assertTrue(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Traffic")); assertFalse(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Loan")); assertFalse(GrafanaDashboardUtils.isDomainDashboardEnabled(propertiesMap, "Hello")); } }
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2020 Ruhr University Bochum, Paderborn University, * and Hackmanit GmbH * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package de.rub.nds.tlsattacker.core.record; import de.rub.nds.tlsattacker.core.config.Config; import de.rub.nds.tlsattacker.core.constants.ProtocolMessageType; import de.rub.nds.tlsattacker.core.constants.ProtocolVersion; import de.rub.nds.tlsattacker.core.record.compressor.RecordCompressor; import de.rub.nds.tlsattacker.core.record.crypto.Encryptor; import de.rub.nds.tlsattacker.core.record.parser.AbstractRecordParser; import de.rub.nds.tlsattacker.core.record.parser.BlobRecordParser; import de.rub.nds.tlsattacker.core.record.preparator.AbstractRecordPreparator; import de.rub.nds.tlsattacker.core.record.preparator.BlobRecordPreparator; import de.rub.nds.tlsattacker.core.record.serializer.AbstractRecordSerializer; import de.rub.nds.tlsattacker.core.record.serializer.BlobRecordSerializer; import de.rub.nds.tlsattacker.core.state.TlsContext; import de.rub.nds.tlsattacker.core.workflow.chooser.Chooser; /** * A Blob Record is not a record in a conventional sense but is rather a non * exisiting record and represents just a collection of bytes. Is used for * unparseable Records and for SSLv2 */ public class BlobRecord extends AbstractRecord { private RecordCryptoComputations computations; public BlobRecord() { } public BlobRecord(Config config) { super(config); } @Override public AbstractRecordPreparator getRecordPreparator(Chooser chooser, Encryptor encryptor, RecordCompressor compressor, ProtocolMessageType type) { return new BlobRecordPreparator(chooser, this, encryptor, type, compressor); } @Override public AbstractRecordParser getRecordParser(int startposition, byte[] array, ProtocolVersion version) { return new BlobRecordParser(startposition, array, version); } @Override public AbstractRecordSerializer getRecordSerializer() { return new BlobRecordSerializer(this); } @Override public void adjustContext(TlsContext context) { // do nothing } public RecordCryptoComputations getComputations() { return computations; } public void setComputations(RecordCryptoComputations computations) { this.computations = computations; } @Override public void prepareComputations() { computations = new RecordCryptoComputations(); } @Override public String toString() { return "BlobRecord{" + "computations=" + computations + '}'; } }
package org.hswebframework.web.service.authorization.simple; import org.hswebframework.web.commons.entity.DataStatus; import org.hswebframework.web.dao.authorization.PermissionDao; import org.hswebframework.web.entity.authorization.PermissionEntity; import org.hswebframework.web.id.IDGenerator; import org.hswebframework.web.service.GenericEntityService; import org.hswebframework.web.service.authorization.PermissionService; import org.hswebframework.web.service.authorization.events.ClearUserAuthorizationCacheEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import java.util.Optional; /** * 权限管理 * * @author zhouhao */ @Service("permissionService") public class SimplePermissionService extends GenericEntityService<PermissionEntity, String> implements PermissionService { @Autowired private PermissionDao permissionDao; @Autowired private ApplicationEventPublisher eventPublisher; @Override protected IDGenerator<String> getIDGenerator() { return IDGenerator.MD5; } @Override public PermissionDao getDao() { return permissionDao; } @Override public String insert(PermissionEntity entity) { entity.setStatus(DataStatus.STATUS_ENABLED); return super.insert(entity); } @Override public int updateByPk(String id, PermissionEntity entity) { int len = super.updateByPk(id, entity); eventPublisher.publishEvent(new ClearUserAuthorizationCacheEvent(null, true)); return len; } @Override public int deleteByPk(String id) { int len = super.deleteByPk(id); eventPublisher.publishEvent(new ClearUserAuthorizationCacheEvent(null, true)); return len; } }
/* ==================================================================== 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.poi.stress; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.sun.management.HotSpotDiagnosticMXBean; import org.apache.poi.util.SuppressForbidden; @SuppressForbidden("class only exists for manual tests in XSSFFileHandler") public class HeapDump { // This is the name of the HotSpot Diagnostic MBean private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; // field to store the hotspot diagnostic MBean private static volatile HotSpotDiagnosticMXBean hotspotMBean; /** * Call this method from your application whenever you * want to dump the heap snapshot into a file. * * @param fileName name of the heap dump file * @param live flag that tells whether to dump * only the live objects */ public static void dumpHeap(String fileName, boolean live) throws IOException { try { if (isIbmVm()) { dumpHeapJ9(fileName); } else { // initialize hotspot diagnostic MBean initHotspotMBean(); dumpHeapHotSpot(fileName, live); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) { throw new RuntimeException(e); } } // initialize the hotspot diagnostic MBean field private static void initHotspotMBean() throws IOException { if (hotspotMBean == null) { synchronized (HeapDump.class) { if (hotspotMBean == null) { hotspotMBean = getHotspotMBean(); } } } } // get the hotspot diagnostic MBean from the platform MBean server private static HotSpotDiagnosticMXBean getHotspotMBean() throws IOException { return ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(), HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class); } private static boolean isIbmVm() { try { Class.forName("com.ibm.jvm.Dump"); return true; } catch (ClassNotFoundException e) { return false; } } private static void dumpHeapJ9(String fileName) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?> dump = Class.forName("com.ibm.jvm.Dump"); Method heapDumpToFile = dump.getMethod("heapDumpToFile", String.class); heapDumpToFile.invoke(dump, fileName); } private static void dumpHeapHotSpot(String fileName, boolean live) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method dumpHeap = hotspotMBean.getClass().getMethod("dumpHeap", String.class, boolean.class); dumpHeap.invoke(hotspotMBean, fileName, live); } }
package com.example.sugarandroid.ui.gallery; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class GalleryViewModel extends ViewModel { private MutableLiveData<String> mText; public GalleryViewModel() { mText = new MutableLiveData<>(); mText.setValue("This is gallery fragment"); } public LiveData<String> getText() { return mText; } }
/* * Copyright 2018 ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package tech.pegasys.pantheon.consensus.ibft.messagedata; import tech.pegasys.pantheon.consensus.ibft.payload.NewRoundPayload; import tech.pegasys.pantheon.consensus.ibft.payload.SignedData; import tech.pegasys.pantheon.ethereum.p2p.api.MessageData; import tech.pegasys.pantheon.ethereum.rlp.RLP; import tech.pegasys.pantheon.util.bytes.BytesValue; public class NewRoundMessageData extends AbstractIbftMessageData { private static final int MESSAGE_CODE = IbftV2.NEW_ROUND; private NewRoundMessageData(final BytesValue data) { super(data); } public static NewRoundMessageData fromMessageData(final MessageData messageData) { return fromMessageData( messageData, MESSAGE_CODE, NewRoundMessageData.class, NewRoundMessageData::new); } public SignedData<NewRoundPayload> decode() { return SignedData.readSignedNewRoundPayloadFrom(RLP.input(data)); } public static NewRoundMessageData create(final SignedData<NewRoundPayload> signedPayload) { return new NewRoundMessageData(signedPayload.encode()); } @Override public int getCode() { return MESSAGE_CODE; } }
package com.vondear.rxfeature.tool; import android.graphics.Bitmap; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.Result; import com.google.zxing.common.HybridBinarizer; import com.vondear.rxfeature.module.scaner.BitmapLuminanceSource; import com.vondear.rxtool.RxImageTool; import java.util.Hashtable; import java.util.Vector; /** * @author Vondear * @date 2017/10/11 */ public class RxQrBarTool { /** * 解析图片中的 二维码 或者 条形码 * * @param photo 待解析的图片 * @return Result 解析结果,解析识别时返回NULL */ public static Result decodeFromPhoto(Bitmap photo) { Result rawResult = null; if (photo != null) { Bitmap smallBitmap = RxImageTool.zoomBitmap(photo, photo.getWidth() / 2, photo.getHeight() / 2);// 为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存 photo.recycle(); // 释放原始图片占用的内存,防止out of memory异常发生 MultiFormatReader multiFormatReader = new MultiFormatReader(); // 解码的参数 Hashtable<DecodeHintType, Object> hints = new Hashtable<>(2); // 可以解析的编码类型 Vector<BarcodeFormat> decodeFormats = new Vector<>(); if (decodeFormats.isEmpty()) { decodeFormats = new Vector<>(); Vector<BarcodeFormat> PRODUCT_FORMATS = new Vector<>(5); PRODUCT_FORMATS.add(BarcodeFormat.UPC_A); PRODUCT_FORMATS.add(BarcodeFormat.UPC_E); PRODUCT_FORMATS.add(BarcodeFormat.EAN_13); PRODUCT_FORMATS.add(BarcodeFormat.EAN_8); // PRODUCT_FORMATS.add(BarcodeFormat.RSS14); Vector<BarcodeFormat> ONE_D_FORMATS = new Vector<>(PRODUCT_FORMATS.size() + 4); ONE_D_FORMATS.addAll(PRODUCT_FORMATS); ONE_D_FORMATS.add(BarcodeFormat.CODE_39); ONE_D_FORMATS.add(BarcodeFormat.CODE_93); ONE_D_FORMATS.add(BarcodeFormat.CODE_128); ONE_D_FORMATS.add(BarcodeFormat.ITF); Vector<BarcodeFormat> QR_CODE_FORMATS = new Vector<>(1); QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE); Vector<BarcodeFormat> DATA_MATRIX_FORMATS = new Vector<>(1); DATA_MATRIX_FORMATS.add(BarcodeFormat.DATA_MATRIX); // 这里设置可扫描的类型,我这里选择了都支持 decodeFormats.addAll(ONE_D_FORMATS); decodeFormats.addAll(QR_CODE_FORMATS); decodeFormats.addAll(DATA_MATRIX_FORMATS); } hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats); // 设置继续的字符编码格式为UTF8 // hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); // 设置解析配置参数 multiFormatReader.setHints(hints); // 开始对图像资源解码 try { rawResult = multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource(smallBitmap)))); } catch (Exception e) { e.printStackTrace(); } } return rawResult; } }
/* * Copyright (c) 2016. TedaLIEz <aliezted@gmail.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 com.hustunique.jianguo.dribile.service.endpoint; import com.hustunique.jianguo.dribile.models.Attachment; import com.hustunique.jianguo.dribile.models.Buckets; import com.hustunique.jianguo.dribile.models.Comments; import com.hustunique.jianguo.dribile.models.Shots; import com.hustunique.jianguo.dribile.service.api.Constants; import java.util.List; import java.util.Map; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.QueryMap; import rx.Observable; /** * Created by JianGuo on 3/29/16. * Request for dribbble shots */ public interface DribbbleShotsService { /** * Get all the shots * @param params query params * @return all shots. */ @GET(Constants.URL_BASE_SHOTS) Observable<List<Shots>> getAllShots(@QueryMap Map<String, String> params); /** * Get shot by id * @param id the shot id * @return the shot */ @GET(Constants.URL_BASE_SHOTS + "{id}") Observable<Shots> getShotById(@Path("id") String id); /** * Get buckets which includes the shot * @param id the shot id * @return buckets including the shot. */ @GET(Constants.URL_BASE_SHOTS + "{id}" + Constants.URL_BASE_BUCKETS) Observable<Buckets> getBuckets(@Path("id") String id); /** * Get comments in the shot * @param id the shot's id * @param params other query params * @return comments in this shot. */ @GET(Constants.URL_BASE_SHOTS + "{id}/" + Constants.URL_BASE_COMMENTS) Observable<List<Comments>> getComment(@Path("id") String id, @QueryMap Map<String, String> params); /** * Get comments in the shot * @param id the shot's id * @return comments in this shot, get first 12 comments by default */ @GET(Constants.URL_BASE_SHOTS + "{id}/" + Constants.URL_BASE_COMMENTS) Observable<List<Comments>> getComment(@Path("id") String id); @FormUrlEncoded @POST(Constants.URL_BASE_SHOTS + "{id}/" + Constants.URL_BASE_COMMENTS) Observable<Comments> addComment(@Path("id") String id, @Field("body") String body); @GET(Constants.URL_BASE_SHOTS + "{id}/" + Constants.URL_BASE_ATTACHMENTS) Observable<List<Attachment>> getAttachments(@Path("id") String id); }
package me.egg82.antivpn.services.lookup; import me.egg82.antivpn.services.lookup.models.ProfileModel; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.UUID; public interface PlayerInfo { @NotNull String getName(); @NotNull UUID getUUID(); @NotNull List<ProfileModel.@NotNull ProfilePropertyModel> getProperties(); }
package com.dataiku.dss.formats.spss; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import com.dataiku.dss.formats.spss.SPSSStreamReader.NumericFormat; import org.apache.commons.lang.ArrayUtils; public class SPSSInputStream extends InputStream { Charset charset; DataInputStream is; boolean littleEndian; byte[] buff; SPSSInputStream(InputStream is) { this.is = new DataInputStream(is); } @Override public int read(byte[] userBuff) throws IOException { int ret = is.read(userBuff); buff = userBuff.clone(); if (ret < userBuff.length) { throw new EOFException("End of stream reached"); } return ret; } @Override public int read() throws IOException { int ret = is.read(); if (ret == -1) { throw new EOFException("End of stream reached"); } return ret; } public void setLittleEndian(boolean littleEndian) { this.littleEndian = littleEndian; } public void setCharset(Charset charset) { this.charset = charset; } public int readInt() throws IOException { int i = is.readInt(); if (littleEndian) { return Integer.reverseBytes(i); } return i; } public double readDouble() throws IOException { buff = new byte[8]; is.read(buff); ByteBuffer bb; if (littleEndian) { bb = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).put(buff); bb.flip(); } else { bb = ByteBuffer.allocate(8).order(ByteOrder.BIG_ENDIAN).put(buff); } return bb.getDouble(); } public NumericFormat readNumericFormat() throws IOException { // To note: it IS endian-dependant ;) int formatCode = this.readInt(); NumericFormat f = new NumericFormat(); f.decimals = (formatCode >> 0) & 0xFF; f.width = (formatCode >> 8) & 0xFF; f.type = (formatCode >> 16) & 0xFF; //f.zero = (formatCode >> 24) & 0xFF; return f; } public String readString(int len, boolean shouldTrim) throws IOException { String ret; buff = new byte[len]; is.read(buff); if (charset != null) { ret = new String(buff, charset); } else { ret = new String(buff); } return shouldTrim ? ret.trim() : ret; } public List<Byte> getLastByteArray() { return Arrays.asList(ArrayUtils.toObject(buff)); } public String readString(int len) throws IOException { return readString(len, true); } public void skipBytes(int i) throws IOException { // When we skip bytes for the padding, these bytes might still be used for the value labels. if (buff.length + i == 8) { byte[] secondBuff = new byte[i]; is.read(secondBuff); byte[] newBuff = new byte[8]; System.arraycopy(buff, 0, newBuff, 0, buff.length); System.arraycopy(secondBuff, 0, newBuff, buff.length, secondBuff.length); buff = newBuff; } else { is.skipBytes(i); } } public byte[] toByteArray(double value) { byte[] bytes = new byte[8]; ByteBuffer.wrap(bytes).order(littleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).putDouble(value); return bytes; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.gst.infrastructure.core.exceptionmapper; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import com.gst.infrastructure.core.data.ApiGlobalErrorResponse; import com.gst.infrastructure.core.data.ApiParameterError; import com.gst.infrastructure.core.exception.UnsupportedParameterException; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** * An {@link ExceptionMapper} to map {@link UnsupportedParameterException} * thrown by platform into a HTTP API friendly format. */ @Provider @Component @Scope("singleton") public class UnsupportedParameterExceptionMapper implements ExceptionMapper<UnsupportedParameterException> { @Override public Response toResponse(final UnsupportedParameterException exception) { final List<ApiParameterError> errors = new ArrayList<>(); for (final String parameterName : exception.getUnsupportedParameters()) { final StringBuilder validationErrorCode = new StringBuilder("error.msg.parameter.unsupported"); final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameterName).append( " is not supported."); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), parameterName, parameterName); errors.add(error); } final ApiGlobalErrorResponse invalidParameterError = ApiGlobalErrorResponse.badClientRequest( "validation.msg.validation.errors.exist", "Validation errors exist.", errors); return Response.status(Status.BAD_REQUEST).entity(invalidParameterError).type(MediaType.APPLICATION_JSON).build(); } }
package abattleground.jsonptest; import com.alibaba.fastjson.annotation.JSONField; import org.springframework.data.mongodb.core.geo.GeoJsonPoint; public class TestObj { private String name; private int age; private String id; private long frameTime; @JSONField(deserializeUsing = GeoJsonPointDeserializer.class) private GeoJsonPoint obj; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public long getFrameTime() { return frameTime; } public void setFrameTime(long frameTime) { this.frameTime = frameTime; } public GeoJsonPoint getObj() { return obj; } public void setObj(GeoJsonPoint obj) { this.obj = obj; } }
package br.unisal.aula.helpers; import javax.swing.JOptionPane; public final class MensagemHelper { public static void exibir(String texto) { JOptionPane.showMessageDialog(null, texto); } }
package com.client.skclient; import com.client.skclient.controllers.LogInController; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import java.io.IOException; public class Main extends Application { private Stage stage; private Scene scene; private Parent root; private Client client; @Override public void start(Stage startingStage) throws IOException { client = new Client(); stage = startingStage; FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("login-view.fxml")); root = fxmlLoader.load(); LogInController logInController = fxmlLoader.getController(); logInController.initialize(client, stage); scene = new Scene(root); stage.setScene(scene); stage.setTitle("Współbieżny edytor tekstu"); stage.sizeToScene(); stage.show(); } public static void main(String[] args) { launch(args); } } //public class Main { // // private int j; // // public static void main(String[] args) { // com.client.skclient.Main Main = new com.client.skclient.Main(); // for(int i=0;i<2;i++){ // new Thread(Main.new ShareData1()).start();//Increase // new Thread(Main.new ShareData2()).start();//Reduce // } // } // //Increase // private synchronized void Inc(){ // j++; // System.out.println(Thread.currentThread().getName()+" inc "+j); // } // // decrement // private synchronized void Dec(){ // j--; // System.out.println(Thread.currentThread().getName()+" dec "+j); // } // // class ShareData1 implements Runnable { // public void run() { // for(int i=0;i<5;i++){ // Inc(); // } // } // } // class ShareData2 implements Runnable { // public void run() { // for(int i=0;i<5;i++){ // Dec(); // } // } // } // // }
package com.raywenderlich.android.movieapp.ui.movies; import java.lang.System; @kotlin.Metadata(mv = {1, 1, 16}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\f\n\u0002\u0018\u0002\n\u0002\u0010\u0010\n\u0002\b\u0006\b\u0086\u0001\u0018\u00002\b\u0012\u0004\u0012\u00020\u00000\u0001B\u0007\b\u0002\u00a2\u0006\u0002\u0010\u0002j\u0002\b\u0003j\u0002\b\u0004j\u0002\b\u0005j\u0002\b\u0006\u00a8\u0006\u0007"}, d2 = {"Lcom/raywenderlich/android/movieapp/ui/movies/MovieLoadingState;", "", "(Ljava/lang/String;I)V", "LOADING", "ERROR", "LOADED", "INVALID_API_KEY", "app_debug"}) public enum MovieLoadingState { /*public static final*/ LOADING /* = new LOADING() */, /*public static final*/ ERROR /* = new ERROR() */, /*public static final*/ LOADED /* = new LOADED() */, /*public static final*/ INVALID_API_KEY /* = new INVALID_API_KEY() */; MovieLoadingState() { } }
//package net.debug; // //import com.mojang.blaze3d.systems.RenderSystem; //import net.minecraft.client.gui.screen.ingame.HandledScreen; //import net.minecraft.client.render.GameRenderer; //import net.minecraft.client.util.math.MatrixStack; //import net.minecraft.entity.player.PlayerInventory; //import net.minecraft.screen.ScreenHandler; //import net.minecraft.text.Text; //import net.minecraft.util.Identifier; // //public class BoxScreen extends HandledScreen<ScreenHandler> { // //A path to the gui texture. In this example we use the texture from the dispenser // private static final Identifier TEXTURE = new Identifier("minecraft", "textures/gui/container/dispenser.png"); // // public BoxScreen(ScreenHandler handler, PlayerInventory inventory, Text title) { // super(handler, inventory, title); // } // // @Override // protected void drawBackground(MatrixStack matrices, float delta, int mouseX, int mouseY) { // RenderSystem.setShader(GameRenderer::getPositionTexShader); // RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); // RenderSystem.setShaderTexture(0, TEXTURE); // int x = (width - backgroundWidth) / 2; // int y = (height - backgroundHeight) / 2; // drawTexture(matrices, x, y, 0, 0, backgroundWidth, backgroundHeight); // } // // @Override // public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { // renderBackground(matrices); // super.render(matrices, mouseX, mouseY, delta); // drawMouseoverTooltip(matrices, mouseX, mouseY); // } // // @Override // protected void init() { // super.init(); // // Center the title // titleX = (backgroundWidth - textRenderer.getWidth(title)) / 2; // } //} //
package ru.job4j.web; import java.io.File; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Before; //import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import ru.job4j.checking.DBDriver; import ru.job4j.models.Body; import ru.job4j.models.Brand; import ru.job4j.models.Car; import ru.job4j.models.Founder; import ru.job4j.models.IModel; import ru.job4j.models.Offer; import ru.job4j.models.User; import ru.job4j.services.DAO; /** * Класс OfferDeleteTest тестирует класс OfferDelete. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-12-08 * @since 2018-05-29 */ public class OfferDeleteTest { /** * Заглушка контекста сервлета. */ @Mock private ServletContext ctx; /** * DAO. */ private DAO dao; /** * Логгер. */ private Logger logger = LogManager.getLogger(this.getClass().getSimpleName()); /** * Заглушка диспатчера реквеста. */ @Mock private RequestDispatcher reqDesp; /** * Сервлет. */ @Mock private OfferDelete servlet; /** * Действия перед тестом. */ @Before public void beforeTest() { try { DBDriver driver = new DBDriver("jdbc:postgresql://localhost:5432/jpack3p1ch2task2", "postgres", "postgresrootpass"); String path = new File(DBDriver.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath() + "/"; path = path.replaceFirst("^/(.:/)", "$1"); driver.executeSqlScript(path + "../../src/main/resources/junior.pack3.p1.ch2.task2.sql"); MockitoAnnotations.initMocks(this); this.dao = new DAO(); this.servlet = new OfferDelete(); ServletConfig conf = mock(ServletConfig.class); this.servlet.init(conf); } catch (Exception ex) { this.logger.error("ERROR", ex); ex.printStackTrace(); } } /** * СОздаёт папку с заглушками изображений объявления. * @param id идентификатор объявления. * @throws Exception исключение. */ private void createFakeFotos(int id) throws Exception { String path = new File(".").getCanonicalPath(); path = String.format("%s/webapps/ch2_carStoreWeb/fotos", path); String fotosPath = Paths.get(path).normalize().toString(); String dirName = String.format("%s/%d", fotosPath, id); File dir = new File(dirName); if (!dir.exists() && !dir.mkdir()) { throw new Exception(String.format("Folder %s not created.", dirName)); } String name = String.format("%s/%d/%s", fotosPath, id, "fakeFoto1.jpg"); File foto = new File(name); if (!foto.exists() && !foto.createNewFile()) { throw new Exception(String.format("%s not created.", name)); } } /** * Получает объявление. * @return объявление. * @throws Exception исключение. */ private Offer getOffer() throws Exception { HashMap<String, IModel> items = new HashMap<>(); items.put("body", new Body(1, "sedan")); List<Body> bodies = new ArrayList<>(); bodies.add(new Body(1, "sedan")); bodies.add(new Body(2, "hatchback")); Founder founder = new Founder(0, "ЦК КПСС", "Совет министров СССР"); int id = this.dao.create(founder); founder.setId(id); Brand brand = new Brand(0, "ВАЗ", founder); id = this.dao.create(brand); brand.setId(id); Car car = new Car(0, "Vesta", bodies, brand); id = this.dao.create(car); car.setId(id); items.put("car", car); User user = new User(1, "testUser1"); items.put("user", user); return new Offer(0, items, 100500, false); } /** * Тестирует public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException. */ @Test public void testDoGet() { try { Offer expected = this.getOffer(); int id = this.dao.create(expected); expected.setId(id); HttpServletRequest req = mock(HttpServletRequest.class); HttpServletResponse resp = mock(HttpServletResponse.class); when(req.getParameter("id")).thenReturn(Integer.toString(id)); when(this.servlet.getServletContext()).thenReturn(ctx); when(ctx.getRequestDispatcher("/WEB-INF/views/offerDeleteGet.jsp")).thenReturn(reqDesp); AttributeStorage storage = new AttributeStorage(); storage.set(req); this.servlet.doGet(req, resp); Offer actual = (Offer) req.getAttribute("offer"); assertEquals(expected, actual); } catch (Exception ex) { this.logger.error("ERROR", ex); ex.printStackTrace(); } } /** * Тестирует public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException. */ @Test public void testDoPost() { try { Offer offer = this.getOffer(); int id = this.dao.create(offer); offer.setId(id); this.createFakeFotos(id); // Удаление. HttpServletRequest req = mock(HttpServletRequest.class); HttpServletResponse resp = mock(HttpServletResponse.class); String expected = String.format("%s, объявление о продаже %s %s за %s рублей удалено.", offer.getUser().getName(), offer.getCar().getBrand().getName(), offer.getCar().getName(), offer.getPrice()); when(req.getParameter("id")).thenReturn(Integer.toString(id)); when(req.getParameter("name")).thenReturn("testUser1"); when(this.servlet.getServletContext()).thenReturn(ctx); when(ctx.getRequestDispatcher("/WEB-INF/views/offerDeletePost.jsp")).thenReturn(reqDesp); AttributeStorage storage = new AttributeStorage(); storage.set(req); this.servlet.doPost(req, resp); String actual = (String) req.getAttribute("msg"); assertEquals(expected, actual); } catch (Exception ex) { this.logger.error("ERROR", ex); ex.printStackTrace(); } } /** * Тестирует public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException. * Ошибка. Объявление не существует. */ @Test public void testDoPostErrorOfferNotExists() { try { HttpServletRequest req = mock(HttpServletRequest.class); HttpServletResponse resp = mock(HttpServletResponse.class); when(req.getParameter("id")).thenReturn("999"); when(req.getParameter("name")).thenReturn("testUser1"); when(this.servlet.getServletContext()).thenReturn(ctx); when(ctx.getRequestDispatcher("/WEB-INF/views/offerDeletePost.jsp")).thenReturn(reqDesp); AttributeStorage storage = new AttributeStorage(); storage.set(req); this.servlet.doPost(req, resp); String expected = "Объявление уже удалено или не существует."; String actual = (String) req.getAttribute("msg"); assertEquals(expected, actual); } catch (Exception ex) { this.logger.error("ERROR", ex); ex.printStackTrace(); } } /** * Тестирует public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException. * Ошибка. Пользователь не имеет прав для удаления объявления. */ @Test public void testDoPostErrorUserHasNoRights() { try { HttpServletRequest req = mock(HttpServletRequest.class); HttpServletResponse resp = mock(HttpServletResponse.class); when(req.getParameter("id")).thenReturn("1"); when(req.getParameter("name")).thenReturn("FakeUser"); when(this.servlet.getServletContext()).thenReturn(ctx); when(ctx.getRequestDispatcher("/WEB-INF/views/offerDeletePost.jsp")).thenReturn(reqDesp); AttributeStorage storage = new AttributeStorage(); storage.set(req); this.servlet.doPost(req, resp); String expected = "У вас нет прав для удаления этого объявления."; String actual = (String) req.getAttribute("msg"); assertEquals(expected, actual); } catch (Exception ex) { this.logger.error("ERROR", ex); ex.printStackTrace(); } } /** * Тестирует public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException. * Фатальная ошибка. */ @Test public void testDoPostFatalError() { try { HttpServletRequest req = mock(HttpServletRequest.class); HttpServletResponse resp = mock(HttpServletResponse.class); when(req.getParameter("id")).thenReturn("NotANumber"); when(req.getParameter("name")).thenReturn("FakeUser"); when(this.servlet.getServletContext()).thenReturn(ctx); when(ctx.getRequestDispatcher("/WEB-INF/views/offerDeletePost.jsp")).thenReturn(reqDesp); AttributeStorage storage = new AttributeStorage(); storage.set(req); this.servlet.doPost(req, resp); String expected = "Ошибка удаления объявления."; String actual = (String) req.getAttribute("msg"); assertEquals(expected, actual); } catch (Exception ex) { this.logger.error("ERROR", ex); ex.printStackTrace(); } } }
/* * Copyright 2000-2012 JetBrains s.r.o. * * 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.jetbrains.jps.model; import org.jetbrains.annotations.NotNull; import java.util.EventListener; public interface JpsEventDispatcher { @NotNull <T extends EventListener> T getPublisher(Class<T> listenerClass); void fireElementRenamed(@NotNull JpsNamedElement element, @NotNull String oldName, @NotNull String newName); void fireElementChanged(@NotNull JpsElement element); <T extends JpsElement> void fireElementAdded(@NotNull T element, @NotNull JpsElementChildRole<T> role); <T extends JpsElement> void fireElementRemoved(@NotNull T element, @NotNull JpsElementChildRole<T> role); }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.cosmos.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** The CassandraKeyspaceCreateUpdateParameters model. */ @JsonFlatten @Fluent public class CassandraKeyspaceCreateUpdateParameters extends ArmResourceProperties { @JsonIgnore private final ClientLogger logger = new ClientLogger(CassandraKeyspaceCreateUpdateParameters.class); /* * The standard JSON format of a Cassandra keyspace */ @JsonProperty(value = "properties.resource", required = true) private CassandraKeyspaceResource resource; /* * A key-value pair of options to be applied for the request. This * corresponds to the headers sent with the request. */ @JsonProperty(value = "properties.options", required = true) private Map<String, String> options; /** * Get the resource property: The standard JSON format of a Cassandra keyspace. * * @return the resource value. */ public CassandraKeyspaceResource resource() { return this.resource; } /** * Set the resource property: The standard JSON format of a Cassandra keyspace. * * @param resource the resource value to set. * @return the CassandraKeyspaceCreateUpdateParameters object itself. */ public CassandraKeyspaceCreateUpdateParameters withResource(CassandraKeyspaceResource resource) { this.resource = resource; return this; } /** * Get the options property: A key-value pair of options to be applied for the request. This corresponds to the * headers sent with the request. * * @return the options value. */ public Map<String, String> options() { return this.options; } /** * Set the options property: A key-value pair of options to be applied for the request. This corresponds to the * headers sent with the request. * * @param options the options value to set. * @return the CassandraKeyspaceCreateUpdateParameters object itself. */ public CassandraKeyspaceCreateUpdateParameters withOptions(Map<String, String> options) { this.options = options; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (resource() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property resource in model CassandraKeyspaceCreateUpdateParameters")); } else { resource().validate(); } if (options() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property options in model CassandraKeyspaceCreateUpdateParameters")); } } }
package com.example.s.why_no.servlet; import android.util.Log; import com.example.s.why_no.cache.Net; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; /** * Created by S on 2016/10/26. */ public class ToIntegralExchangeServlet { private String urlStr = Net.ACTION_INTEGRAL_EXCHANGE; /** * 查询货物列表 */ public String getJson(String phone,int integral , String shopname,String name ,String tel ,String region , String address,int integralid ,String img ) { //网络地址 通过字符串,生成URL对象 URL url = null; // 网络会话链接 HttpURLConnection conn = null; //获取网站返回的输入流 InputStream in = null; //每次读的字节数 byte[] data = new byte[1024]; //每次读到的字节数,一般是1024,如果到了最后一行就会少于1024,到了末尾就是 -1 int len = 0; //本地的输出流 ByteArrayOutputStream os; try { Log.v("lws", "使用httpurlconnection"); url = new URL(urlStr); // url = new URL("http://192.168.0.101/shop/public/appindex");//内网 // url = new URL("http://api.dataoke.com/index.php?r=goodsLink/android"); conn = (HttpURLConnection) url.openConnection(); //默认是get 方式 conn.setRequestMethod("POST"); conn.setReadTimeout(30000); // 设置是否向connection输出,如果是post请求,参数要放在http正文内,因此需要设为true conn.setDoOutput(true); // Post 请求不能使用缓存 conn.setUseCaches(false); //设置请求头 一般没特殊要求, 不需要 //conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect,所以下面这句可以不要 //conn.connect(); //要上传的参数 /** * 传参数 */ PrintWriter pw = new PrintWriter(conn.getOutputStream()); String content = "phone=" + URLEncoder.encode(phone, "UTF-8") + "&integral=" + URLEncoder.encode(String.valueOf(integral), "UTF-8") + "&shopname=" + URLEncoder.encode(shopname, "UTF-8") + "&name=" + URLEncoder.encode(name, "UTF-8") + "&tel=" + URLEncoder.encode(tel, "UTF-8") + "&region=" + URLEncoder.encode(region, "UTF-8") + "&address=" + URLEncoder.encode(address, "UTF-8") + "&integralid=" + URLEncoder.encode(String.valueOf(integralid), "UTF-8") + "&img=" + URLEncoder.encode(img, "UTF-8") ; pw.print(content); pw.flush(); pw.close(); int code = conn.getResponseCode(); System.out.println("状态码:" + code); //时候需要获取输入, 废话,当然需要返回,最少要返回状态吧。 所以默认是true //conn.setDoInput(true); in = conn.getInputStream(); os = new ByteArrayOutputStream(); while ((len = in.read(data)) != -1) { os.write(data, 0, len); } in.close(); return new String(os.toByteArray()); } catch (Exception e) { e.printStackTrace(); } return "error"; } }
package me.xdrop.jrand.generators.basics; import me.xdrop.jrand.Generator; import me.xdrop.jrand.annotation.Facade; import me.xdrop.jrand.model.basics.enums.CHARSET; @Facade(accessor = "string") public class StringGenerator extends Generator<String> { protected CharacterGenerator charGen; protected int min; protected int max; protected int length; public StringGenerator() { this.min = 1; this.max = 6; this.length = 0; this.charGen = new CharacterGenerator(); } /** * Set the pool of characters to choose from * * @param pool The pool of characters to choose from * @return The same generator */ public StringGenerator pool(String pool) { charGen.pool(pool); return this; } /** * Return only symbols * * @return The same generator */ public StringGenerator symbols() { charGen.symbols(); return this; } /** * Return only alphabet characters * * @return The same generator */ public StringGenerator alpha() { charGen.alpha(); return this; } /** * Add digits to the pool of elements this generator * will return * @return The same generator */ public StringGenerator addDigits() { charGen.addDigits(); return this; } /** * Add letters to the pool of elements this generator * will return * @return The same generator */ public StringGenerator addAlpha() { charGen.addAlpha(); return this; } /** * Add symbols to the pool of elements this generator * will return * @return The same generator */ public StringGenerator addSymbols() { charGen.addSymbols(); return this; } /** * Add a charset to the pool * @param charset The charset to add * @return The same generator */ public StringGenerator addCharset(CHARSET charset) { charGen.addCharset(charset); return this; } /** * Set the casing of the letters (in case alpha() is used) * * @param casing Casing of the letters * @return The same generator */ public StringGenerator casing(CharacterGenerator.Casing casing) { charGen.casing(casing); return this; } /** * Return only digits * * @return The same generator */ public StringGenerator digits() { charGen.digit(); return this; } /** * Set the casing of the letters (in case alpha() is used) * * "upper" is uppercase, "lower" is lowercase * * @param casing Casing of the letters. Use "upper" or "lower" * @return The same generator */ public StringGenerator casing(String casing) { charGen.casing(casing); return this; } /** * Set the range of the length of the string between minimum of * min and maximum of max * * @param min Minimum string length (inclusive) * @param max Maximum string length (inclusive) * @return The same generator */ public StringGenerator range(int min, int max) { this.min = min; this.max = max; return this; } /** * Set the length of the string * * @param length The length of the string * @return The same generator */ public StringGenerator length(int length) { this.length = length; return this; } @Override public String gen() { StringBuilder builder = new StringBuilder(8); int length; if (this.length > 0) { length = this.length; } else { length = new NaturalGenerator().min(min).max(max).gen(); } while (length > 0) { builder.append(charGen.gen()); length--; } return builder.toString(); } }
/* * 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.sharding.distsql.query; import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmConfiguration; import org.apache.shardingsphere.infra.distsql.query.DistSQLResultSet; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration; import org.apache.shardingsphere.sharding.api.config.rule.ShardingAutoTableRuleConfiguration; import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration; import org.apache.shardingsphere.sharding.api.config.strategy.keygen.KeyGenerateStrategyConfiguration; import org.apache.shardingsphere.sharding.api.config.strategy.sharding.NoneShardingStrategyConfiguration; import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; import org.apache.shardingsphere.sharding.distsql.handler.query.ShardingTableRulesUsedKeyGeneratorQueryResultSet; import org.apache.shardingsphere.sharding.distsql.parser.statement.ShowShardingTableRulesUsedKeyGeneratorStatement; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Properties; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public final class ShowShardingTableRulesUsedKeyGeneratorQueryResultSetTest { @Test public void assertGetRowData() { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); ShardingRule rule = mock(ShardingRule.class); when(rule.getConfiguration()).thenReturn(createRuleConfiguration()); when(database.getRuleMetaData().findSingleRule(ShardingRule.class)).thenReturn(Optional.of(rule)); DistSQLResultSet resultSet = new ShardingTableRulesUsedKeyGeneratorQueryResultSet(); ShowShardingTableRulesUsedKeyGeneratorStatement statement = mock(ShowShardingTableRulesUsedKeyGeneratorStatement.class); when(statement.getKeyGeneratorName()).thenReturn(Optional.of("snowflake")); resultSet.init(database, statement); List<Object> actual = new ArrayList<>(resultSet.getRowData()); assertThat(actual.size(), is(2)); assertThat(actual.get(0), is("table")); assertThat(actual.get(1), is("t_order")); actual = new ArrayList<>(resultSet.getRowData()); assertThat(actual.size(), is(2)); assertThat(actual.get(0), is("auto_table")); assertThat(actual.get(1), is("t_order_auto")); } private ShardingRuleConfiguration createRuleConfiguration() { ShardingRuleConfiguration result = new ShardingRuleConfiguration(); result.getTables().add(createShardingTableRuleConfiguration()); result.getAutoTables().add(createShardingAutoTableRuleConfiguration()); result.getBindingTableGroups().add("t_order,t_order_item"); result.setDefaultDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("user_id", "database_inline")); result.setDefaultTableShardingStrategy(new NoneShardingStrategyConfiguration()); result.getShardingAlgorithms().put("database_inline", createShardingInlineAlgorithmConfiguration("ds_${user_id % 2}")); result.getShardingAlgorithms().put("t_order_inline", createShardingInlineAlgorithmConfiguration("t_order_${order_id % 2}")); result.getShardingAlgorithms().put("auto_mod", createShardingAutoModAlgorithmConfiguration()); result.getKeyGenerators().put("snowflake", createKeyGeneratorConfiguration()); return result; } private ShardingAutoTableRuleConfiguration createShardingAutoTableRuleConfiguration() { ShardingAutoTableRuleConfiguration result = new ShardingAutoTableRuleConfiguration("t_order_auto", "ds_0, ds_1"); result.setShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "auto_mod")); result.setKeyGenerateStrategy(new KeyGenerateStrategyConfiguration("order_id", "snowflake")); return result; } private ShardingTableRuleConfiguration createShardingTableRuleConfiguration() { ShardingTableRuleConfiguration result = new ShardingTableRuleConfiguration("t_order", "ds_${0..1}.t_order_${0..1}"); result.setTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "t_order_inline")); result.setKeyGenerateStrategy(new KeyGenerateStrategyConfiguration("order_id", "snowflake")); return result; } private ShardingSphereAlgorithmConfiguration createShardingInlineAlgorithmConfiguration(final String algorithmExpression) { Properties props = new Properties(); props.put("algorithm-expression", algorithmExpression); return new ShardingSphereAlgorithmConfiguration("INLINE", props); } private ShardingSphereAlgorithmConfiguration createShardingAutoModAlgorithmConfiguration() { Properties props = new Properties(); props.put("sharding-count", 4); return new ShardingSphereAlgorithmConfiguration("MOD", props); } private ShardingSphereAlgorithmConfiguration createKeyGeneratorConfiguration() { return new ShardingSphereAlgorithmConfiguration("SNOWFLAKE", new Properties()); } }
package com.google.cloud.talent.v4beta1; import static io.grpc.MethodDescriptor.generateFullMethodName; import static io.grpc.stub.ClientCalls.asyncUnaryCall; import static io.grpc.stub.ClientCalls.blockingUnaryCall; import static io.grpc.stub.ClientCalls.futureUnaryCall; import static io.grpc.stub.ServerCalls.asyncUnaryCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; /** * * * <pre> * A service that handles profile management, including profile CRUD, * enumeration and search. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler (version 1.10.0)", comments = "Source: google/cloud/talent/v4beta1/profile_service.proto") public final class ProfileServiceGrpc { private ProfileServiceGrpc() {} public static final String SERVICE_NAME = "google.cloud.talent.v4beta1.ProfileService"; // Static method descriptors that strictly reflect the proto. @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") @java.lang.Deprecated // Use {@link #getListProfilesMethod()} instead. public static final io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.ListProfilesRequest, com.google.cloud.talent.v4beta1.ListProfilesResponse> METHOD_LIST_PROFILES = getListProfilesMethodHelper(); private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.ListProfilesRequest, com.google.cloud.talent.v4beta1.ListProfilesResponse> getListProfilesMethod; @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.ListProfilesRequest, com.google.cloud.talent.v4beta1.ListProfilesResponse> getListProfilesMethod() { return getListProfilesMethodHelper(); } private static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.ListProfilesRequest, com.google.cloud.talent.v4beta1.ListProfilesResponse> getListProfilesMethodHelper() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.ListProfilesRequest, com.google.cloud.talent.v4beta1.ListProfilesResponse> getListProfilesMethod; if ((getListProfilesMethod = ProfileServiceGrpc.getListProfilesMethod) == null) { synchronized (ProfileServiceGrpc.class) { if ((getListProfilesMethod = ProfileServiceGrpc.getListProfilesMethod) == null) { ProfileServiceGrpc.getListProfilesMethod = getListProfilesMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.ListProfilesRequest, com.google.cloud.talent.v4beta1.ListProfilesResponse> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName( "google.cloud.talent.v4beta1.ProfileService", "ListProfiles")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.ListProfilesRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.ListProfilesResponse .getDefaultInstance())) .setSchemaDescriptor( new ProfileServiceMethodDescriptorSupplier("ListProfiles")) .build(); } } } return getListProfilesMethod; } @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") @java.lang.Deprecated // Use {@link #getCreateProfileMethod()} instead. public static final io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.CreateProfileRequest, com.google.cloud.talent.v4beta1.Profile> METHOD_CREATE_PROFILE = getCreateProfileMethodHelper(); private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.CreateProfileRequest, com.google.cloud.talent.v4beta1.Profile> getCreateProfileMethod; @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.CreateProfileRequest, com.google.cloud.talent.v4beta1.Profile> getCreateProfileMethod() { return getCreateProfileMethodHelper(); } private static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.CreateProfileRequest, com.google.cloud.talent.v4beta1.Profile> getCreateProfileMethodHelper() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.CreateProfileRequest, com.google.cloud.talent.v4beta1.Profile> getCreateProfileMethod; if ((getCreateProfileMethod = ProfileServiceGrpc.getCreateProfileMethod) == null) { synchronized (ProfileServiceGrpc.class) { if ((getCreateProfileMethod = ProfileServiceGrpc.getCreateProfileMethod) == null) { ProfileServiceGrpc.getCreateProfileMethod = getCreateProfileMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.CreateProfileRequest, com.google.cloud.talent.v4beta1.Profile> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName( "google.cloud.talent.v4beta1.ProfileService", "CreateProfile")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.CreateProfileRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.Profile.getDefaultInstance())) .setSchemaDescriptor( new ProfileServiceMethodDescriptorSupplier("CreateProfile")) .build(); } } } return getCreateProfileMethod; } @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") @java.lang.Deprecated // Use {@link #getGetProfileMethod()} instead. public static final io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.GetProfileRequest, com.google.cloud.talent.v4beta1.Profile> METHOD_GET_PROFILE = getGetProfileMethodHelper(); private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.GetProfileRequest, com.google.cloud.talent.v4beta1.Profile> getGetProfileMethod; @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.GetProfileRequest, com.google.cloud.talent.v4beta1.Profile> getGetProfileMethod() { return getGetProfileMethodHelper(); } private static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.GetProfileRequest, com.google.cloud.talent.v4beta1.Profile> getGetProfileMethodHelper() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.GetProfileRequest, com.google.cloud.talent.v4beta1.Profile> getGetProfileMethod; if ((getGetProfileMethod = ProfileServiceGrpc.getGetProfileMethod) == null) { synchronized (ProfileServiceGrpc.class) { if ((getGetProfileMethod = ProfileServiceGrpc.getGetProfileMethod) == null) { ProfileServiceGrpc.getGetProfileMethod = getGetProfileMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.GetProfileRequest, com.google.cloud.talent.v4beta1.Profile> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName( "google.cloud.talent.v4beta1.ProfileService", "GetProfile")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.GetProfileRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.Profile.getDefaultInstance())) .setSchemaDescriptor(new ProfileServiceMethodDescriptorSupplier("GetProfile")) .build(); } } } return getGetProfileMethod; } @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") @java.lang.Deprecated // Use {@link #getUpdateProfileMethod()} instead. public static final io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.UpdateProfileRequest, com.google.cloud.talent.v4beta1.Profile> METHOD_UPDATE_PROFILE = getUpdateProfileMethodHelper(); private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.UpdateProfileRequest, com.google.cloud.talent.v4beta1.Profile> getUpdateProfileMethod; @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.UpdateProfileRequest, com.google.cloud.talent.v4beta1.Profile> getUpdateProfileMethod() { return getUpdateProfileMethodHelper(); } private static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.UpdateProfileRequest, com.google.cloud.talent.v4beta1.Profile> getUpdateProfileMethodHelper() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.UpdateProfileRequest, com.google.cloud.talent.v4beta1.Profile> getUpdateProfileMethod; if ((getUpdateProfileMethod = ProfileServiceGrpc.getUpdateProfileMethod) == null) { synchronized (ProfileServiceGrpc.class) { if ((getUpdateProfileMethod = ProfileServiceGrpc.getUpdateProfileMethod) == null) { ProfileServiceGrpc.getUpdateProfileMethod = getUpdateProfileMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.UpdateProfileRequest, com.google.cloud.talent.v4beta1.Profile> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName( "google.cloud.talent.v4beta1.ProfileService", "UpdateProfile")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.UpdateProfileRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.Profile.getDefaultInstance())) .setSchemaDescriptor( new ProfileServiceMethodDescriptorSupplier("UpdateProfile")) .build(); } } } return getUpdateProfileMethod; } @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") @java.lang.Deprecated // Use {@link #getDeleteProfileMethod()} instead. public static final io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.DeleteProfileRequest, com.google.protobuf.Empty> METHOD_DELETE_PROFILE = getDeleteProfileMethodHelper(); private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.DeleteProfileRequest, com.google.protobuf.Empty> getDeleteProfileMethod; @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.DeleteProfileRequest, com.google.protobuf.Empty> getDeleteProfileMethod() { return getDeleteProfileMethodHelper(); } private static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.DeleteProfileRequest, com.google.protobuf.Empty> getDeleteProfileMethodHelper() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.DeleteProfileRequest, com.google.protobuf.Empty> getDeleteProfileMethod; if ((getDeleteProfileMethod = ProfileServiceGrpc.getDeleteProfileMethod) == null) { synchronized (ProfileServiceGrpc.class) { if ((getDeleteProfileMethod = ProfileServiceGrpc.getDeleteProfileMethod) == null) { ProfileServiceGrpc.getDeleteProfileMethod = getDeleteProfileMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.DeleteProfileRequest, com.google.protobuf.Empty> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName( "google.cloud.talent.v4beta1.ProfileService", "DeleteProfile")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.DeleteProfileRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.protobuf.Empty.getDefaultInstance())) .setSchemaDescriptor( new ProfileServiceMethodDescriptorSupplier("DeleteProfile")) .build(); } } } return getDeleteProfileMethod; } @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") @java.lang.Deprecated // Use {@link #getSearchProfilesMethod()} instead. public static final io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.SearchProfilesRequest, com.google.cloud.talent.v4beta1.SearchProfilesResponse> METHOD_SEARCH_PROFILES = getSearchProfilesMethodHelper(); private static volatile io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.SearchProfilesRequest, com.google.cloud.talent.v4beta1.SearchProfilesResponse> getSearchProfilesMethod; @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.SearchProfilesRequest, com.google.cloud.talent.v4beta1.SearchProfilesResponse> getSearchProfilesMethod() { return getSearchProfilesMethodHelper(); } private static io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.SearchProfilesRequest, com.google.cloud.talent.v4beta1.SearchProfilesResponse> getSearchProfilesMethodHelper() { io.grpc.MethodDescriptor< com.google.cloud.talent.v4beta1.SearchProfilesRequest, com.google.cloud.talent.v4beta1.SearchProfilesResponse> getSearchProfilesMethod; if ((getSearchProfilesMethod = ProfileServiceGrpc.getSearchProfilesMethod) == null) { synchronized (ProfileServiceGrpc.class) { if ((getSearchProfilesMethod = ProfileServiceGrpc.getSearchProfilesMethod) == null) { ProfileServiceGrpc.getSearchProfilesMethod = getSearchProfilesMethod = io.grpc.MethodDescriptor .<com.google.cloud.talent.v4beta1.SearchProfilesRequest, com.google.cloud.talent.v4beta1.SearchProfilesResponse> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName( "google.cloud.talent.v4beta1.ProfileService", "SearchProfiles")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.SearchProfilesRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.cloud.talent.v4beta1.SearchProfilesResponse .getDefaultInstance())) .setSchemaDescriptor( new ProfileServiceMethodDescriptorSupplier("SearchProfiles")) .build(); } } } return getSearchProfilesMethod; } /** Creates a new async stub that supports all call types for the service */ public static ProfileServiceStub newStub(io.grpc.Channel channel) { return new ProfileServiceStub(channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static ProfileServiceBlockingStub newBlockingStub(io.grpc.Channel channel) { return new ProfileServiceBlockingStub(channel); } /** Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static ProfileServiceFutureStub newFutureStub(io.grpc.Channel channel) { return new ProfileServiceFutureStub(channel); } /** * * * <pre> * A service that handles profile management, including profile CRUD, * enumeration and search. * </pre> */ public abstract static class ProfileServiceImplBase implements io.grpc.BindableService { /** * * * <pre> * Lists profiles by filter. The order is unspecified. * </pre> */ public void listProfiles( com.google.cloud.talent.v4beta1.ListProfilesRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.ListProfilesResponse> responseObserver) { asyncUnimplementedUnaryCall(getListProfilesMethodHelper(), responseObserver); } /** * * * <pre> * Creates and returns a new profile. * </pre> */ public void createProfile( com.google.cloud.talent.v4beta1.CreateProfileRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile> responseObserver) { asyncUnimplementedUnaryCall(getCreateProfileMethodHelper(), responseObserver); } /** * * * <pre> * Gets the specified profile. * </pre> */ public void getProfile( com.google.cloud.talent.v4beta1.GetProfileRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile> responseObserver) { asyncUnimplementedUnaryCall(getGetProfileMethodHelper(), responseObserver); } /** * * * <pre> * Updates the specified profile and returns the updated result. * </pre> */ public void updateProfile( com.google.cloud.talent.v4beta1.UpdateProfileRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile> responseObserver) { asyncUnimplementedUnaryCall(getUpdateProfileMethodHelper(), responseObserver); } /** * * * <pre> * Deletes the specified profile. * Prerequisite: The profile has no associated applications or assignments * associated. * </pre> */ public void deleteProfile( com.google.cloud.talent.v4beta1.DeleteProfileRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { asyncUnimplementedUnaryCall(getDeleteProfileMethodHelper(), responseObserver); } /** * * * <pre> * Searches for profiles within a tenant. * For example, search by raw queries "software engineer in Mountain View" or * search by structured filters (location filter, education filter, etc.). * See * [SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest] * for more information. * </pre> */ public void searchProfiles( com.google.cloud.talent.v4beta1.SearchProfilesRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.SearchProfilesResponse> responseObserver) { asyncUnimplementedUnaryCall(getSearchProfilesMethodHelper(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getListProfilesMethodHelper(), asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.ListProfilesRequest, com.google.cloud.talent.v4beta1.ListProfilesResponse>( this, METHODID_LIST_PROFILES))) .addMethod( getCreateProfileMethodHelper(), asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.CreateProfileRequest, com.google.cloud.talent.v4beta1.Profile>(this, METHODID_CREATE_PROFILE))) .addMethod( getGetProfileMethodHelper(), asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.GetProfileRequest, com.google.cloud.talent.v4beta1.Profile>(this, METHODID_GET_PROFILE))) .addMethod( getUpdateProfileMethodHelper(), asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.UpdateProfileRequest, com.google.cloud.talent.v4beta1.Profile>(this, METHODID_UPDATE_PROFILE))) .addMethod( getDeleteProfileMethodHelper(), asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.DeleteProfileRequest, com.google.protobuf.Empty>(this, METHODID_DELETE_PROFILE))) .addMethod( getSearchProfilesMethodHelper(), asyncUnaryCall( new MethodHandlers< com.google.cloud.talent.v4beta1.SearchProfilesRequest, com.google.cloud.talent.v4beta1.SearchProfilesResponse>( this, METHODID_SEARCH_PROFILES))) .build(); } } /** * * * <pre> * A service that handles profile management, including profile CRUD, * enumeration and search. * </pre> */ public static final class ProfileServiceStub extends io.grpc.stub.AbstractStub<ProfileServiceStub> { private ProfileServiceStub(io.grpc.Channel channel) { super(channel); } private ProfileServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ProfileServiceStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfileServiceStub(channel, callOptions); } /** * * * <pre> * Lists profiles by filter. The order is unspecified. * </pre> */ public void listProfiles( com.google.cloud.talent.v4beta1.ListProfilesRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.ListProfilesResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getListProfilesMethodHelper(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Creates and returns a new profile. * </pre> */ public void createProfile( com.google.cloud.talent.v4beta1.CreateProfileRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile> responseObserver) { asyncUnaryCall( getChannel().newCall(getCreateProfileMethodHelper(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Gets the specified profile. * </pre> */ public void getProfile( com.google.cloud.talent.v4beta1.GetProfileRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile> responseObserver) { asyncUnaryCall( getChannel().newCall(getGetProfileMethodHelper(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Updates the specified profile and returns the updated result. * </pre> */ public void updateProfile( com.google.cloud.talent.v4beta1.UpdateProfileRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile> responseObserver) { asyncUnaryCall( getChannel().newCall(getUpdateProfileMethodHelper(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Deletes the specified profile. * Prerequisite: The profile has no associated applications or assignments * associated. * </pre> */ public void deleteProfile( com.google.cloud.talent.v4beta1.DeleteProfileRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { asyncUnaryCall( getChannel().newCall(getDeleteProfileMethodHelper(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Searches for profiles within a tenant. * For example, search by raw queries "software engineer in Mountain View" or * search by structured filters (location filter, education filter, etc.). * See * [SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest] * for more information. * </pre> */ public void searchProfiles( com.google.cloud.talent.v4beta1.SearchProfilesRequest request, io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.SearchProfilesResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getSearchProfilesMethodHelper(), getCallOptions()), request, responseObserver); } } /** * * * <pre> * A service that handles profile management, including profile CRUD, * enumeration and search. * </pre> */ public static final class ProfileServiceBlockingStub extends io.grpc.stub.AbstractStub<ProfileServiceBlockingStub> { private ProfileServiceBlockingStub(io.grpc.Channel channel) { super(channel); } private ProfileServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ProfileServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfileServiceBlockingStub(channel, callOptions); } /** * * * <pre> * Lists profiles by filter. The order is unspecified. * </pre> */ public com.google.cloud.talent.v4beta1.ListProfilesResponse listProfiles( com.google.cloud.talent.v4beta1.ListProfilesRequest request) { return blockingUnaryCall( getChannel(), getListProfilesMethodHelper(), getCallOptions(), request); } /** * * * <pre> * Creates and returns a new profile. * </pre> */ public com.google.cloud.talent.v4beta1.Profile createProfile( com.google.cloud.talent.v4beta1.CreateProfileRequest request) { return blockingUnaryCall( getChannel(), getCreateProfileMethodHelper(), getCallOptions(), request); } /** * * * <pre> * Gets the specified profile. * </pre> */ public com.google.cloud.talent.v4beta1.Profile getProfile( com.google.cloud.talent.v4beta1.GetProfileRequest request) { return blockingUnaryCall( getChannel(), getGetProfileMethodHelper(), getCallOptions(), request); } /** * * * <pre> * Updates the specified profile and returns the updated result. * </pre> */ public com.google.cloud.talent.v4beta1.Profile updateProfile( com.google.cloud.talent.v4beta1.UpdateProfileRequest request) { return blockingUnaryCall( getChannel(), getUpdateProfileMethodHelper(), getCallOptions(), request); } /** * * * <pre> * Deletes the specified profile. * Prerequisite: The profile has no associated applications or assignments * associated. * </pre> */ public com.google.protobuf.Empty deleteProfile( com.google.cloud.talent.v4beta1.DeleteProfileRequest request) { return blockingUnaryCall( getChannel(), getDeleteProfileMethodHelper(), getCallOptions(), request); } /** * * * <pre> * Searches for profiles within a tenant. * For example, search by raw queries "software engineer in Mountain View" or * search by structured filters (location filter, education filter, etc.). * See * [SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest] * for more information. * </pre> */ public com.google.cloud.talent.v4beta1.SearchProfilesResponse searchProfiles( com.google.cloud.talent.v4beta1.SearchProfilesRequest request) { return blockingUnaryCall( getChannel(), getSearchProfilesMethodHelper(), getCallOptions(), request); } } /** * * * <pre> * A service that handles profile management, including profile CRUD, * enumeration and search. * </pre> */ public static final class ProfileServiceFutureStub extends io.grpc.stub.AbstractStub<ProfileServiceFutureStub> { private ProfileServiceFutureStub(io.grpc.Channel channel) { super(channel); } private ProfileServiceFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ProfileServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfileServiceFutureStub(channel, callOptions); } /** * * * <pre> * Lists profiles by filter. The order is unspecified. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.ListProfilesResponse> listProfiles(com.google.cloud.talent.v4beta1.ListProfilesRequest request) { return futureUnaryCall( getChannel().newCall(getListProfilesMethodHelper(), getCallOptions()), request); } /** * * * <pre> * Creates and returns a new profile. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.Profile> createProfile(com.google.cloud.talent.v4beta1.CreateProfileRequest request) { return futureUnaryCall( getChannel().newCall(getCreateProfileMethodHelper(), getCallOptions()), request); } /** * * * <pre> * Gets the specified profile. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.Profile> getProfile(com.google.cloud.talent.v4beta1.GetProfileRequest request) { return futureUnaryCall( getChannel().newCall(getGetProfileMethodHelper(), getCallOptions()), request); } /** * * * <pre> * Updates the specified profile and returns the updated result. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.Profile> updateProfile(com.google.cloud.talent.v4beta1.UpdateProfileRequest request) { return futureUnaryCall( getChannel().newCall(getUpdateProfileMethodHelper(), getCallOptions()), request); } /** * * * <pre> * Deletes the specified profile. * Prerequisite: The profile has no associated applications or assignments * associated. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty> deleteProfile(com.google.cloud.talent.v4beta1.DeleteProfileRequest request) { return futureUnaryCall( getChannel().newCall(getDeleteProfileMethodHelper(), getCallOptions()), request); } /** * * * <pre> * Searches for profiles within a tenant. * For example, search by raw queries "software engineer in Mountain View" or * search by structured filters (location filter, education filter, etc.). * See * [SearchProfilesRequest][google.cloud.talent.v4beta1.SearchProfilesRequest] * for more information. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.cloud.talent.v4beta1.SearchProfilesResponse> searchProfiles(com.google.cloud.talent.v4beta1.SearchProfilesRequest request) { return futureUnaryCall( getChannel().newCall(getSearchProfilesMethodHelper(), getCallOptions()), request); } } private static final int METHODID_LIST_PROFILES = 0; private static final int METHODID_CREATE_PROFILE = 1; private static final int METHODID_GET_PROFILE = 2; private static final int METHODID_UPDATE_PROFILE = 3; private static final int METHODID_DELETE_PROFILE = 4; private static final int METHODID_SEARCH_PROFILES = 5; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final ProfileServiceImplBase serviceImpl; private final int methodId; MethodHandlers(ProfileServiceImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_LIST_PROFILES: serviceImpl.listProfiles( (com.google.cloud.talent.v4beta1.ListProfilesRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.ListProfilesResponse>) responseObserver); break; case METHODID_CREATE_PROFILE: serviceImpl.createProfile( (com.google.cloud.talent.v4beta1.CreateProfileRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile>) responseObserver); break; case METHODID_GET_PROFILE: serviceImpl.getProfile( (com.google.cloud.talent.v4beta1.GetProfileRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile>) responseObserver); break; case METHODID_UPDATE_PROFILE: serviceImpl.updateProfile( (com.google.cloud.talent.v4beta1.UpdateProfileRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.Profile>) responseObserver); break; case METHODID_DELETE_PROFILE: serviceImpl.deleteProfile( (com.google.cloud.talent.v4beta1.DeleteProfileRequest) request, (io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver); break; case METHODID_SEARCH_PROFILES: serviceImpl.searchProfiles( (com.google.cloud.talent.v4beta1.SearchProfilesRequest) request, (io.grpc.stub.StreamObserver<com.google.cloud.talent.v4beta1.SearchProfilesResponse>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private abstract static class ProfileServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { ProfileServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.cloud.talent.v4beta1.ProfileServiceProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("ProfileService"); } } private static final class ProfileServiceFileDescriptorSupplier extends ProfileServiceBaseDescriptorSupplier { ProfileServiceFileDescriptorSupplier() {} } private static final class ProfileServiceMethodDescriptorSupplier extends ProfileServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; ProfileServiceMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (ProfileServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new ProfileServiceFileDescriptorSupplier()) .addMethod(getListProfilesMethodHelper()) .addMethod(getCreateProfileMethodHelper()) .addMethod(getGetProfileMethodHelper()) .addMethod(getUpdateProfileMethodHelper()) .addMethod(getDeleteProfileMethodHelper()) .addMethod(getSearchProfilesMethodHelper()) .build(); } } } return result; } }
package org.tokenscript.attestation; import org.tokenscript.attestation.core.ASNEncodable; import org.tokenscript.attestation.core.Attestable; import org.tokenscript.attestation.core.AttestationCrypto; import org.tokenscript.attestation.core.ExceptionUtil; import org.tokenscript.attestation.core.SignatureUtility; import org.tokenscript.attestation.core.Verifiable; import java.io.IOException; import java.io.InvalidObjectException; import java.math.BigInteger; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.util.PublicKeyFactory; public class AttestedObject<T extends Attestable> implements ASNEncodable, Verifiable { private static final Logger logger = LogManager.getLogger(AttestedObject.class); private final T attestableObject; private final SignedIdentifierAttestation att; private final ProofOfExponent pok; private final AsymmetricKeyParameter userPublicKey; private final byte[] encoding; public AttestedObject(T attestableObject, SignedIdentifierAttestation att, AsymmetricKeyParameter userPublicKey, BigInteger attestationSecret, BigInteger chequeSecret, AttestationCrypto crypto) { this(attestableObject, att, userPublicKey, attestationSecret, chequeSecret, new byte[0], crypto); } public AttestedObject(T attestableObject, SignedIdentifierAttestation att, AsymmetricKeyParameter userPublicKey, BigInteger attestationSecret, BigInteger chequeSecret, byte[] unpredictableNumber, AttestationCrypto crypto) { this.attestableObject = attestableObject; this.att = att; this.userPublicKey = userPublicKey; try { this.pok = makeProof(attestationSecret, chequeSecret, unpredictableNumber, crypto); ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(ASN1Sequence.getInstance(this.attestableObject.getDerEncoding())); vec.add(ASN1Sequence.getInstance(att.getDerEncoding())); vec.add(ASN1Sequence.getInstance(pok.getDerEncoding())); this.encoding = new DERSequence(vec).getEncoded(); } catch (IOException e) { throw ExceptionUtil.makeRuntimeException(logger, "Could not decode asn1", e); } constructorCheck(); } public AttestedObject(T object, SignedIdentifierAttestation att, ProofOfExponent pok) { this.attestableObject = object; this.att = att; this.pok = pok; try { ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(ASN1Sequence.getInstance(object.getDerEncoding())); vec.add(ASN1Sequence.getInstance(att.getDerEncoding())); vec.add(ASN1Sequence.getInstance(pok.getDerEncoding())); this.encoding = new DERSequence(vec).getEncoded(); this.userPublicKey = PublicKeyFactory.createKey(att.getUnsignedAttestation().getSubjectPublicKeyInfo()); } catch (IOException e) { throw ExceptionUtil.makeRuntimeException(logger, "Could not encode asn1", e); } constructorCheck(); } public AttestedObject(byte[] derEncoding, AttestableObjectDecoder<T> decoder, AsymmetricKeyParameter publicAttestationSigningKey) { this.encoding = derEncoding; try { ASN1InputStream input = new ASN1InputStream(derEncoding); ASN1Sequence asn1 = ASN1Sequence.getInstance(input.readObject()); this.attestableObject = decoder.decode(asn1.getObjectAt(0).toASN1Primitive().getEncoded()); this.att = new SignedIdentifierAttestation(asn1.getObjectAt(1).toASN1Primitive().getEncoded(), publicAttestationSigningKey); this.pok = new UsageProofOfExponent(asn1.getObjectAt(2).toASN1Primitive().getEncoded()); this.userPublicKey = PublicKeyFactory.createKey(att.getUnsignedAttestation().getSubjectPublicKeyInfo()); } catch (IOException e) { throw ExceptionUtil.makeRuntimeException(logger, "Could not decode asn1", e); } constructorCheck(); } private void constructorCheck() { if (!verify()) { throw ExceptionUtil.throwException(logger, new IllegalArgumentException("Could not verify object")); } } public T getAttestableObject() { return attestableObject; } public SignedIdentifierAttestation getAtt() { return att; } public ProofOfExponent getPok() { return pok; } public AsymmetricKeyParameter getUserPublicKey() { return userPublicKey; } /** * Verifies that the redeem request will be accepted by the smart contract * @return true if the redeem request should be accepted by the smart contract */ public boolean checkValidity() { // CHECK: that it is an identifier attestation otherwise not all the checks of validity needed gets carried out try { byte[] attEncoded = att.getUnsignedAttestation().getDerEncoding(); IdentifierAttestation std = new IdentifierAttestation(attEncoded); // CHECK: perform the needed checks of an identifier attestation if (!std.checkValidity()) { logger.error("The attestation is not a valid standard attestation"); return false; } } catch (InvalidObjectException e) { logger.error("The attestation is invalid"); return false; } catch (IOException e) { logger.error("The attestation could not be parsed as a standard attestation"); return false; } // CHECK: that the object is still valid if (!getAttestableObject().checkValidity()) { logger.error("Object is not valid"); return false; } // CHECK: the Ethereum address on the attestation matches receivers signing key String attestationEthereumAddress = getAtt().getUnsignedAttestation().getAddress(); if (!attestationEthereumAddress.equals(SignatureUtility.addressFromKey(getUserPublicKey()))) { logger.error("The attestation is not to the same Ethereum user who is sending this request"); return false; } return true; } @Override public boolean verify() { if (!attestableObject.verify()) { logger.error("Could not verify attestable object"); return false; } if (!att.verify()) { logger.error("Could not verify attestation"); return false; } if (!AttestationCrypto.verifyEqualityProof(att.getUnsignedAttestation().getCommitment(), attestableObject.getCommitment(), pok)) { logger.error("Could not verify the consistency between the commitment in the attestation and the attested object"); return false; } return true; } private UsageProofOfExponent makeProof(BigInteger attestationSecret, BigInteger objectSecret, byte[] unpredictableNumber, AttestationCrypto crypto) { // TODO Bob should actually verify the attestable object is valid before trying to work with on the blockchain it to avoid wasting gas // We require that the internal attestation is an IdentifierAttestation UsageProofOfExponent pok = crypto.computeEqualityProof(att.getUnsignedAttestation().getCommitment(), attestableObject.getCommitment(), attestationSecret, objectSecret, unpredictableNumber); if (!crypto.verifyEqualityProof(att.getUnsignedAttestation().getCommitment(), attestableObject.getCommitment(), pok)) { throw ExceptionUtil.throwException(logger, new RuntimeException("The redeem proof did not verify")); } return pok; } @Override public byte[] getDerEncoding() { return encoding; } // TODO override equals and hashcode }
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * rbarkhouse - 2009-10-06 10:01:09 - initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings.anyattribute.reuse; import java.util.Iterator; import java.util.Map; import java.util.Properties; public class Root { private Map any = new Properties(); public Map getAny() { return any; } public void setAny(Map a) { any = a; } public boolean equals(Object object) { if (object instanceof Root) { Map collection1 = any; Map collection2 = ((Root) object).getAny(); if (collection1 == null && collection2 == null) { return true; } else if (collection1 == null && collection2.size() == 0) { return true; } else if (collection2 == null && collection1.size() == 0) { return true; } else if (collection1 == null && collection2.size() > 0) { return false; } else if (collection2 == null && collection1.size() > 0) { return false; } else if (any.size() != ((Root) object).getAny().size()) { return false; } else if (any.getClass() != ((Root) object).getAny().getClass()) { return false; } else { Iterator values1 = any.keySet().iterator(); Iterator values2 = ((Root) object).getAny().keySet().iterator(); while (values1.hasNext()) { Object key1 = values1.next(); Object key2 = values2.next(); if (!(key1.equals(key2) && any.get(key1).equals(collection2.get(key2)))) { return false; } } return true; } } return false; } public String toString() { String value = "Root:\n"; if (any == null) { return value; } Iterator keys = any.keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); value += "\tKey:" + key + " --> Value:" + any.get(key) + "\n"; } return value; } }
/** * 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.smartdata.protocol.protobuffer; import com.google.protobuf.ServiceException; import org.smartdata.model.ActionDescriptor; import org.smartdata.model.CmdletState; import org.smartdata.model.ActionInfo; import org.smartdata.model.CmdletDescriptor; import org.smartdata.protocol.AdminServerProto.ActionDescriptorProto; import org.smartdata.protocol.AdminServerProto.CmdletInfoProto; import org.smartdata.protocol.AdminServerProto.RuleInfoProto; import org.smartdata.protocol.ClientServerProto.ReportFileAccessEventRequestProto; import org.smartdata.model.RuleInfo; import org.smartdata.model.RuleState; import org.smartdata.model.CmdletInfo; import org.smartdata.metrics.FileAccessEvent; import org.smartdata.protocol.AdminServerProto.ActionInfoProto; import org.smartdata.protocol.AdminServerProto.ActionInfoProto.Builder; import java.io.IOException; import java.text.ParseException; import java.util.List; public class ProtoBufferHelper { private ProtoBufferHelper() { } public static IOException getRemoteException(ServiceException se) { Throwable e = se.getCause(); if (e == null) { return new IOException(se); } return e instanceof IOException ? (IOException) e : new IOException(se); } public static int convert(RuleState state) { return state.getValue(); } public static RuleState convert(int state) { return RuleState.fromValue(state); } public static RuleInfoProto convert(RuleInfo info) { return RuleInfoProto.newBuilder().setId(info.getId()) .setSubmitTime(info.getSubmitTime()) .setLastCheckTime(info.getLastCheckTime()) .setRuleText(info.getRuleText()) .setNumChecked(info.getNumChecked()) .setNumCmdsGen(info.getNumCmdsGen()) .setRulestateProto(convert(info.getState())).build(); } public static RuleInfo convert(RuleInfoProto proto) { return RuleInfo.newBuilder().setId(proto.getId()) .setSubmitTime(proto.getSubmitTime()) .setLastCheckTime(proto.getLastCheckTime()) .setRuleText(proto.getRuleText()) .setNumChecked(proto.getNumChecked()) .setNumCmdsGen(proto.getNumCmdsGen()) .setState(convert(proto.getRulestateProto())).build(); } public static CmdletInfo convert(CmdletInfoProto proto) { // TODO replace actionType with aids CmdletInfo.Builder builder = CmdletInfo.newBuilder(); builder.setCid(proto.getCid()) .setRid(proto.getRid()) .setState(CmdletState.fromValue(proto.getState())) .setParameters(proto.getParameters()) .setGenerateTime(proto.getGenerateTime()) .setStateChangedTime(proto.getStateChangedTime()); List<Long> list = proto.getAidsList(); builder.setAids(list); return builder.build(); } public static CmdletInfoProto convert(CmdletInfo info) { // TODO replace actionType with aids CmdletInfoProto.Builder builder = CmdletInfoProto.newBuilder(); builder.setCid(info.getCid()) .setRid(info.getRid()) .setState(info.getState().getValue()) .setParameters(info.getParameters()) .setGenerateTime(info.getGenerateTime()) .setStateChangedTime(info.getStateChangedTime()); builder.addAllAids(info.getAids()); return builder.build(); } public static ReportFileAccessEventRequestProto convert(FileAccessEvent event) { return ReportFileAccessEventRequestProto.newBuilder() .setFilePath(event.getPath()) .setAccessedBy(event.getAccessedBy()) .setFileId(event.getFileId()) .build(); } public static ActionInfoProto convert(ActionInfo actionInfo) { Builder builder = ActionInfoProto.newBuilder(); builder.setActionName(actionInfo.getActionName()) .setResult(actionInfo.getResult()) .setLog(actionInfo.getLog()) .setSuccessful(actionInfo.isSuccessful()) .setCreateTime(actionInfo.getCreateTime()) .setFinished(actionInfo.isFinished()) .setFinishTime(actionInfo.getFinishTime()) .setProgress(actionInfo.getProgress()) .setActionId(actionInfo.getActionId()) .setCmdletId(actionInfo.getCmdletId()); builder.addAllArgs(CmdletDescriptor.toArgList(actionInfo.getArgs())); return builder.build(); } public static ActionInfo convert(ActionInfoProto infoProto) { ActionInfo.Builder builder = ActionInfo.newBuilder(); builder.setActionName(infoProto.getActionName()) .setResult(infoProto.getResult()) .setLog(infoProto.getLog()) .setSuccessful(infoProto.getSuccessful()) .setCreateTime(infoProto.getCreateTime()) .setFinished(infoProto.getFinished()) .setFinishTime(infoProto.getFinishTime()) .setActionId(infoProto.getActionId()) .setCmdletId(infoProto.getCmdletId()); List<String> list = infoProto.getArgsList(); try { builder.setArgs(CmdletDescriptor.toArgMap(list)); } catch (ParseException e) { return null; } return builder.build(); } public static FileAccessEvent convert(final ReportFileAccessEventRequestProto event) { return new FileAccessEvent(event.getFilePath(), 0, event.getAccessedBy()); } public static ActionDescriptor convert(ActionDescriptorProto proto) { return ActionDescriptor.newBuilder() .setActionName(proto.getActionName()) .setComment(proto.getComment()) .setDisplayName(proto.getDisplayName()) .setUsage(proto.getUsage()) .build(); } public static ActionDescriptorProto convert(ActionDescriptor ac) { return ActionDescriptorProto.newBuilder() .setActionName(ac.getActionName()) .setComment(ac.getComment()) .setDisplayName(ac.getDisplayName()) .setUsage(ac.getUsage()) .build(); } }
/* * Copyright 2014 Alexey Andreev. * * 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.teavm.debugging.javascript; import java.util.Objects; /** * * @author Alexey Andreev */ public class JavaScriptLocation { private String script; private int line; private int column; public JavaScriptLocation(String script, int line, int column) { this.script = script; this.line = line; this.column = column; } public String getScript() { return script; } public int getLine() { return line; } public int getColumn() { return column; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof JavaScriptLocation)) { return false; } JavaScriptLocation other = (JavaScriptLocation)obj; return Objects.equals(other.script, script) && other.line == line && other.column == column; } @Override public int hashCode() { return (31 + column) * ((31 + line) * 31 + Objects.hashCode(script)); } @Override public String toString() { return script + ":(" + line + ";" + column + ")"; } }
/** * Created by tdh on 10/26/17. */ package me.tadho.markgo; import android.support.multidex.MultiDexApplication; import com.google.firebase.analytics.FirebaseAnalytics; import com.squareup.leakcanary.LeakCanary; import timber.log.Timber; public class App extends MultiDexApplication { @Override public void onCreate() { super.onCreate(); // Leak Canary init // if (LeakCanary.isInAnalyzerProcess(this)) { // // This process is dedicated to LeakCanary for heap analysis. // // You should not init your app in this process. // return; // } // LeakCanary.install(this); // Timber init if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } else { FirebaseAnalytics.getInstance(this) .setAnalyticsCollectionEnabled(true); } } }
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package cc.sc.modules.info.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cc.sc.common.persistence.Page; import cc.sc.common.service.CrudService; import cc.sc.modules.info.entity.Areas; import cc.sc.modules.info.dao.AreasDao; /** * 区域Service * @author 许军杰 * @version 2018-01-11 */ @Service @Transactional(readOnly = true) public class AreasService extends CrudService<AreasDao, Areas> { public Areas get(Integer id) { return super.get(id); } public List<Areas> findList(Areas areas) { return super.findList(areas); } public Page<Areas> findPage(Page<Areas> page, Areas areas) { return super.findPage(page, areas); } @Transactional(readOnly = false) public void save(Areas areas) { super.save(areas); } @Transactional(readOnly = false) public void delete(Areas areas) { super.delete(areas); } }
/* * 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 brooklyn.entity.network.bind; import java.util.Map; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Multimap; import com.google.common.reflect.TypeToken; import brooklyn.catalog.Catalog; import brooklyn.config.ConfigKey; import brooklyn.entity.Entity; import brooklyn.entity.annotation.Effector; import brooklyn.entity.basic.ConfigKeys; import brooklyn.entity.basic.DynamicGroup; import brooklyn.entity.basic.SoftwareProcess; import brooklyn.entity.proxying.ImplementedBy; import brooklyn.event.AttributeSensor; import brooklyn.event.basic.PortAttributeSensorAndConfigKey; import brooklyn.event.basic.Sensors; import brooklyn.location.basic.PortRanges; import brooklyn.util.flags.SetFromFlag; import brooklyn.util.net.Cidr; /** * This sets up a BIND DNS server. */ @Catalog(name="BIND", description="BIND is an Internet Domain Name Server.", iconUrl="classpath:///isc-logo.png") @ImplementedBy(BindDnsServerImpl.class) public interface BindDnsServer extends SoftwareProcess { @SetFromFlag("filter") ConfigKey<Predicate<? super Entity>> ENTITY_FILTER = ConfigKeys.newConfigKey(new TypeToken<Predicate<? super Entity>>() {}, "bind.entity.filter", "Filter for entities which will use the BIND DNS service for name resolution." + "Default is all instances of SoftwareProcess in the application.", Predicates.instanceOf(SoftwareProcess.class)); @SetFromFlag("domainName") ConfigKey<String> DOMAIN_NAME = ConfigKeys.newStringConfigKey( "bind.domain.name", "The DNS domain name to serve", "brooklyn.local"); @SetFromFlag("reverseLookupNetwork") ConfigKey<String> REVERSE_LOOKUP_NETWORK = ConfigKeys.newStringConfigKey( "bind.reverse-lookup.address", "Network address for reverse lookup zone"); @SetFromFlag("subnet") ConfigKey<String> MANAGEMENT_CIDR = ConfigKeys.newStringConfigKey( "bind.access.cidr", "Subnet CIDR or ACL allowed to access DNS", "0.0.0.0/0"); @SetFromFlag("hostnameSensor") ConfigKey<AttributeSensor<String>> HOSTNAME_SENSOR = ConfigKeys.newConfigKey(new TypeToken<AttributeSensor<String>>() {}, "bind.sensor.hostname", "Sensor on managed entities that reports the hostname"); PortAttributeSensorAndConfigKey DNS_PORT = new PortAttributeSensorAndConfigKey("bind.port", "BIND DNS port for TCP and UDP", PortRanges.fromString("53")); @SetFromFlag("zoneFileTemplate") ConfigKey<String> DOMAIN_ZONE_FILE_TEMPLATE = ConfigKeys.newStringConfigKey( "bind.template.domain-zone", "The BIND domain zone file to serve (as FreeMarker template)", "classpath://brooklyn/entity/network/bind/domain.zone"); @SetFromFlag("reverseZoneFileTemplate") ConfigKey<String> REVERSE_ZONE_FILE_TEMPLATE = ConfigKeys.newStringConfigKey( "bind.template.reverse-zone", "The BIND reverse lookup zone file to serve (as FreeMarker template)", "classpath://brooklyn/entity/network/bind/reverse.zone"); @SetFromFlag("namedConfTemplate") ConfigKey<String> NAMED_CONF_TEMPLATE = ConfigKeys.newStringConfigKey( "bind.template.named-conf", "The BIND named configuration file (as FreeMarker template)", "classpath://brooklyn/entity/network/bind/named.conf"); @SetFromFlag("updateRootZonesFile") ConfigKey<Boolean> UPDATE_ROOT_ZONES_FILE = ConfigKeys.newBooleanConfigKey( "bind.updateRootZones", "Instructs the entity to fetch the latest root zones file from ftp.rs.internic.net.", Boolean.FALSE); /* Reverse lookup attributes. */ AttributeSensor<Cidr> REVERSE_LOOKUP_CIDR = Sensors.newSensor(Cidr.class, "bind.reverse-lookup.cidr", "The network CIDR that hosts must have for reverse lookup entries " + "to be added (default uses server address /24)"); AttributeSensor<String> REVERSE_LOOKUP_DOMAIN = Sensors.newStringSensor( "bind.reverse-lookup.domain", "The in-addr.arpa reverse lookup domain name"); /* Configuration applicable to clients of the BIND DNS service. */ @SetFromFlag("replaceResolvConf") ConfigKey<Boolean> REPLACE_RESOLV_CONF = ConfigKeys.newBooleanConfigKey( "bind.resolv-conf.replce", "Set to replace resolv.conf with the template (default is to use eth0 script)", Boolean.FALSE); @SetFromFlag("interfaceConfigTemplate") ConfigKey<String> INTERFACE_CONFIG_TEMPLATE = ConfigKeys.newStringConfigKey( "bind.template.interface-cfg", "The network interface configuration file for clients (as FreeMarker template)", "classpath://brooklyn/entity/network/bind/ifcfg"); @SetFromFlag("interfaceConfigTemplate") ConfigKey<String> RESOLV_CONF_TEMPLATE = ConfigKeys.newStringConfigKey( "bind.template.resolv-conf", "The resolver configuration file for clients (as FreeMarker template)", "classpath://brooklyn/entity/network/bind/resolv.conf"); AttributeSensor<DynamicGroup> ENTITIES = Sensors.newSensor(DynamicGroup.class, "bind.entities", "The entities being managed by this server"); AttributeSensor<Multimap<String, String>> ADDRESS_MAPPINGS = Sensors.newSensor(new TypeToken<Multimap<String, String>>() {}, "bind.mappings", "All address mappings maintained by the server, in form address -> [names]"); AttributeSensor<Map<String, String>> A_RECORDS = Sensors.newSensor(new TypeToken<Map<String, String>>() {}, "bind.records.a", "All A records for the server, in form name -> address"); AttributeSensor<Multimap<String, String>> CNAME_RECORDS = Sensors.newSensor(new TypeToken<Multimap<String, String>>() {}, "bind.records.cname", "All CNAME records for the server, in form name -> [names]"); AttributeSensor<Map<String, String>> PTR_RECORDS = Sensors.newSensor(new TypeToken<Map<String, String>>() {}, "bind.records.ptr", "All PTR records for the server, in form address -> name. Entries will be in REVERSE_LOOKUP_CIDR. " + "Entries are guaranteed to have an inverse mapping in A_RECORDS."); AttributeSensor<Long> SERIAL = Sensors.newLongSensor( "bind.serial", "A serial number guaranteed to be valid for use in a modified domain.zone or reverse.zone file"); public Multimap<String, String> getAddressMappings(); /** * @return the IP to hostname mappings stored in this DNS server's conf file * @deprecated since 0.7.0 use {@link #PTR_RECORDS} instead. */ @Deprecated @Effector(description="Gets the IP to hostname mappings stored in this DNS server's conf file") public Map<String, String> getReverseMappings(); /** * @return the predicate used to filter entities for the Bind server to manage. */ Predicate<? super Entity> getEntityFilter(); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.drds.transform.v20150413; import java.util.ArrayList; import java.util.List; import com.aliyuncs.drds.model.v20150413.DescribeDrdsInstanceResponse; import com.aliyuncs.drds.model.v20150413.DescribeDrdsInstanceResponse.Data; import com.aliyuncs.drds.model.v20150413.DescribeDrdsInstanceResponse.Data.Vip; import com.aliyuncs.transform.UnmarshallerContext; public class DescribeDrdsInstanceResponseUnmarshaller { public static DescribeDrdsInstanceResponse unmarshall(DescribeDrdsInstanceResponse describeDrdsInstanceResponse, UnmarshallerContext context) { describeDrdsInstanceResponse.setRequestId(context.stringValue("DescribeDrdsInstanceResponse.RequestId")); describeDrdsInstanceResponse.setSuccess(context.booleanValue("DescribeDrdsInstanceResponse.Success")); Data data = new Data(); data.setDrdsInstanceId(context.stringValue("DescribeDrdsInstanceResponse.Data.DrdsInstanceId")); data.setType(context.stringValue("DescribeDrdsInstanceResponse.Data.Type")); data.setRegionId(context.stringValue("DescribeDrdsInstanceResponse.Data.RegionId")); data.setZoneId(context.stringValue("DescribeDrdsInstanceResponse.Data.ZoneId")); data.setDescription(context.stringValue("DescribeDrdsInstanceResponse.Data.Description")); data.setNetworkType(context.stringValue("DescribeDrdsInstanceResponse.Data.NetworkType")); data.setStatus(context.stringValue("DescribeDrdsInstanceResponse.Data.Status")); data.setCreateTime(context.longValue("DescribeDrdsInstanceResponse.Data.CreateTime")); data.setVersion(context.longValue("DescribeDrdsInstanceResponse.Data.Version")); List<Vip> vips = new ArrayList<Vip>(); for (int i = 0; i < context.lengthValue("DescribeDrdsInstanceResponse.Data.Vips.Length"); i++) { Vip vip = new Vip(); vip.setIP(context.stringValue("DescribeDrdsInstanceResponse.Data.Vips["+ i +"].IP")); vip.setPort(context.stringValue("DescribeDrdsInstanceResponse.Data.Vips["+ i +"].Port")); vip.setType(context.stringValue("DescribeDrdsInstanceResponse.Data.Vips["+ i +"].Type")); vips.add(vip); } data.setVips(vips); describeDrdsInstanceResponse.setData(data); return describeDrdsInstanceResponse; } }
/* * This file is part of Empires, licensed under the MIT License (MIT). * * Copyright (c) Crypnotic <https://www.crypnotic.me> * * 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 me.crypnotic.empires.command; import org.bukkit.Chunk; import me.crypnotic.empires.api.command.CommandContext; import me.crypnotic.empires.api.command.ICommand; import me.crypnotic.empires.api.empire.Empire; import me.crypnotic.empires.api.player.EmpirePlayer; public class ClaimCommand implements ICommand { @Override public void execute(EmpirePlayer player, CommandContext context) { if (player.getEmpire() != null) { Empire empire = player.getEmpire(); if (empire.isOwner(player.getUuid())) { Chunk chunk = player.getChunk(); Empire holder = getEmpireManager().getEmpireByChunk(chunk); if (holder == null) { // TODO check WorldGuard regions and other applicable // systems // TODO add some sort of restriction on territory claiming empire.getTerritory().add(chunk); empire.broadcast("&a" + player.getName() + " has claimed a new territory."); getEmpireManager().save(empire); } else { if (holder.equals(empire)) { player.message("&cYour empire has already claimed this territory."); } else { player.message("&c" + empire.getName() + " owns this territory!"); } } } else { player.message("&cYou must own your empire to claim territories."); } } else { player.message("&cYou must own an empire to claim territories."); } } @Override public String getName() { return "claim"; } @Override public String getDescription() { return "&eClaim more territory for your Empire"; } }
package pl.allegro.tech.hermes.client.webclient; import org.springframework.web.reactive.function.client.WebClient; import pl.allegro.tech.hermes.client.HermesMessage; import pl.allegro.tech.hermes.client.HermesResponse; import pl.allegro.tech.hermes.client.HermesSender; import reactor.core.publisher.Mono; import java.net.URI; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import static java.util.stream.Collectors.toMap; import static pl.allegro.tech.hermes.client.HermesResponseBuilder.hermesResponse; public class WebClientHermesSender implements HermesSender { private final static Mono<String> NO_BODY = Mono.just(""); private final WebClient webClient; public WebClientHermesSender(WebClient webClient) { this.webClient = webClient; } @Override public CompletableFuture<HermesResponse> send(URI uri, HermesMessage message) { return webClient.post() .uri(uri) .syncBody(message.getBody()) .headers(httpHeaders -> httpHeaders.setAll(message.getHeaders())) .exchange() .flatMap(response -> response .bodyToMono(String.class) .switchIfEmpty(NO_BODY) .map(body -> hermesResponse(message) .withBody(body) .withHttpStatus(response.rawStatusCode()) .withHeaderSupplier(header -> convertToCaseInsensitiveMap(response.headers().asHttpHeaders().toSingleValueMap()).get(header)) .build())) .toFuture(); } private TreeMap<String, String> convertToCaseInsensitiveMap(Map<String, String> hashMap) { return hashMap.entrySet().stream() .collect(toMap( Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> newVal, () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER) )); } }
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.linalg.api.ops.impl.transforms.custom; import lombok.val; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.autodiff.samediff.SameDiff; import org.nd4j.common.base.Preconditions; import org.nd4j.imports.NoOpNameFoundException; import org.nd4j.linalg.api.buffer.DataType; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.impl.transforms.BaseDynamicTransformOp; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.nd4j.linalg.ops.transforms.Transforms; public class ATan2 extends BaseDynamicTransformOp { public ATan2(SameDiff sameDiff, SDVariable y, SDVariable x) { super(sameDiff, new SDVariable[] {y, x} ,false); } /** * Note that the order of x and y match {@link java.lang.Math#atan2(double, double)}, * and are reversed when compared to OldATan2. * See {@link Transforms#atan2(org.nd4j.linalg.api.ndarray.INDArray, org.nd4j.linalg.api.ndarray.INDArray)} */ public ATan2(INDArray x, INDArray y) { this(x,y,null); } /** * Note that the order of x and y match {@link java.lang.Math#atan2(double, double)}, * and are reversed when compared to OldATan2. * See {@link Transforms#atan2(org.nd4j.linalg.api.ndarray.INDArray, org.nd4j.linalg.api.ndarray.INDArray)} */ public ATan2(INDArray x, INDArray y, INDArray z) { super(new INDArray[]{x, y}, wrapOrNull(z)); } public ATan2() {} @Override public String opName() { return "tf_atan2"; } @Override public String onnxName() { throw new NoOpNameFoundException("No onnx op opName found for " + opName()); } @Override public String tensorflowName() { return "Atan2"; } @Override public List<SDVariable> doDiff(List<SDVariable> i_v) { //Let z=atan2(r), with r=y/x //dz/dr = 1/(r^2+1), dr/dy = 1/x, dr/dx = -y/x^2 SDVariable y = larg(); SDVariable x = rarg(); val xGrad = sameDiff.math.neg(y.div(x.pow(2).add(y.pow(2)))).mul(i_v.get(0)); val yGrad = x.div(x.pow(2).add(y.pow(2))).mul(i_v.get(0)); return Arrays.asList(yGrad, xGrad); } @Override public List<DataType> calculateOutputDataTypes(List<DataType> dataTypes){ Preconditions.checkState(dataTypes != null && dataTypes.size() == 2, "Expected exactly 2 input datatypes for %s, got %s", getClass(), dataTypes); Preconditions.checkState(dataTypes.get(0) == dataTypes.get(1), "Input datatypes must be same type: got %s", dataTypes); return Collections.singletonList(dataTypes.get(0)); } }
package tools.fastlane.screengrab; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import com.jraska.falcon.Falcon; /** * <p>Screenshot strategy that delegates to Falcon for screenshot capture. <b>Requires * API level &gt;= 10</b></p> */ public class FalconScreenshotStrategy implements ScreenshotStrategy { private final Activity activity; public FalconScreenshotStrategy(Activity activity) { this.activity = activity; } @Override @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1) public void takeScreenshot(String screenshotName, ScreenshotCallback screenshotCallback) { screenshotCallback.screenshotCaptured(screenshotName, Falcon.takeScreenshotBitmap(activity)); } }
/******************************************************************************* * Copyright (c) 2018, 2020 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * 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.eclipse.microprofile.reactive.streams.operators; import org.eclipse.microprofile.reactive.streams.operators.spi.ReactiveStreamsEngine; import org.reactivestreams.Processor; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionStage; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; /** * A builder for a {@link Processor}. * <p> * The documentation for each operator uses marble diagrams to visualize how the operator functions. Each element * flowing in and out of the stream is represented as a coloured marble that has a value, with the operator * applying some transformation or some side effect, termination and error signals potentially being passed, and * for operators that subscribe to the stream, an output value being redeemed at the end. * <p> * Below is an example diagram labelling all the parts of the stream. * <p> * <img src="doc-files/example.png" alt="Example marble diagram"> * <p> * Instances of this interface are immutable. Methods which return a {@code ProcessorBuilder} will return a new instance. * * @param <T> The type of the elements that the processor consumes. * @param <R> The type of the elements that the processor emits. * @see ReactiveStreams */ public interface ProcessorBuilder<T, R> extends TransformingOperators<R>, FilteringOperators<R>, PeekingOperators<R>, ConsumingOperators<R>, ErrorHandlingOperators<R>, ConnectingOperators<R> { /** * {@inheritDoc} */ @Override <S> ProcessorBuilder<T, S> map(Function<? super R, ? extends S> mapper); /** * {@inheritDoc} */ @Override <S> ProcessorBuilder<T, S> flatMap(Function<? super R, ? extends PublisherBuilder<? extends S>> mapper); /** * {@inheritDoc} */ @Override <S> ProcessorBuilder<T, S> flatMapRsPublisher(Function<? super R, ? extends Publisher<? extends S>> mapper); /** * {@inheritDoc} */ @Override <S> ProcessorBuilder<T, S> flatMapCompletionStage(Function<? super R, ? extends CompletionStage<? extends S>> mapper); /** * {@inheritDoc} */ @Override <S> ProcessorBuilder<T, S> flatMapIterable(Function<? super R, ? extends Iterable<? extends S>> mapper); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> filter(Predicate<? super R> predicate); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> distinct(); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> limit(long maxSize); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> skip(long n); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> takeWhile(Predicate<? super R> predicate); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> dropWhile(Predicate<? super R> predicate); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> peek(Consumer<? super R> consumer); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> onError(Consumer<Throwable> errorHandler); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> onTerminate(Runnable action); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> onComplete(Runnable action); /** * {@inheritDoc} * @return A {@link SubscriberBuilder} that will invoke the action for each element of the stream. */ @Override SubscriberBuilder<T, Void> forEach(Consumer<? super R> action); /** * {@inheritDoc} * @return A new {@link SubscriberBuilder} for the stream. */ @Override SubscriberBuilder<T, Void> ignore(); /** * {@inheritDoc} * @return A new {@link SubscriberBuilder} for the stream. */ @Override SubscriberBuilder<T, Void> cancel(); /** * {@inheritDoc} * @return A new {@link SubscriberBuilder} for the reduction. */ @Override SubscriberBuilder<T, R> reduce(R identity, BinaryOperator<R> accumulator); /** * {@inheritDoc} * @return A new {@link SubscriberBuilder} for the reduction. */ @Override SubscriberBuilder<T, Optional<R>> reduce(BinaryOperator<R> accumulator); /** * {@inheritDoc} * @return A new {@link SubscriberBuilder} that will emit the collected result. */ @Override <S, A> SubscriberBuilder<T, S> collect(Collector<? super R, A, S> collector); /** * {@inheritDoc} * @return A new {@link SubscriberBuilder} that will emit the collected result. */ @Override <S> SubscriberBuilder<T, S> collect(Supplier<S> supplier, BiConsumer<S, ? super R> accumulator); /** * {@inheritDoc} * @return A new {@link SubscriberBuilder} that will emit the list. */ @Override SubscriberBuilder<T, List<R>> toList(); /** * {@inheritDoc} * @return A new {@link SubscriberBuilder}. */ @Override SubscriberBuilder<T, Optional<R>> findFirst(); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> onErrorResume(Function<Throwable, ? extends R> errorHandler); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> onErrorResumeWith(Function<Throwable, ? extends PublisherBuilder<? extends R>> errorHandler); /** * {@inheritDoc} */ @Override ProcessorBuilder<T, R> onErrorResumeWithRsPublisher(Function<Throwable, ? extends Publisher<? extends R>> errorHandler); /** * {@inheritDoc} */ @Override SubscriberBuilder<T, Void> to(Subscriber<? super R> subscriber); /** * {@inheritDoc} */ @Override <S> SubscriberBuilder<T, S> to(SubscriberBuilder<? super R, ? extends S> subscriber); /** * {@inheritDoc} */ @Override <S> ProcessorBuilder<T, S> via(ProcessorBuilder<? super R, ? extends S> processor); /** * {@inheritDoc} */ @Override <S> ProcessorBuilder<T, S> via(Processor<? super R, ? extends S> processor); /** * Build this stream, using the first {@link ReactiveStreamsEngine} found by the {@link java.util.ServiceLoader}. * * @return A {@link Processor} that will run this stream. */ Processor<T, R> buildRs(); /** * Build this stream, using the supplied {@link ReactiveStreamsEngine}. * * @param engine The engine to run the stream with. * @return A {@link Processor} that will run this stream. */ Processor<T, R> buildRs(ReactiveStreamsEngine engine); }
package similar; public class SimilarTest { public static void main(String[] args) { String Str_1 = "并合群集半羊兽"; //String Str_2 = "akcdefghijkl2uvwxz"; String Str_2 = "并合相位恐鸟"; // length int Length1 = Str_1.length(); int Length2 = Str_2.length(); int Distance = 0; if (Length1 == 0) { Distance = Length2; } if (Length2 == 0) { Distance = Length1; } if (Length1 != 0 && Length2 != 0) { int[][] Distance_Matrix = new int[Length1 + 1][Length2 + 1]; //编号 int Bianhao = 0; for (int i = 0; i <= Length1; i++) { Distance_Matrix[i][0] = Bianhao; Bianhao++; } Bianhao = 0; for (int i = 0; i <= Length2; i++) { Distance_Matrix[0][i] = Bianhao; Bianhao++; } char[] Str_1_CharArray = Str_1.toCharArray(); char[] Str_2_CharArray = Str_2.toCharArray(); for (int i = 1; i <= Length1; i++) { for (int j = 1; j <= Length2; j++) { if (Str_1_CharArray[i - 1] == Str_2_CharArray[j - 1]) { Distance = 0; } else { Distance = 1; } int Temp1 = Distance_Matrix[i - 1][j] + 1; int Temp2 = Distance_Matrix[i][j - 1] + 1; int Temp3 = Distance_Matrix[i - 1][j - 1] + Distance; Distance_Matrix[i][j] = Temp1 > Temp2 ? Temp2 : Temp1; Distance_Matrix[i][j] = Distance_Matrix[i][j] > Temp3 ? Temp3 : Distance_Matrix[i][j]; } } Distance = Distance_Matrix[Length1][Length2]; } double Aerfa = 1 - 1.0 * Distance / (Length1 > Length2 ? Length1 : Length2); System.out.println(Aerfa); } }
package pt.isel.pdm.g04.se2_1.serverside.bags; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import pt.isel.pdm.g04.se2_1.R; import pt.isel.pdm.g04.se2_1.clientside.CsCompanies; import pt.isel.pdm.g04.se2_1.helpers.HgDefs; import pt.isel.pdm.g04.se2_1.provider.HgDbSchema; public class Strike extends HashMap<String, String> implements HasId, Comparable<Strike> { public final static String LBL_COMPANY = "company"; public final static String LBL_DATES = "dates"; public static final String LBL_MONTH_FROM = "month_from"; public static final String LBL_DAY_FROM = "day_from"; public static final String LBL_MONTH_TO = "month_to"; public static final String LBL_DAY_TO = "day_to"; public static final String LBL_CANCELLED = "cancelled"; public static final int STRIKE_VW = 0; public static final int UN_STRIKE_VW = 1; public final int id; public final Company company; // Descreve a empresa afectada pela greve. public final String description; // Uma descrição da greve ("This is a strike description."); public final Date startDate, endDate; // Datas para o início e fim da greve ("2011-11-30 20:25:23"); public final String sourceLink; // URL da fonte dos dados ("http://example.com"); public final boolean allDay; // true se a greve for de dias inteiros (true) public final boolean canceled; // true se a greve tiver sido cancelada (false); public final Submitter submitter; // Descreve o autor do aviso. public Strike(Context ctx, int id, String description, Date startDate, Date endDate, String sourceLink, boolean allDay, boolean canceled, Submitter submitter, Company company) { this.id = id; this.description = description; this.startDate = startDate; this.endDate = endDate; this.sourceLink = sourceLink; this.allDay = allDay; this.canceled = canceled; this.submitter = submitter; this.company = company; SimpleDateFormat dateFormat = new SimpleDateFormat(HgDefs.MONTHDAY_4_STRING_FORMAT, Locale.getDefault()); SimpleDateFormat monthsDateFormat = new SimpleDateFormat(HgDefs.MONTH_3_STRING_FORMAT, Locale.getDefault()); SimpleDateFormat daysDateFormat = new SimpleDateFormat(HgDefs.DAY_2_STRING_FORMAT, Locale.getDefault()); String strikeFrom = dateFormat.format(startDate); String strikeTo = dateFormat.format(endDate); put(LBL_COMPANY, company.name); put(LBL_DATES, strikeFrom + (strikeFrom.equals(strikeTo) ? "" : " - " + strikeTo)); put(LBL_MONTH_FROM, monthsDateFormat.format(startDate)); put(LBL_DAY_FROM, daysDateFormat.format(startDate)); if (strikeFrom.equals(strikeTo)) { put(LBL_MONTH_TO, ""); put(LBL_DAY_TO, ""); } else { put(LBL_MONTH_TO, monthsDateFormat.format(endDate)); put(LBL_DAY_TO, daysDateFormat.format(endDate)); } put(LBL_CANCELLED, canceled ? ctx.getString(R.string.am_msg_cancelled) : ""); } public Strike(Context ctx, Builder builder) { this(ctx, builder.mId, builder.mDescription, builder.mStart_date, builder.mEnd_date, builder.mSource_link, builder.mAll_day, builder.mCanceled, builder.mSubmitter, builder.mCompany); } // region HasId public static Builder builder() { return new Builder(); } // endregion HasId // region Comparable public static Strike build(Context ctx, Cursor cursor) throws ParseException { int colId, colCompany, colDescription, colSource_link, colStartDate, colEndDate, colAllDay, colCancelled, colSubmitter; colId = cursor.getColumnIndex(HgDbSchema.COL_ID); colCompany = cursor.getColumnIndex(HgDbSchema.Strikes_vw.COL_COMPANY); colDescription = cursor.getColumnIndex(HgDbSchema.Strikes_vw.COL_DESCRIPTION); colSource_link = cursor.getColumnIndex(HgDbSchema.Strikes_vw.COL_SOURCE_LINK); colStartDate = cursor.getColumnIndex(HgDbSchema.Strikes_vw.COL_DATE_FROM); colEndDate = cursor.getColumnIndex(HgDbSchema.Strikes_vw.COL_DATE_TO); colAllDay = cursor.getColumnIndex(HgDbSchema.Strikes_vw.COL_ALL_DAY); colCancelled = cursor.getColumnIndex(HgDbSchema.Strikes_vw.COL_CANCELLED); // colSubmitter = cursor.getColumnIndex(HgDbSchema.Strikes_vw.COL_SUBMITTER); Strike result = null; DateFormat dateFormat = new SimpleDateFormat(HgDefs.DATETIME_14_STRING_FORMAT, Locale.getDefault()); int id = cursor.getInt(colId); Company company = new CsCompanies(ctx).load_cbg(Integer.parseInt(cursor.getString(colCompany))); String description = cursor.getString(colDescription); String source_link = cursor.getString(colSource_link); Date startDate = dateFormat.parse(cursor.getString(colStartDate)); Date endDate = dateFormat.parse(cursor.getString(colEndDate)); boolean allDay = cursor.getInt(colAllDay) > 0; boolean cancelled = cursor.getInt(colCancelled) > 0; Submitter submitter = null; return builder() .id(id).company(company).description(description).source_link(source_link) .start_date(startDate).end_date(endDate).all_day(allDay).cancelled(cancelled) .submitter(submitter).build(ctx); } // endregion Comparable // region Build from Cursor @Override public String toString() { SimpleDateFormat dateFormat = new SimpleDateFormat(HgDefs.MONTHDAY_4_STRING_FORMAT, Locale.getDefault()); String strikeStart = dateFormat.format(startDate); String strikeEnd = dateFormat.format(endDate); return strikeStart + (strikeStart.equals(strikeEnd) ? "" : " -> " + strikeEnd) + " -> " + company.name; } @Override public int getId() { return id; } @Override public int compareTo(@NonNull Strike another) { if (canceled != another.canceled) return canceled ? 1 : -1; if (id != another.id) return id - another.id; if (allDay != another.allDay) return allDay ? 1 : -1; int _descriptionCompare = description.compareTo(another.description); if (_descriptionCompare != 0) return _descriptionCompare; int _end_dateCompare = endDate.compareTo(another.endDate); if (_end_dateCompare != 0) return _end_dateCompare; int _source_linkCompare = sourceLink.compareTo(another.sourceLink); if (_source_linkCompare != 0) return _source_linkCompare; int _start_dateCompare = startDate.compareTo(another.startDate); if (_start_dateCompare != 0) return _start_dateCompare; int _companyCompare = company.compareTo(another.company); if (_companyCompare != 0) return _companyCompare; int _submitterCompare = submitter == null ? 0 : submitter.compareTo(another.submitter); if (_submitterCompare != 0) return _submitterCompare; return 0; } // endregion Build from Cursor // region Builder public static class Builder { private int mId; private String mDescription; private Date mStart_date, mEnd_date; private String mSource_link; private boolean mAll_day; private boolean mCanceled; private Submitter mSubmitter; private Company mCompany; public Builder id(int id) { this.mId = id; return this; } public Builder description(String description) { this.mDescription = description; return this; } public Builder start_date(Date start_date) { this.mStart_date = start_date; return this; } public Builder end_date(Date end_date) { this.mEnd_date = end_date; return this; } public Builder source_link(String source_link) { this.mSource_link = source_link; return this; } public Builder all_day(boolean all_day) { this.mAll_day = all_day; return this; } public Builder cancelled(boolean canceled) { this.mCanceled = canceled; return this; } public Builder submitter(Submitter submitter) { this.mSubmitter = submitter; return this; } public Builder company(Company company) { this.mCompany = company; return this; } public Strike build(Context ctx) { return new Strike(ctx, this); } } // endregion Builder }
package cn.finalteam.okhttpfinal.sample.http.model; import android.text.TextUtils; /** * Desction: * Author:pengjianbo * Date:15/9/26 下午10:56 */ public class GameInfo { private int gameId; private String name; private String packageName; private String gameState; private boolean hasActive; private boolean hasGift; private int commentCount; private String iconUrl; private int isHot; private int jingCount; private int playerCount; private int resourceId; private int totalSocre; private int openState;//开放状态 private String coverUrl;//封面图片 public int getGameId() { return gameId; } public void setGameId(int gameId) { this.gameId = gameId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getGameState() { return gameState; } public void setGameState(String gameState) { this.gameState = gameState; } public boolean isHasActive() { return hasActive; } public void setHasActive(boolean hasActive) { this.hasActive = hasActive; } public boolean isHasGift() { return hasGift; } public void setHasGift(boolean hasGift) { this.hasGift = hasGift; } public int getCommentCount() { return commentCount; } public void setCommentCount(int commentCount) { this.commentCount = commentCount; } public String getIconUrl() { if(!TextUtils.isEmpty(this.coverUrl)){ return coverUrl; } return iconUrl; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public int getIsHot() { return isHot; } public void setIsHot(int isHot) { this.isHot = isHot; } public int getJingCount() { return jingCount; } public void setJingCount(int jingCount) { this.jingCount = jingCount; } public int getPlayerCount() { return playerCount; } public void setPlayerCount(int playerCount) { this.playerCount = playerCount; } public int getResourceId() { return resourceId; } public void setResourceId(int resourceId) { this.resourceId = resourceId; } public int getTotalSocre() { return totalSocre; } public String getCoverUrl() { return coverUrl; } public void setCoverUrl(String coverUrl) { this.coverUrl = coverUrl; } public float getTotalSocreV() { if(this.totalSocre > 0){ return this.totalSocre / 10.0f; } return 0f; } public void setTotalSocre(int totalSocre) { this.totalSocre = totalSocre; } public int getOpenState() { return openState; } public void setOpenState(int openState) { this.openState = openState; } /** * 获取游戏的星级,转换 * @return */ public float getRating(){ if(this.totalSocre!=0){ float rating = this.totalSocre / 20.0f; return rating; } return 0f; } }
package jkind.lustre; import jkind.Assert; import jkind.lustre.visitors.ExprVisitor; public class UnaryExpr extends Expr { public final UnaryOp op; public final Expr expr; public UnaryExpr(Location location, UnaryOp op, Expr expr) { super(location); Assert.isNotNull(op); Assert.isNotNull(expr); this.op = op; this.expr = expr; } public UnaryExpr(UnaryOp op, Expr expr) { this(Location.NULL, op, expr); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
package io.quarkus.amazon.common.deployment; import java.util.List; import java.util.Optional; import java.util.function.Function; import org.jboss.jandex.DotName; import org.jboss.jandex.Type; import io.quarkus.amazon.common.runtime.AmazonClientApacheTransportRecorder; import io.quarkus.amazon.common.runtime.AmazonClientNettyTransportRecorder; import io.quarkus.amazon.common.runtime.AmazonClientRecorder; import io.quarkus.amazon.common.runtime.AmazonClientUrlConnectionTransportRecorder; import io.quarkus.amazon.common.runtime.AwsConfig; import io.quarkus.amazon.common.runtime.NettyHttpClientConfig; import io.quarkus.amazon.common.runtime.SdkBuildTimeConfig; import io.quarkus.amazon.common.runtime.SdkConfig; import io.quarkus.amazon.common.runtime.SyncHttpClientBuildTimeConfig; import io.quarkus.amazon.common.runtime.SyncHttpClientConfig; import io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem; import io.quarkus.arc.processor.BuildExtension; import io.quarkus.arc.processor.InjectionPointInfo; import io.quarkus.deployment.Feature; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.builditem.ExtensionSslNativeSupportBuildItem; import io.quarkus.deployment.builditem.FeatureBuildItem; import io.quarkus.runtime.RuntimeValue; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.core.SdkClient; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; abstract public class AbstractAmazonServiceProcessor { abstract protected Feature amazonServiceClientName(); abstract protected String configName(); abstract protected DotName syncClientName(); abstract protected DotName asyncClientName(); abstract protected String builtinInterceptorsPath(); protected void setupExtension(BeanRegistrationPhaseBuildItem beanRegistrationPhase, BuildProducer<ExtensionSslNativeSupportBuildItem> extensionSslNativeSupport, BuildProducer<FeatureBuildItem> feature, BuildProducer<AmazonClientInterceptorsPathBuildItem> interceptors, BuildProducer<AmazonClientBuildItem> clientProducer, SdkBuildTimeConfig buildTimeSdkConfig, SyncHttpClientBuildTimeConfig buildTimeSyncConfig) { feature.produce(new FeatureBuildItem(amazonServiceClientName())); extensionSslNativeSupport.produce(new ExtensionSslNativeSupportBuildItem(amazonServiceClientName())); interceptors.produce(new AmazonClientInterceptorsPathBuildItem(builtinInterceptorsPath())); Optional<DotName> syncClassName = Optional.empty(); Optional<DotName> asyncClassName = Optional.empty(); //Discover all clients injections in order to determine if async or sync client is required for (InjectionPointInfo injectionPoint : beanRegistrationPhase.getContext().get(BuildExtension.Key.INJECTION_POINTS)) { Type requiredType = injectionPoint.getRequiredType(); if (syncClientName().equals(requiredType.name())) { syncClassName = Optional.of(syncClientName()); } if (asyncClientName().equals(requiredType.name())) { asyncClassName = Optional.of(asyncClientName()); } } if (syncClassName.isPresent() || asyncClassName.isPresent()) { clientProducer.produce(new AmazonClientBuildItem(syncClassName, asyncClassName, configName(), buildTimeSdkConfig, buildTimeSyncConfig)); } } protected void createApacheSyncTransportBuilder(List<AmazonClientBuildItem> amazonClients, AmazonClientApacheTransportRecorder recorder, SyncHttpClientBuildTimeConfig buildSyncConfig, RuntimeValue<SyncHttpClientConfig> syncConfig, BuildProducer<AmazonClientSyncTransportBuildItem> clientSyncTransports) { Optional<AmazonClientBuildItem> matchingClientBuildItem = amazonClients.stream() .filter(c -> c.getAwsClientName().equals(configName())) .findAny(); matchingClientBuildItem.ifPresent(client -> { if (!client.getSyncClassName().isPresent()) { return; } if (buildSyncConfig.type != SyncHttpClientBuildTimeConfig.SyncClientType.APACHE) { return; } clientSyncTransports.produce( new AmazonClientSyncTransportBuildItem( client.getAwsClientName(), client.getSyncClassName().get(), recorder.configureSync(configName(), syncConfig))); }); } protected void createUrlConnectionSyncTransportBuilder(List<AmazonClientBuildItem> amazonClients, AmazonClientUrlConnectionTransportRecorder recorder, SyncHttpClientBuildTimeConfig buildSyncConfig, RuntimeValue<SyncHttpClientConfig> syncConfig, BuildProducer<AmazonClientSyncTransportBuildItem> clientSyncTransports) { Optional<AmazonClientBuildItem> matchingClientBuildItem = amazonClients.stream() .filter(c -> c.getAwsClientName().equals(configName())) .findAny(); matchingClientBuildItem.ifPresent(client -> { if (!client.getSyncClassName().isPresent()) { return; } if (buildSyncConfig.type != SyncHttpClientBuildTimeConfig.SyncClientType.URL) { return; } clientSyncTransports.produce( new AmazonClientSyncTransportBuildItem( client.getAwsClientName(), client.getSyncClassName().get(), recorder.configureSync(configName(), syncConfig))); }); } protected void createNettyAsyncTransportBuilder(List<AmazonClientBuildItem> amazonClients, AmazonClientNettyTransportRecorder recorder, RuntimeValue<NettyHttpClientConfig> asyncConfig, BuildProducer<AmazonClientAsyncTransportBuildItem> clientAsyncTransports) { Optional<AmazonClientBuildItem> matchingClientBuildItem = amazonClients.stream() .filter(c -> c.getAwsClientName().equals(configName())) .findAny(); matchingClientBuildItem.ifPresent(client -> { if (!client.getAsyncClassName().isPresent()) { return; } clientAsyncTransports.produce( new AmazonClientAsyncTransportBuildItem( client.getAwsClientName(), client.getAsyncClassName().get(), recorder.configureAsync(configName(), asyncConfig))); }); } protected void createClientBuilders(List<AmazonClientSyncTransportBuildItem> syncClientBuilders, List<AmazonClientAsyncTransportBuildItem> asyncClientBuilders, BuildProducer<AmazonClientBuilderBuildItem> builderProducer, Function<RuntimeValue<SdkHttpClient.Builder>, RuntimeValue<AwsClientBuilder>> syncFunc, Function<RuntimeValue<SdkAsyncHttpClient.Builder>, RuntimeValue<AwsClientBuilder>> asyncFunc) { String configName = configName(); Optional<RuntimeValue<SdkHttpClient.Builder>> syncClientBuilder = syncClientBuilders.stream() .filter(c -> configName.equals(c.getAwsClientName())) .map(c -> c.getClientBuilder()) .findFirst(); Optional<RuntimeValue<SdkAsyncHttpClient.Builder>> asyncClientBuilder = asyncClientBuilders.stream() .filter(c -> configName.equals(c.getAwsClientName())) .map(c -> c.getClientBuilder()) .findFirst(); if (!syncClientBuilder.isPresent() && !asyncClientBuilder.isPresent()) { return; } builderProducer.produce(new AmazonClientBuilderBuildItem(configName, syncClientBuilder.isPresent() ? syncFunc.apply(syncClientBuilder.get()) : null, asyncClientBuilder.isPresent() ? asyncFunc.apply(asyncClientBuilder.get()) : null)); } protected void buildClients(List<AmazonClientBuilderConfiguredBuildItem> configuredClients, Function<RuntimeValue<? extends AwsClientBuilder>, RuntimeValue<? extends SdkClient>> syncClient, Function<RuntimeValue<? extends AwsClientBuilder>, RuntimeValue<? extends SdkClient>> asyncClient) { for (AmazonClientBuilderConfiguredBuildItem client : configuredClients) { if (configName().equals(client.getAwsClientName())) { if (client.getSyncBuilder() != null) { syncClient.apply(client.getSyncBuilder()); } if (client.getAsyncBuilder() != null) { asyncClient.apply(client.getAsyncBuilder()); } } } } protected void initClientBuilders(List<AmazonClientBuilderBuildItem> clients, AmazonClientRecorder recorder, RuntimeValue<AwsConfig> awsConfigRuntime, RuntimeValue<SdkConfig> sdkConfigRuntime, SdkBuildTimeConfig sdkBuildConfig, BuildProducer<AmazonClientBuilderConfiguredBuildItem> producer) { Optional<AmazonClientBuilderBuildItem> matchingClientBuilderBuildItem = clients.stream() .filter(c -> c.getAwsClientName().equals(configName())) .findAny(); matchingClientBuilderBuildItem.ifPresent(client -> { RuntimeValue<? extends AwsClientBuilder> syncBuilder = null; RuntimeValue<? extends AwsClientBuilder> asyncBuilder = null; if (client.getSyncBuilder() != null) { syncBuilder = recorder.configure(client.getSyncBuilder(), awsConfigRuntime, sdkConfigRuntime, sdkBuildConfig, configName()); } if (client.getAsyncBuilder() != null) { asyncBuilder = recorder.configure(client.getAsyncBuilder(), awsConfigRuntime, sdkConfigRuntime, sdkBuildConfig, configName()); } producer.produce(new AmazonClientBuilderConfiguredBuildItem(configName(), syncBuilder, asyncBuilder)); }); } }
package com.tony.tmall.service.impl; import com.tony.tmall.util.PageUtils; import com.tony.tmall.util.Query; import org.springframework.stereotype.Service; import java.util.Map; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.tony.tmall.dao.CmsSubjectProductRelationDao; import com.tony.tmall.entity.CmsSubjectProductRelationEntity; import com.tony.tmall.service.CmsSubjectProductRelationService; @Service("cmsSubjectProductRelationService") public class CmsSubjectProductRelationServiceImpl extends ServiceImpl<CmsSubjectProductRelationDao, CmsSubjectProductRelationEntity> implements CmsSubjectProductRelationService { @Override public PageUtils queryPage(Map<String, Object> params) { IPage<CmsSubjectProductRelationEntity> page = this.page( new Query<CmsSubjectProductRelationEntity>().getPage(params), new QueryWrapper<CmsSubjectProductRelationEntity>() ); return new PageUtils(page); } }
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.starlarkbuildapi.java; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.Depset; import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions; import com.google.devtools.build.lib.starlarkbuildapi.FileApi; import com.google.devtools.build.lib.starlarkbuildapi.StarlarkActionFactoryApi; import com.google.devtools.build.lib.starlarkbuildapi.StarlarkRuleContextApi; import com.google.devtools.build.lib.starlarkbuildapi.core.ProviderApi; import com.google.devtools.build.lib.starlarkbuildapi.cpp.CcInfoApi; import com.google.devtools.build.lib.starlarkbuildapi.platform.ConstraintValueInfoApi; import javax.annotation.Nullable; import net.starlark.java.annot.Param; import net.starlark.java.annot.ParamType; import net.starlark.java.annot.StarlarkBuiltin; import net.starlark.java.annot.StarlarkMethod; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.NoneType; import net.starlark.java.eval.Sequence; import net.starlark.java.eval.StarlarkThread; import net.starlark.java.eval.StarlarkValue; /** Utilities for Java compilation support in Starlark. */ @StarlarkBuiltin(name = "java_common", doc = "Utilities for Java compilation support in Starlark.") public interface JavaCommonApi< FileT extends FileApi, JavaInfoT extends JavaInfoApi<FileT, ?, ?>, JavaToolchainT extends JavaToolchainStarlarkApiProviderApi, ConstraintValueT extends ConstraintValueInfoApi, StarlarkRuleContextT extends StarlarkRuleContextApi<ConstraintValueT>, StarlarkActionFactoryT extends StarlarkActionFactoryApi> extends StarlarkValue { @StarlarkMethod( name = "provider", structField = true, doc = "Returns the Java declared provider. <br>" + "The same value is accessible as <code>JavaInfo</code>. <br>" + "Prefer using <code>JavaInfo</code> in new code.") ProviderApi getJavaProvider(); @StarlarkMethod( name = "compile", doc = "Compiles Java source files/jars from the implementation of a Starlark rule and returns " + "a provider that represents the results of the compilation and can be added to " + "the set of providers emitted by this rule.", parameters = { @Param(name = "ctx", positional = true, named = false, doc = "The rule context."), @Param( name = "source_jars", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, defaultValue = "[]", doc = "A list of the jars to be compiled. At least one of source_jars or source_files" + " should be specified."), @Param( name = "source_files", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, defaultValue = "[]", doc = "A list of the Java source files to be compiled. At least one of source_jars or " + "source_files should be specified."), @Param(name = "output", positional = false, named = true), @Param( name = "output_source_jar", positional = false, named = true, allowedTypes = { @ParamType(type = FileApi.class), @ParamType(type = NoneType.class), }, defaultValue = "None", doc = "The output source jar. Optional. Defaults to `{output_jar}-src.jar` if unset."), @Param( name = "javac_opts", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)}, defaultValue = "[]", doc = "A list of the desired javac options. Optional."), @Param( name = "deps", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = JavaInfoApi.class)}, defaultValue = "[]", doc = "A list of dependencies. Optional."), @Param( name = "runtime_deps", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = JavaInfoApi.class)}, defaultValue = "[]", doc = "A list of runtime dependencies. Optional."), @Param( name = "exports", positional = false, named = true, allowedTypes = { @ParamType(type = Sequence.class, generic1 = JavaInfoApi.class), }, defaultValue = "[]", doc = "A list of exports. Optional."), @Param( name = "plugins", positional = false, named = true, allowedTypes = { @ParamType(type = Sequence.class, generic1 = JavaPluginInfoApi.class), @ParamType(type = Sequence.class, generic1 = JavaInfoApi.class) }, defaultValue = "[]", doc = "A list of plugins. Optional."), @Param( name = "exported_plugins", positional = false, named = true, allowedTypes = { @ParamType(type = Sequence.class, generic1 = JavaPluginInfoApi.class), @ParamType(type = Sequence.class, generic1 = JavaInfoApi.class) }, defaultValue = "[]", doc = "A list of exported plugins. Optional."), @Param( name = "native_libraries", positional = false, allowedTypes = {@ParamType(type = Sequence.class, generic1 = CcInfoApi.class)}, named = true, defaultValue = "[]", doc = "CC native library dependencies that are needed for this library."), @Param( name = "annotation_processor_additional_inputs", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, defaultValue = "[]", doc = "A list of inputs that the Java compilation action will take in addition to the " + "Java sources for annotation processing."), @Param( name = "annotation_processor_additional_outputs", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, defaultValue = "[]", doc = "A list of outputs that the Java compilation action will output in addition to " + "the class jar from annotation processing."), @Param( name = "strict_deps", defaultValue = "'ERROR'", positional = false, named = true, doc = "A string that specifies how to handle strict deps. Possible values: 'OFF', " + "'ERROR', 'WARN' and 'DEFAULT'. For more details see " + "https://docs.bazel.build/versions/main/bazel-user-manual.html#" + "flag--strict_java_deps. By default 'ERROR'."), @Param( name = "java_toolchain", positional = false, named = true, doc = "A JavaToolchainInfo to be used for this compilation. Mandatory."), @Param( name = "host_javabase", positional = false, named = true, doc = "Deprecated: You can drop this parameter (host_javabase is provided with " + "java_toolchain)", defaultValue = "None", disableWithFlag = BuildLanguageOptions.INCOMPATIBLE_JAVA_COMMON_PARAMETERS, valueWhenDisabled = "None"), @Param( name = "sourcepath", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, defaultValue = "[]"), @Param( name = "resources", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, defaultValue = "[]"), @Param(name = "neverlink", positional = false, named = true, defaultValue = "False"), @Param( name = "enable_annotation_processing", positional = false, named = true, defaultValue = "True", doc = "Disables annotation processing in this compilation, causing any annotation" + " processors provided in plugins or in exported_plugins of deps to be" + " ignored."), @Param( name = "enable_compile_jar_action", positional = false, named = true, defaultValue = "True", doc = "Enables header compilation or ijar creation. If set to False, it forces use of the" + " full class jar in the compilation classpaths of any dependants. Doing so is" + " intended for use by non-library targets such as binaries that do not have" + " dependants.") }, useStarlarkThread = true) JavaInfoT createJavaCompileAction( StarlarkRuleContextT starlarkRuleContext, Sequence<?> sourceJars, // <FileT> expected. Sequence<?> sourceFiles, // <FileT> expected. FileT outputJar, Object outputSourceJar, Sequence<?> javacOpts, // <String> expected. Sequence<?> deps, // <JavaInfoT> expected. Sequence<?> runtimeDeps, // <JavaInfoT> expected. Sequence<?> exports, // <JavaInfoT> expected. Sequence<?> plugins, // <JavaInfoT> expected. Sequence<?> exportedPlugins, // <JavaInfoT> expected. Sequence<?> nativeLibraries, // <CcInfoT> expected. Sequence<?> annotationProcessorAdditionalInputs, // <FileT> expected. Sequence<?> annotationProcessorAdditionalOutputs, // <FileT> expected. String strictDepsMode, JavaToolchainT javaToolchain, Object hostJavabase, Sequence<?> sourcepathEntries, // <FileT> expected. Sequence<?> resources, // <FileT> expected. Boolean neverlink, Boolean enableAnnotationProcessing, Boolean enableCompileJarAction, StarlarkThread thread) throws EvalException, InterruptedException; @StarlarkMethod( name = "run_ijar", doc = "Runs ijar on a jar, stripping it of its method bodies. This helps reduce rebuilding " + "of dependent jars during any recompiles consisting only of simple changes to " + "method implementations. The return value is typically passed to " + "<code><a class=\"anchor\" href=\"JavaInfo.html\">" + "JavaInfo</a>#compile_jar</code>.", parameters = { @Param(name = "actions", named = true, doc = "ctx.actions"), @Param(name = "jar", positional = false, named = true, doc = "The jar to run ijar on."), @Param( name = "target_label", positional = false, named = true, allowedTypes = { @ParamType(type = Label.class), @ParamType(type = NoneType.class), }, defaultValue = "None", doc = "A target label to stamp the jar with. Used for <code>add_dep</code> support. " + "Typically, you would pass <code>ctx.label</code> to stamp the jar " + "with the current rule's label."), @Param( name = "java_toolchain", positional = false, named = true, doc = "A JavaToolchainInfo to used to find the ijar tool."), }) FileApi runIjar( StarlarkActionFactoryT actions, FileT jar, Object targetLabel, JavaToolchainT javaToolchain) throws EvalException; @StarlarkMethod( name = "stamp_jar", doc = "Stamps a jar with a target label for <code>add_dep</code> support. " + "The return value is typically passed to " + "<code><a class=\"anchor\" href=\"JavaInfo.html\">" + "JavaInfo</a>#compile_jar</code>. " + "Prefer to use " + "<code><a class=\"anchor\" href=\"java_common.html#run_ijar\">run_ijar</a></code> " + "when possible.", parameters = { @Param( name = "actions", named = true, doc = "ctx.actions"), @Param( name = "jar", positional = false, named = true, doc = "The jar to run stamp_jar on."), @Param( name = "target_label", positional = false, named = true, doc = "A target label to stamp the jar with. Used for <code>add_dep</code> support. " + "Typically, you would pass <code>ctx.label</code> to stamp the jar " + "with the current rule's label."), @Param( name = "java_toolchain", positional = false, named = true, doc = "A JavaToolchainInfo to used to find the stamp_jar tool."), }) FileApi stampJar( StarlarkActionFactoryT actions, FileT jar, Label targetLabel, JavaToolchainT javaToolchain) throws EvalException; @StarlarkMethod( name = "pack_sources", doc = "Packs sources and source jars into a single source jar file. " + "The return value is typically passed to" + "<p><code><a class=\"anchor\" href=\"JavaInfo.html\">" + "JavaInfo</a>#source_jar</code></p>." + "At least one of parameters output_jar or output_source_jar is required.", parameters = { @Param(name = "actions", named = true, doc = "ctx.actions"), @Param( name = "output_jar", positional = false, named = true, allowedTypes = { @ParamType(type = FileApi.class), @ParamType(type = NoneType.class), }, defaultValue = "None", doc = "Deprecated: The output jar of the rule. Used to name the resulting source jar. " + "The parameter sets output_source_jar parameter to `{output_jar}-src.jar`." + "Use output_source_jar parameter directly instead.", disableWithFlag = BuildLanguageOptions.INCOMPATIBLE_JAVA_COMMON_PARAMETERS, valueWhenDisabled = "None"), @Param( name = "output_source_jar", positional = false, named = true, allowedTypes = { @ParamType(type = FileApi.class), @ParamType(type = NoneType.class), }, defaultValue = "None", doc = "The output source jar."), @Param( name = "sources", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, defaultValue = "[]", doc = "A list of Java source files to be packed into the source jar."), @Param( name = "source_jars", positional = false, named = true, allowedTypes = {@ParamType(type = Sequence.class, generic1 = FileApi.class)}, defaultValue = "[]", doc = "A list of source jars to be packed into the source jar."), @Param( name = "java_toolchain", positional = false, named = true, doc = "A JavaToolchainInfo to used to find the ijar tool."), @Param( name = "host_javabase", positional = false, named = true, doc = "Deprecated: You can drop this parameter (host_javabase is provided with " + "java_toolchain)", defaultValue = "None", disableWithFlag = BuildLanguageOptions.INCOMPATIBLE_JAVA_COMMON_PARAMETERS, valueWhenDisabled = "None"), }, allowReturnNones = true) @Nullable FileApi packSources( StarlarkActionFactoryT actions, Object outputJar, Object outputSourceJar, Sequence<?> sourceFiles, // <FileT> expected. Sequence<?> sourceJars, // <FileT> expected. JavaToolchainT javaToolchain, Object hostJavabase) throws EvalException; @StarlarkMethod( name = "default_javac_opts", // This function is experimental for now. documented = false, parameters = { @Param( name = "java_toolchain", positional = false, named = true, allowedTypes = {@ParamType(type = JavaToolchainStarlarkApiProviderApi.class)}, doc = "A JavaToolchainInfo to be used for retrieving the ijar " + "tool. Only set when use_ijar is True."), }) // TODO(b/78512644): migrate callers to passing explicit javacopts or using custom toolchains, and // delete ImmutableList<String> getDefaultJavacOpts(JavaToolchainT javaToolchain) throws EvalException; @StarlarkMethod( name = "merge", doc = "Merges the given providers into a single JavaInfo.", parameters = { @Param( name = "providers", positional = true, named = false, allowedTypes = {@ParamType(type = Sequence.class, generic1 = JavaInfoApi.class)}, doc = "The list of providers to merge."), }, useStarlarkThread = true) JavaInfoT mergeJavaProviders( Sequence<?> providers /* <JavaInfoT> expected. */, StarlarkThread thread) throws EvalException; @StarlarkMethod( name = "make_non_strict", doc = "Returns a new Java provider whose direct-jars part is the union of both the direct and" + " indirect jars of the given Java provider.", parameters = { @Param(name = "java_info", positional = true, named = false, doc = "The java info."), }) JavaInfoT makeNonStrict(JavaInfoT javaInfo); @StarlarkMethod( name = "JavaPluginInfo", doc = "The key used to retrieve the provider that contains information about the Java " + "plugins. The same value is accessible as <code>JavaPluginInfo</code>. <br>" + "Prefer using <code>JavaPluginInfo</code> in new code.", structField = true) ProviderApi getJavaPluginProvider(); @StarlarkMethod( name = "JavaToolchainInfo", doc = "The key used to retrieve the provider that contains information about the Java " + "toolchain being used.", structField = true) ProviderApi getJavaToolchainProvider(); @StarlarkMethod( name = "JavaRuntimeInfo", doc = "The key used to retrieve the provider that contains information about the Java " + "runtime being used.", structField = true) ProviderApi getJavaRuntimeProvider(); @StarlarkMethod( name = "MessageBundleInfo", doc = "The provider used to supply message bundles for translation", structField = true, enableOnlyWithFlag = BuildLanguageOptions.EXPERIMENTAL_GOOGLE_LEGACY_API) ProviderApi getMessageBundleInfo(); @StarlarkMethod( name = "add_constraints", doc = "Returns a copy of the given JavaInfo with the given constraints added.", parameters = { @Param( name = "java_info", positional = true, named = false, doc = "The JavaInfo to enhance."), @Param( name = "constraints", allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)}, named = true, positional = false, defaultValue = "[]", doc = "Constraints to add") }, enableOnlyWithFlag = BuildLanguageOptions.EXPERIMENTAL_GOOGLE_LEGACY_API) JavaInfoT addConstraints(JavaInfoT javaInfo, Sequence<?> constraints /* <String> expected. */) throws EvalException; @StarlarkMethod( name = "get_constraints", doc = "Returns a set of constraints added.", parameters = { @Param( name = "java_info", positional = true, named = false, doc = "The JavaInfo to get constraints from."), }, enableOnlyWithFlag = BuildLanguageOptions.EXPERIMENTAL_GOOGLE_LEGACY_API) Sequence<String> getConstraints(JavaInfoT javaInfo); @StarlarkMethod( name = "set_annotation_processing", doc = "Returns a copy of the given JavaInfo with the given annotation_processing info.", parameters = { @Param( name = "java_info", positional = true, named = false, doc = "The JavaInfo to enhance."), @Param( name = "enabled", named = true, positional = false, defaultValue = "False", doc = "Returns true if the rule uses annotation processing."), @Param( name = "processor_classnames", allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)}, named = true, positional = false, defaultValue = "[]", doc = "Class names of annotation processors applied to this rule."), @Param( name = "processor_classpath", allowedTypes = { @ParamType(type = Depset.class), @ParamType(type = NoneType.class), }, named = true, positional = false, defaultValue = "None", doc = "Class names of annotation processors applied to this rule."), @Param( name = "class_jar", allowedTypes = { @ParamType(type = FileApi.class), @ParamType(type = NoneType.class), }, named = true, positional = false, defaultValue = "None", doc = "Jar file that is the result of annotation processing for this rule, or None."), @Param( name = "source_jar", allowedTypes = { @ParamType(type = FileApi.class), @ParamType(type = NoneType.class), }, named = true, positional = false, defaultValue = "None", doc = "Source archive resulting from annotation processing of this rule, or None."), }, enableOnlyWithFlag = BuildLanguageOptions.EXPERIMENTAL_GOOGLE_LEGACY_API) JavaInfoT setAnnotationProcessing( JavaInfoT javaInfo, boolean enabled, Sequence<?> processorClassnames /* <String> expected. */, Object processorClasspath, Object classJar, Object sourceJar) throws EvalException; @StarlarkMethod( name = "java_toolchain_label", doc = "Returns the toolchain's label.", parameters = { @Param(name = "java_toolchain", positional = true, named = false, doc = "The toolchain."), }, enableOnlyWithFlag = BuildLanguageOptions.EXPERIMENTAL_GOOGLE_LEGACY_API) Label getJavaToolchainLabel(JavaToolchainStarlarkApiProviderApi toolchain) throws EvalException; @StarlarkMethod( name = "BootClassPathInfo", doc = "The provider used to supply bootclasspath information", structField = true) ProviderApi getBootClassPathInfo(); /** Returns target kind. */ @StarlarkMethod( name = "target_kind", parameters = { @Param(name = "target", positional = true, named = false, doc = "The target."), }, documented = false, useStarlarkThread = true) String getTargetKind(Object target, StarlarkThread thread) throws EvalException; @StarlarkMethod( name = "to_java_binary_info", doc = "Returns a copy of the given JavaInfo with minimal info returned by a java_binary", parameters = { @Param( name = "java_info", positional = true, named = false, doc = "The JavaInfo to enhance."), }, useStarlarkThread = true) JavaInfoT toJavaBinaryInfo(JavaInfoT javaInfo, StarlarkThread thread) throws EvalException; }
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.windows.media.animation; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.windows.media.animation.VectorAnimationBase; import system.windows.media.animation.VectorAnimationUsingKeyFrames; import system.windows.media.animation.VectorKeyFrameCollection; import system.windows.markup.IAddChild; import system.windows.markup.IAddChildImplementation; /** * The base .NET class managing System.Windows.Media.Animation.VectorAnimationUsingKeyFrames, PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Media.Animation.VectorAnimationUsingKeyFrames" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Media.Animation.VectorAnimationUsingKeyFrames</a> */ public class VectorAnimationUsingKeyFrames extends VectorAnimationBase implements system.windows.markup.IAddChild { /** * Fully assembly qualified name: PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 */ public static final String assemblyFullName = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; /** * Assembly name: PresentationCore */ public static final String assemblyShortName = "PresentationCore"; /** * Qualified class name: System.Windows.Media.Animation.VectorAnimationUsingKeyFrames */ public static final String className = "System.Windows.Media.Animation.VectorAnimationUsingKeyFrames"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public VectorAnimationUsingKeyFrames(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link VectorAnimationUsingKeyFrames}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link VectorAnimationUsingKeyFrames} instance * @throws java.lang.Throwable in case of error during cast operation */ public static VectorAnimationUsingKeyFrames cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new VectorAnimationUsingKeyFrames(from.getJCOInstance()); } // Constructors section public VectorAnimationUsingKeyFrames() throws Throwable { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Methods section public boolean ShouldSerializeKeyFrames() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Invoke("ShouldSerializeKeyFrames"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public VectorAnimationUsingKeyFrames CloneNewVectorAnimationUsingKeyFrames() throws Throwable, system.InvalidOperationException, system.ArgumentNullException, system.ArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objClone = (JCObject)classInstance.Invoke("Clone"); return new VectorAnimationUsingKeyFrames(objClone); } catch (JCNativeException jcne) { throw translateException(jcne); } } public VectorAnimationUsingKeyFrames CloneCurrentValueNewVectorAnimationUsingKeyFrames() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.FormatException, system.PlatformNotSupportedException, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objCloneCurrentValue = (JCObject)classInstance.Invoke("CloneCurrentValue"); return new VectorAnimationUsingKeyFrames(objCloneCurrentValue); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIAddChild method available in IAddChild to obtain an object with an invocable method */ @Deprecated public void AddChild(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIAddChild to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIAddChild method available in IAddChild to obtain an object with an invocable method */ @Deprecated public void AddText(java.lang.String text) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIAddChild to obtain the full interface."); } // Properties section public boolean getIsAdditive() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.ArgumentOutOfRangeException, system.NotSupportedException, system.IndexOutOfRangeException, system.FormatException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Get("IsAdditive"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setIsAdditive(boolean IsAdditive) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.FormatException, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("IsAdditive", IsAdditive); } catch (JCNativeException jcne) { throw translateException(jcne); } } public boolean getIsCumulative() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.ArgumentOutOfRangeException, system.NotSupportedException, system.IndexOutOfRangeException, system.FormatException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Get("IsCumulative"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setIsCumulative(boolean IsCumulative) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.FormatException, system.NotSupportedException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("IsCumulative", IsCumulative); } catch (JCNativeException jcne) { throw translateException(jcne); } } public VectorKeyFrameCollection getKeyFrames() throws Throwable, system.ArgumentNullException, system.ArgumentException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.ArgumentOutOfRangeException, system.componentmodel.Win32Exception, system.IndexOutOfRangeException, system.FormatException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject val = (JCObject)classInstance.Get("KeyFrames"); return new VectorKeyFrameCollection(val); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void setKeyFrames(VectorKeyFrameCollection KeyFrames) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.FormatException, system.ArrayTypeMismatchException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Set("KeyFrames", KeyFrames == null ? null : KeyFrames.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Instance Events section }
package rmblworx.tools.timey.gui.config; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.junit.Test; /* * Copyright 2014-2015 Christian Raue * MIT License http://opensource.org/licenses/mit-license.php */ /** * Tests fürs Speichern/Laden der GUI-Konfiguration. * @author Christian Raue {@literal <christian.raue@gmail.com>} */ public class ConfigStorageTest { /** * Testet das Speichern der Konfiguration. * @throws IOException */ @Test public final void testSaveDefaultConfig() throws IOException { // Standardkonfiguration erzeugen final Config config = ConfigManager.getNewDefaultConfig(); // Konfiguration speichern final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new ConfigStorage().saveConfig(config, outputStream); final Map<String, String> testCases = new HashMap<>(4); testCases.put(ConfigStorage.PROP_LOCALE, String.format("%s", config.getLocale())); testCases.put(ConfigStorage.PROP_MINIMIZE_TO_TRAY, String.format("%s", config.isMinimizeToTray())); testCases.put(ConfigStorage.PROP_STOPWATCH_SHOW_MILLIS, String.format("%s", config.isStopwatchShowMilliseconds())); testCases.put(ConfigStorage.PROP_ACTIVE_TAB, String.format("%d", config.getActiveTab())); // sicherstellen, dass gespeicherte Konfiguration korrekte Einträge enthält final String content = outputStream.toString(); for (final Entry<String, String> testCase : testCases.entrySet()) { assertTrue(content, content.contains(String.format("<entry key=\"%s\">%s</entry>", testCase.getKey(), testCase.getValue()))); } } /** * Testet das Laden einer Konfiguration. * @throws IOException */ @Test public final void testLoadConfig() throws IOException { // Werte festlegen, die von Standardkonfiguration abweichen final Config expectedConfig = ConfigManager.getNewDefaultConfig(); expectedConfig.setLocale(expectedConfig.getDefaultLocale().equals(Locale.ENGLISH) ? Locale.GERMAN : Locale.ENGLISH); expectedConfig.setMinimizeToTray(!expectedConfig.isMinimizeToTray()); expectedConfig.setStopwatchShowMilliseconds(!expectedConfig.isStopwatchShowMilliseconds()); expectedConfig.setActiveTab(expectedConfig.getActiveTab() + 1); // Konfiguration speichern final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { new ConfigStorage().getConfigAsProperties(expectedConfig).storeToXML(outputStream, null); } catch (final IOException e) { fail(e.getLocalizedMessage()); } // gespeicherte Konfiguration laden final Config actualConfig = new ConfigStorage().loadConfig(redirectOutputToInput(outputStream)); // sicherstellen, dass geladene Konfiguration der erwarteten Konfiguration entspricht assertEquals(getConfigAsString(expectedConfig), getConfigAsString(actualConfig)); } /** * Testet das Laden einer leeren Konfiguration und Befüllung mit Standardwerten. * @throws IOException */ @Test public final void testLoadEmptyConfig() throws IOException { // leere Konfiguration speichern final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { new Properties().storeToXML(outputStream, null); } catch (final IOException e) { fail(e.getLocalizedMessage()); } // gespeicherte Konfiguration laden, sollte dabei mit Standardwerten gefüllt werden final Config emptyConfig = new ConfigStorage().loadConfig(redirectOutputToInput(outputStream)); // sicherstellen, dass geladene Konfiguration der Standardkonfiguration entspricht assertEquals(getConfigAsString(ConfigManager.getNewDefaultConfig()), getConfigAsString(emptyConfig)); } /** * Testet das Laden einer Konfiguration mit ungültigen Werten. * @throws IOException */ @Test public final void testLoadConfigWithInvalidValues() throws IOException { // Werte festlegen final Properties props = new Properties(); final String invalidValue = "blabla"; props.put(ConfigStorage.PROP_LOCALE, invalidValue); props.put(ConfigStorage.PROP_MINIMIZE_TO_TRAY, invalidValue); props.put(ConfigStorage.PROP_STOPWATCH_SHOW_MILLIS, invalidValue); props.put(ConfigStorage.PROP_ACTIVE_TAB, invalidValue); // Konfiguration speichern final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { props.storeToXML(outputStream, null); } catch (final IOException e) { fail(e.getLocalizedMessage()); } // gespeicherte Konfiguration laden, sollte dabei mit Standardwerten gefüllt werden final Config emptyConfig = new ConfigStorage().loadConfig(redirectOutputToInput(outputStream)); // erwartete Konfiguration final Config expectedConfig = ConfigManager.getNewDefaultConfig(); expectedConfig.setMinimizeToTray(false); expectedConfig.setStopwatchShowMilliseconds(false); // sicherstellen, dass geladene Konfiguration der erwarteten Konfiguration entspricht assertEquals(getConfigAsString(expectedConfig), getConfigAsString(emptyConfig)); } /** * Testet das Laden einer ungültigen Konfiguration. * @throws IOException */ @Test public final void testLoadInvalidConfig() throws IOException { // ungültige Konfiguration speichern final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { outputStream.write("kein gültiges XML-Dokument".getBytes("UTF-8")); } catch (final IOException e) { fail(e.getLocalizedMessage()); } // gespeicherte Konfiguration laden, sollte dabei mit Standardwerten gefüllt werden final Config emptyConfig = new ConfigStorage().loadConfig(redirectOutputToInput(outputStream), true); // sicherstellen, dass geladene Konfiguration der Standardkonfiguration entspricht assertEquals(getConfigAsString(ConfigManager.getNewDefaultConfig()), getConfigAsString(emptyConfig)); } /** * Testet das Werfen einer {@link IOException} beim Laden einer ungültigen Konfiguration. * @throws IOException */ @Test(expected = IOException.class) public final void testLoadInvalidConfigThrowException() throws IOException { // ungültige Konfiguration speichern final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { outputStream.write("kein gültiges XML-Dokument".getBytes("UTF-8")); } catch (final IOException e) { fail(e.getLocalizedMessage()); } // versuchen, gespeicherte Konfiguration zu laden new ConfigStorage().loadConfig(redirectOutputToInput(outputStream)); } /** * Testet, ob eine Konfiguration, nachdem sie gespeichert wurde, als nicht-geändert gilt. * @throws IOException */ @Test public final void testSavingConfigWillMarkItAsUnchanged() throws IOException { // Standardkonfiguration erzeugen final Config config = ConfigManager.getNewDefaultConfig(); config.setChanged(true); // Konfiguration speichern new ConfigStorage().saveConfig(config, new ByteArrayOutputStream()); // sicherstellen, dass gespeicherte Konfiguration als nicht-geändert gilt assertFalse(config.isChanged()); } /** * Testet, ob eine Konfiguration, nachdem sie geladen wurde, als nicht-geändert gilt. * @throws IOException */ @Test public final void testLoadingConfigWillMarkItAsUnchanged() throws IOException { // leere Konfiguration speichern final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { new Properties().storeToXML(outputStream, null); } catch (final IOException e) { fail(e.getLocalizedMessage()); } // gespeicherte Konfiguration laden, sollte dabei mit Standardwerten gefüllt werden final Config emptyConfig = new ConfigStorage().loadConfig(redirectOutputToInput(outputStream)); // sicherstellen, dass geladene Konfiguration als nicht-geändert gilt assertFalse(emptyConfig.isChanged()); } /** * @param config Konfiguration * @return String-Repräsentation der Konfiguration */ private String getConfigAsString(final Config config) { return new ConfigStorage().getConfigAsProperties(config).toString(); } /** * Lenkt den Ausgabestream auf einen Eingabestream um. * @param outputStream Ausgabestream * @return Eingabestream */ private InputStream redirectOutputToInput(final ByteArrayOutputStream outputStream) { return new ByteArrayInputStream(outputStream.toByteArray()); } }
/* * Copyright © 2014 TU Berlin (emma@dima.tu-berlin.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.emmalanguage.mitos.operators; import org.emmalanguage.mitos.util.TupleIntDouble; import it.unimi.dsi.fastutil.ints.Int2DoubleMap; //import it.unimi.dsi.fastutil.ints.Int2DoubleOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2DoubleRBTreeMap; import java.util.function.Consumer; public abstract class GroupBy0ReduceTupleIntDouble extends BagOperator<TupleIntDouble, TupleIntDouble> { //protected Int2DoubleOpenHashMap hm; protected Int2DoubleRBTreeMap hm; @Override public void openOutBag() { super.openOutBag(); hm = new Int2DoubleRBTreeMap(); hm.defaultReturnValue(Double.MIN_VALUE); } @Override public void pushInElement(TupleIntDouble e, int logicalInputId) { super.pushInElement(e, logicalInputId); double g = hm.putIfAbsent(e.f0, e.f1); if (g != hm.defaultReturnValue()) { reduceFunc(e, g); } } protected abstract void reduceFunc(TupleIntDouble e, double g); @Override public void closeInBag(int inputId) { super.closeInBag(inputId); //hm.int2DoubleEntrySet().fastForEach(new Consumer<Int2DoubleMap.Entry>() { hm.int2DoubleEntrySet().forEach(new Consumer<Int2DoubleMap.Entry>() { @Override public void accept(Int2DoubleMap.Entry e) { out.collectElement(TupleIntDouble.of(e.getIntKey(), e.getDoubleValue())); } }); hm = null; out.closeBag(); } }
/** * Copyright (C) 2018 Bruno Candido Volpato da Cunha (brunocvcunha@gmail.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.brunocvcunha.coinpayments.requests.base; import java.io.IOException; import java.io.InputStream; import lombok.*; import org.apache.http.client.ClientProtocolException; import org.brunocvcunha.coinpayments.CoinPayments; import org.brunocvcunha.inutils4j.MyStreamUtils; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.log4j.Log4j; @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode @Log4j public abstract class CoinPaymentsRequest<T> { @Getter @Setter @JsonIgnore protected CoinPayments api; /** * @return the url */ public abstract String getUrl(); /** * @return the method */ public abstract String getMethod(); /** * @return the payload */ public String getPayload() { return null; } /** * @return the result * @throws IOException * @throws ClientProtocolException */ public abstract T execute() throws ClientProtocolException, IOException; /** * Process response * * @param resultCode * Status Code * @param content * Content */ public abstract T parseResult(int resultCode, String content); /** * Parses Json into type * * @param str * Entity content * @param clazz * Class * @return Result */ @SneakyThrows public <U> U parseJson(String str, Class<U> clazz) { log.trace("Reading " + clazz.getSimpleName() + " from " + str); return new ObjectMapper().readValue(str, clazz); } /** * Parses Json into type * * @param str * Entity content * @param type * TypeReference * @return Result */ @SneakyThrows public <U> U parseJson(String str, TypeReference<T> type) { log.trace("Reading " + type.getType() + " from " + str); return new ObjectMapper().readValue(str, type); } /** * Parses Json into type * * @param is * Entity stream * @param clazz * Class * @return Result */ @SneakyThrows public T parseJson(InputStream is, Class<T> clazz) { return this.parseJson(MyStreamUtils.readContent(is), clazz); } }
package com.buguagaoshu.homework.convertoffice.config; import org.jodconverter.core.office.OfficeManager; import org.jodconverter.local.office.LocalOfficeManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * @author Pu Zhiwei {@literal puzhiweipuzhiwei@foxmail.com} * create 2021-03-10 15:28 */ @Component public class OfficeManagerInstance { private static OfficeManager INSTANCE = null; private final LibreOfficeProperties libreOfficeProperties; @Autowired public OfficeManagerInstance(LibreOfficeProperties libreOfficeProperties) { this.libreOfficeProperties = libreOfficeProperties; } public static synchronized void start() { officeManagerStart(); } @PostConstruct private void init() { int[] ports = new int[libreOfficeProperties.getPorts().size()]; for (int i = 0; i < libreOfficeProperties.getPorts().size(); i++) { ports[i] = libreOfficeProperties.getPorts().get(i); } LocalOfficeManager.Builder builder = LocalOfficeManager.builder().install(); if (System.getProperty("os.name").contains("Windows")) { builder.officeHome(libreOfficeProperties.getHome()); } builder.portNumbers(ports); builder.taskExecutionTimeout(libreOfficeProperties.getTaskExecutionTimeoutMinutes() * 1000 * 60); builder.taskQueueTimeout(libreOfficeProperties.getTaskQueueTimeoutHours() * 1000 * 60 * 60); INSTANCE = builder.build(); officeManagerStart(); } private static void officeManagerStart() { if (INSTANCE.isRunning()) { return; } try { INSTANCE.start(); } catch (Exception e) { e.printStackTrace(); } } }
interface List { void clear(); void insert(Object it, ListIndex where); void append(Object it); Object remove(ListIndex where); ListIndex getStart(); ListIndex getEnd(); ListIndex pointToPos(int where); int length(); Object getValue(ListIndex where); }
/******************************************************************************* * Copyright 2012 Geoscience Australia * * 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 au.gov.ga.worldwind.common.render; import java.awt.Dimension; import javax.media.opengl.GL2; /** * Class used by the {@link FrameBuffer} to generate/store the texture. * * @author Michael de Hoog (michael.dehoog@ga.gov.au) */ public class FrameBufferTexture { private int id = 0; private int target = GL2.GL_TEXTURE_2D; private int minificationFilter = GL2.GL_LINEAR; private int magnificationFilter = GL2.GL_LINEAR; private int internalFormat = GL2.GL_RGBA8; private int format = GL2.GL_RGBA; private int type = GL2.GL_UNSIGNED_BYTE; protected void create(GL2 gl, Dimension dimensions) { delete(gl); int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); if (textures[0] <= 0) { throw new IllegalStateException("Error generating texture for frame buffer"); } id = textures[0]; gl.glBindTexture(getTarget(), id); gl.glTexParameteri(getTarget(), GL2.GL_TEXTURE_MAG_FILTER, getMagnificationFilter()); gl.glTexParameteri(getTarget(), GL2.GL_TEXTURE_MIN_FILTER, getMinificationFilter()); gl.glTexParameteri(getTarget(), GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP); gl.glTexParameteri(getTarget(), GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP); gl.glTexEnvf(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_MODULATE); gl.glTexImage2D(getTarget(), 0, getInternalFormat(), dimensions.width, dimensions.height, 0, getFormat(), getType(), null); gl.glBindTexture(getTarget(), 0); } protected void delete(GL2 gl) { if (isCreated()) { gl.glDeleteTextures(1, new int[] { id }, 0); id = 0; } } public boolean isCreated() { return id > 0; } public int getId() { return id; } public int getTarget() { return target; } public void setTarget(int target) { this.target = target; } public int getMinificationFilter() { return minificationFilter; } public void setMinificationFilter(int minificationFilter) { this.minificationFilter = minificationFilter; } public int getMagnificationFilter() { return magnificationFilter; } public void setMagnificationFilter(int magnificationFilter) { this.magnificationFilter = magnificationFilter; } public int getInternalFormat() { return internalFormat; } public void setInternalFormat(int internalFormat) { this.internalFormat = internalFormat; } public int getFormat() { return format; } public void setFormat(int format) { this.format = format; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
package hudson.plugins.performance.parsers; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.nio.charset.StandardCharsets; import org.junit.Test; import org.jvnet.hudson.test.Issue; import static org.junit.Assert.*; public class ParserDetectorTest { @Test public void testFlow() throws Exception { String filePath; filePath = getClass().getResource("/TaurusXMLReport.xml").toURI().getPath(); assertEquals(TaurusParser.class.getSimpleName(), ParserDetector.detect(filePath)); filePath = getClass().getResource("/JMeterResults.jtl").toURI().getPath(); assertEquals(JMeterParser.class.getSimpleName(), ParserDetector.detect(filePath)); filePath = getClass().getResource("/TEST-JUnitResults.xml").toURI().getPath(); assertEquals(JUnitParser.class.getSimpleName(), ParserDetector.detect(filePath)); filePath = getClass().getResource("/IagoResults.log").toURI().getPath(); assertEquals(IagoParser.class.getSimpleName(), ParserDetector.detect(filePath)); filePath = getClass().getResource("/WrkResultsQuick.wrk").toURI().getPath(); assertEquals(WrkSummarizerParser.class.getSimpleName(), ParserDetector.detect(filePath)); filePath = getClass().getResource("/JMeterCsvResults.csv").toURI().getPath(); assertEquals(JMeterCsvParser.class.getSimpleName(), ParserDetector.detect(filePath)); filePath = getClass().getResource("/summary.log").toURI().getPath(); assertEquals(JmeterSummarizerParser.class.getSimpleName(), ParserDetector.detect(filePath)); filePath = getClass().getResource("/lr-session.mdb").toURI().getPath(); assertEquals(LoadRunnerParser.class.getSimpleName(), ParserDetector.detect(filePath)); } @Issue("JENKINS-44317") @Test public void testIssue44317() throws Exception { String filePath = getClass().getResource("/TEST-results.xml").toURI().getPath(); assertEquals(JUnitParser.class.getSimpleName(), ParserDetector.detect(filePath)); } @Issue("JENKINS-45723") @Test public void testIssue45723() throws Exception { String filePath = getClass().getResource("/TEST-JUnitResults-success-failure-error.xml").toURI().getPath(); assertEquals(JUnitParser.class.getSimpleName(), ParserDetector.detect(filePath)); } @Issue("JENKINS-47808") @Test public void testIssue() throws Exception { assertEquals(JMeterParser.class.getSimpleName(), ParserDetector.detectXMLFileType(getHugeJMeterInputStream())); } @Test public void testLocustReport() throws Exception { String filePath = getClass().getResource("/test_results_requests.csv").toURI().getPath(); assertEquals(LocustParser.class.getSimpleName(), ParserDetector.detect(filePath)); } public static InputStream getHugeJMeterInputStream() { return new SequenceInputStream(getPrefixInputStream(), getInfiniteSampleInputStream()); } private static ByteArrayInputStream getPrefixInputStream() { return new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testResults version=\"1.2\">".getBytes( StandardCharsets.UTF_8)); } private static InputStream getInfiniteSampleInputStream() { return repeat("<httpSample t=\"289\" lt=\"289\" ts=\"1509447454646\" s=\"true\" lb=\"test\" rc=\"200\" rm=\"OK\" tn=\"test\" dt=\"text\" by=\"1410\"/>".getBytes( StandardCharsets.UTF_8), Integer.MAX_VALUE); } public static InputStream repeat(final byte[] sample, final int times) { return new InputStream() { private long pos = 0; private final long total = (long)sample.length * times; public int read() throws IOException { return pos < total ? sample[(int)(pos++ % sample.length)] : -1; } }; } }
/* * 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.web.method.annotation; import java.util.ArrayList; import org.springframework.core.MethodParameter; import org.springframework.lang.Nullable; import org.springframework.ui.ModelMap; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; /** * Resolves {@link Errors} method arguments. * * <p>An {@code Errors} method argument is expected to appear immediately after * the model attribute in the method signature. It is resolved by expecting the * last two attributes added to the model to be the model attribute and its * {@link BindingResult}. * * @author Rossen Stoyanchev * @since 3.1 */ public class ErrorsMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { Class<?> paramType = parameter.getParameterType(); return Errors.class.isAssignableFrom(paramType); } @Override @Nullable public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { Assert.state(mavContainer != null, "Errors/BindingResult argument only supported on regular handler methods"); ModelMap model = mavContainer.getModel(); if (model.size() > 0) { int lastIndex = model.size()-1; String lastKey = new ArrayList<>(model.keySet()).get(lastIndex); if (lastKey.startsWith(BindingResult.MODEL_KEY_PREFIX)) { return model.get(lastKey); } } throw new IllegalStateException( "An Errors/BindingResult argument is expected to be declared immediately after the model attribute, " + "the @RequestBody or the @RequestPart arguments to which they apply: " + parameter.getMethod()); } }
package gremlin.patches; import com.evacipated.cardcrawl.modthespire.lib.ByRef; import com.evacipated.cardcrawl.modthespire.lib.SpireInsertPatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePatch; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.powers.AbstractPower; import com.megacrit.cardcrawl.powers.StrengthPower; import gremlin.cards.StrengthAffectedCard; @SpirePatch( clz= AbstractCard.class, method="applyPowers" ) public class StrengthAffectedApplyPatch { @SpireInsertPatch( rloc=19, localvars={"p", "tmp"} ) public static void Insert(AbstractCard __instance, AbstractPower p, @ByRef float[] tmp) { if(__instance instanceof StrengthAffectedCard && p instanceof StrengthPower){ for(int i=1; i < ((StrengthAffectedCard) __instance).strengthMultiplier(); i++){ tmp[0] = p.atDamageGive(tmp[0], __instance.damageTypeForTurn); } } } }
//Copyright (C) 2015 The Android Open Source Project // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. package com.google.gerrit.server.git; import static com.google.common.base.Preconditions.checkState; import com.google.gerrit.lifecycle.LifecycleModule; import com.google.gerrit.reviewdb.client.Project.NameKey; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.config.RepositoryConfig; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.nio.file.Path; import org.eclipse.jgit.lib.Config; public class MultiBaseLocalDiskRepositoryManager extends LocalDiskRepositoryManager { public static class Module extends LifecycleModule { @Override protected void configure() { bind(GitRepositoryManager.class).to(MultiBaseLocalDiskRepositoryManager.class); listener().to(MultiBaseLocalDiskRepositoryManager.Lifecycle.class); } } private final RepositoryConfig config; @Inject MultiBaseLocalDiskRepositoryManager( SitePaths site, @GerritServerConfig Config cfg, RepositoryConfig config) { super(site, cfg); this.config = config; for (Path alternateBasePath : config.getAllBasePaths()) { checkState( alternateBasePath.isAbsolute(), "repository.<name>.basePath must be absolute: %s", alternateBasePath); } } @Override public Path getBasePath(NameKey name) { Path alternateBasePath = config.getBasePath(name); return alternateBasePath != null ? alternateBasePath : super.getBasePath(name); } @Override protected void scanProjects(ProjectVisitor visitor) { super.scanProjects(visitor); for (Path path : config.getAllBasePaths()) { visitor.setStartFolder(path); super.scanProjects(visitor); } } }
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.curiumj.jni; import org.curiumj.wallet.Wallet; import org.curiumj.wallet.listeners.WalletCoinsReceivedEventListener; import org.curiumj.core.Coin; import org.curiumj.core.Transaction; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. */ public class NativeWalletCoinsReceivedEventListener implements WalletCoinsReceivedEventListener { public long ptr; @Override public native void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance); }
package org.onetwo.ext.rocketmq.producer; import org.onetwo.ext.rocketmq.annotation.EnableRocketMQ; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes=MQProducerContextTestConfig.class) @PropertySource(value="classpath:config.properties") @EnableRocketMQ public class MQProducerContextTestConfig { public static final String MQ_PRODUCER_GROUP_INDEX_UPDATE = "search-producer-index-update"; }
/* * eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) <2019> eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * 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 3 of the License, or * 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/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * Further, all user interfaces, including but not limited to citizen facing interfaces, * Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any * derived works should carry eGovernments Foundation logo on the top right corner. * * For the logo, please refer http://egovernments.org/html/logo/egov_logo.png. * For any further queries on attribution, including queries on brand guidelines, * please contact contact@egovernments.org * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org. */ package org.egov.bpa.utils; import static org.egov.bpa.utils.BpaConstants.APPLICATION_STATUS_REJECTED; import static org.egov.bpa.utils.BpaConstants.APPLICATION_STATUS_SUBMITTED; import static org.egov.bpa.utils.BpaConstants.EGMODULE_NAME; import static org.egov.bpa.utils.BpaConstants.WF_LBE_SUBMIT_BUTTON; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.egov.bpa.transaction.entity.OwnershipTransfer; import org.egov.bpa.transaction.entity.PermitRenewal; import org.egov.infra.admin.master.entity.Module; import org.egov.infra.admin.master.entity.User; import org.egov.infra.admin.master.service.ModuleService; import org.egov.portal.entity.PortalInbox; import org.egov.portal.entity.PortalInboxBuilder; import org.egov.portal.service.PortalInboxService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author vinoth * */ @Service @Transactional(readOnly = true) public class PushBpaApplicationToPortalUtil { private static final String APPLICATION_FEE_PAYMENT_PENDING = "Application fee payment pending"; private static final String SUCCESS = "Success"; private static final String CLOSED = "Closed"; private static final String WF_END_ACTION = "END"; private static final String SERVICETYPE = "Permit Renewal - "; private static final String OWNERSHIPTRANSFER = "Ownership Transfer - "; @Autowired private ModuleService moduleService; @Autowired private PortalInboxService portalInboxService; @Autowired private BpaUtils bpaUtils; @Transactional public void updatePortalUserinbox(final PermitRenewal renewal, final User additionalPortalInboxUser) { Module module = moduleService.getModuleByName(EGMODULE_NAME); boolean isResolved = false; String status = renewal.getStatus().getDescription(); if (renewal.getState() != null && (CLOSED.equals(renewal.getState().getValue()) || WF_END_ACTION.equals(renewal.getState().getValue())) || renewal.getStatus() != null && renewal.getStatus().getCode().equals(APPLICATION_STATUS_REJECTED)) isResolved = true; String url = "/bpa/citizen/application/permit/renewal/update/" + renewal.getApplicationNumber(); if (renewal.getStatus() != null) portalInboxService.updateInboxMessage(renewal.getApplicationNumber(), module.getId(), status, isResolved, new Date(), renewal.getState(), additionalPortalInboxUser, renewal.getRenewalNumber(), url); } @Transactional public void createPortalUserinbox(final PermitRenewal renewal, final List<User> portalInboxUser, final String workFlowAction) { String status = renewal.getStatus().getDescription(); Module module = moduleService.getModuleByName(EGMODULE_NAME); boolean isResolved = false; String url = "/bpa/citizen/application/permit/renewal/update/" + renewal.getApplicationNumber(); final PortalInboxBuilder portalInboxBuilder = new PortalInboxBuilder(module, renewal.getParent().getOwner().getName(), SERVICETYPE.concat(renewal.getParent().getServiceType().getDescription()), renewal.getApplicationNumber(), renewal.getRenewalNumber(), renewal.getId(), SUCCESS, SUCCESS, url, isResolved, status, new Date(), renewal.getState(), portalInboxUser); final PortalInbox portalInbox = portalInboxBuilder.build(); portalInboxService.pushInboxMessage(portalInbox); } @Transactional public void updatePortalUserinbox(final OwnershipTransfer ownershipTransfer, final User additionalPortalInboxUser) { Module module = moduleService.getModuleByName(EGMODULE_NAME); boolean isResolved = false; String status; if (APPLICATION_STATUS_SUBMITTED.equals(ownershipTransfer.getStatus().getCode()) && bpaUtils.checkAnyTaxIsPendingToCollect(ownershipTransfer.getDemand())) status = APPLICATION_FEE_PAYMENT_PENDING; else status = ownershipTransfer.getStatus().getDescription(); if (ownershipTransfer.getState() != null && (CLOSED.equals(ownershipTransfer.getState().getValue()) || WF_END_ACTION.equals(ownershipTransfer.getState().getValue())) || ownershipTransfer.getStatus() != null && ownershipTransfer.getStatus().getCode().equals(APPLICATION_STATUS_REJECTED)) isResolved = true; String url = "/bpa/citizen/application/ownership/transfer/update/" + ownershipTransfer.getApplicationNumber(); if (ownershipTransfer.getStatus() != null) portalInboxService.updateInboxMessage(ownershipTransfer.getApplicationNumber(), module.getId(), status, isResolved, new Date(), ownershipTransfer.getState(), additionalPortalInboxUser, ownershipTransfer.getOwnershipNumber(), url); } @Transactional public void createPortalUserinbox(final OwnershipTransfer ownershipTransfer, final List<User> portalInboxUser, final String workFlowAction) { String status = StringUtils.EMPTY; if ("Save".equalsIgnoreCase(workFlowAction)) { status = "To be submitted"; } else if (null != ownershipTransfer.getStatus().getDescription() && WF_LBE_SUBMIT_BUTTON.equalsIgnoreCase(workFlowAction)) { if (bpaUtils.checkAnyTaxIsPendingToCollect(ownershipTransfer.getDemand())) status = APPLICATION_FEE_PAYMENT_PENDING; else status = ownershipTransfer.getStatus().getDescription(); } Module module = moduleService.getModuleByName(EGMODULE_NAME); boolean isResolved = false; String url = "/bpa/citizen/application/ownership/transfer/update/" + ownershipTransfer.getApplicationNumber(); final PortalInboxBuilder portalInboxBuilder = new PortalInboxBuilder(module, ownershipTransfer.getParent() == null ? ownershipTransfer.getOwner().getName() : ownershipTransfer.getParent().getOwner().getName(), OWNERSHIPTRANSFER.concat(ownershipTransfer.getApplication().getServiceType().getDescription()), ownershipTransfer.getApplicationNumber(), ownershipTransfer.getOwnershipNumber(), ownershipTransfer.getId(), SUCCESS, SUCCESS, url, isResolved, status, new Date(), ownershipTransfer.getState(), portalInboxUser); final PortalInbox portalInbox = portalInboxBuilder.build(); portalInboxService.pushInboxMessage(portalInbox); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.12.16 at 01:01:40 PM EST // package xml.us.patent.grant.v45; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "confplace") public class Confplace { @XmlValue protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getvalue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setvalue(String value) { this.value = value; } }
package org.thoughtcrime.securesms.components; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.FrameLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import org.thoughtcrime.securesms.R; public class MaxHeightFrameLayout extends FrameLayout { private final int maxHeight; public MaxHeightFrameLayout(@NonNull Context context) { this(context, null); } public MaxHeightFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public MaxHeightFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (attrs != null) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightFrameLayout); maxHeight = a.getDimensionPixelSize(R.styleable.MaxHeightFrameLayout_mhfl_maxHeight, 0); a.recycle(); } else { maxHeight = 0; } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, Math.min(bottom, top + maxHeight)); } }
/* This file is part of the iText (R) project. Copyright (c) 1998-2021 iText Group NV Authors: Bruno Lowagie, Paulo Soares, et al. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL: http://itextpdf.com/terms-of-use/ The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License. In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer line in every PDF that is created or manipulated using iText. You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the iText software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs on the fly in a web application, shipping iText with a closed source product. For more information, please contact iText Software Corp. at this address: sales@itextpdf.com */ package com.itextpdf.html2pdf.attach.impl.layout.form.renderer; import com.itextpdf.html2pdf.attach.impl.layout.form.element.IFormField; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.layout.renderer.BlockRenderer; import com.itextpdf.layout.renderer.IRenderer; import com.itextpdf.layout.renderer.LineRenderer; import java.util.List; /** * Abstract {@link BlockRenderer} for a single line of text content in a form field. */ public abstract class AbstractOneLineTextFieldRenderer extends AbstractTextFieldRenderer { /** * Creates a new {@link AbstractOneLineTextFieldRenderer} instance. * * @param modelElement the model element */ AbstractOneLineTextFieldRenderer(IFormField modelElement) { super(modelElement); } @Override public void move(float dxRight, float dyUp) { super.move(dxRight, dyUp); } /** * Crops the content lines. * * @param lines a list of lines * @param bBox the bounding box */ void cropContentLines(List<LineRenderer> lines, Rectangle bBox) { adjustNumberOfContentLines(lines, bBox, 1); updateParagraphHeight(); } /** * Updates the paragraph height. */ private void updateParagraphHeight() { Float height = retrieveHeight(); Float minHeight = retrieveMinHeight(); Float maxHeight = retrieveMaxHeight(); float originalHeight = flatRenderer.getOccupiedArea().getBBox().getHeight(); if (height != null && (float) height > 0) { setContentHeight(flatRenderer, (float) height); } else if (minHeight != null && (float) minHeight > originalHeight) { setContentHeight(flatRenderer, (float) minHeight); } else if (maxHeight != null && (float) maxHeight > 0 && (float) maxHeight < originalHeight) { setContentHeight(flatRenderer, (float) maxHeight); } } /** * Sets the content height. * * @param flatRenderer the flat renderer * @param height the height */ private void setContentHeight(IRenderer flatRenderer, float height) { Rectangle bBox = flatRenderer.getOccupiedArea().getBBox(); float dy = (height - bBox.getHeight()) / 2; bBox.moveDown(dy); bBox.setHeight(height); flatRenderer.move(0, -dy); } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * 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.gravitee.identityprovider.api; import java.io.Serializable; import java.time.ZonedDateTime; import java.util.Collections; import java.util.List; import java.util.Map; /** * @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com) * @author GraviteeSource Team * * @see DefaultUser */ public interface User extends Serializable { /** * Returns the technical id used of the user * * @return the technical id */ String getId(); /** * Returns the username used to authenticate the user. Cannot return <code>null</code>. * * @return the username (never <code>null</code>) */ String getUsername(); /** * Returns the password of the user. (Useful for user management) * * @return the password */ String getPassword(); /** * Allows to set the password (Useful to encode the password). */ void setPassword(String password); /** * Indicates whether the user's account has expired. An expired account cannot be authenticated. * * @return <code>true</code> if the user's account is valid (ie non-expired), <code>false</code> if no longer valid * (ie expired) */ boolean isAccountExpired(); /** * Indicates whether the user is enabled or disabled. A disabled user cannot be authenticated. * * @return <code>true</code> if the user is enabled, <code>false</code> otherwise */ boolean isEnabled(); /** * Returns the user roles * * @return the user roles */ default List<String> getRoles(){ return Collections.emptyList(); } /** * Returns the user additional information * * @return the user additional information */ Map<String, Object> getAdditionalInformation(); /** * Returns the user creation date * * @return the user creation date */ ZonedDateTime getCreatedAt(); /** * Returns the last time when user has been updated * * @return the last time when user has been updated */ ZonedDateTime getUpdatedAt(); }
/* * Copyright (c) 2015, 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.siddhi.extension.map; import junit.framework.Assert; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.wso2.siddhi.core.ExecutionPlanRuntime; import org.wso2.siddhi.core.SiddhiManager; import org.wso2.siddhi.core.event.Event; import org.wso2.siddhi.core.stream.input.InputHandler; import org.wso2.siddhi.core.stream.output.StreamCallback; import org.wso2.siddhi.core.util.EventPrinter; import org.wso2.siddhi.extension.map.test.util.SiddhiTestHelper; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; public class RemoveFunctionExtensionTestCase { private static final Logger log = Logger.getLogger(RemoveFunctionExtensionTestCase.class); private AtomicInteger count = new AtomicInteger(0); private volatile boolean eventArrived; @Before public void init() { count.set(0); eventArrived = false; } @Test public void testRemoveFunctionExtension() throws InterruptedException { log.info("RemoveFunctionExtension TestCase"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "@config(async = 'true')\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream select symbol,price, " + "map:create() as tmpMap insert into tmpStream;" + "@info(name = 'query2') from tmpStream select symbol,price,tmpMap, map:put(tmpMap,symbol,price) as map1" + " insert into outputStream;" + "@info(name = 'query3') from outputStream select map1, map:remove(map1,'IBM') as map2" + " insert into outputStream2;" ); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("outputStream2", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); for (Event event : events) { count.incrementAndGet(); if (count.get() == 1) { HashMap map = (HashMap) event.getData(1); Assert.assertEquals(null, map.get("IBM")); eventArrived = true; } if (count.get() == 2) { HashMap map = (HashMap) event.getData(1); Assert.assertEquals(200, map.get("WSO2")); eventArrived = true; } if (count.get() == 3) { HashMap map = (HashMap) event.getData(1); Assert.assertEquals(300, map.get("XYZ")); eventArrived = true; } } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"IBM", 100, 100l}); inputHandler.send(new Object[]{"WSO2", 200, 200l}); inputHandler.send(new Object[]{"XYZ", 300, 200l}); SiddhiTestHelper.waitForEvents(100, 3, count, 60000); Assert.assertEquals(3, count.get()); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); } }
package com.example.android.sunshine.data.database; import android.arch.persistence.db.SupportSQLiteDatabase; import android.arch.persistence.db.SupportSQLiteOpenHelper; import android.arch.persistence.db.SupportSQLiteOpenHelper.Callback; import android.arch.persistence.db.SupportSQLiteOpenHelper.Configuration; import android.arch.persistence.room.DatabaseConfiguration; import android.arch.persistence.room.InvalidationTracker; import android.arch.persistence.room.RoomOpenHelper; import android.arch.persistence.room.RoomOpenHelper.Delegate; import android.arch.persistence.room.util.TableInfo; import android.arch.persistence.room.util.TableInfo.Column; import android.arch.persistence.room.util.TableInfo.ForeignKey; import android.arch.persistence.room.util.TableInfo.Index; import java.lang.IllegalStateException; import java.lang.Override; import java.lang.String; import java.lang.SuppressWarnings; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; @SuppressWarnings("unchecked") public class SunshineDatabase_Impl extends SunshineDatabase { private volatile WeatherDao _weatherDao; @Override protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) { final SupportSQLiteOpenHelper.Callback _openCallback = new RoomOpenHelper(configuration, new RoomOpenHelper.Delegate(1) { @Override public void createAllTables(SupportSQLiteDatabase _db) { _db.execSQL("CREATE TABLE IF NOT EXISTS `weather` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `weatherIconId` INTEGER NOT NULL, `date` INTEGER, `min` REAL NOT NULL, `max` REAL NOT NULL, `humidity` REAL NOT NULL, `pressure` REAL NOT NULL, `wind` REAL NOT NULL, `degrees` REAL NOT NULL)"); _db.execSQL("CREATE UNIQUE INDEX `index_weather_date` ON `weather` (`date`)"); _db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)"); _db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"9db8aa03c94807e7c867e1d94a9e0114\")"); } @Override public void dropAllTables(SupportSQLiteDatabase _db) { _db.execSQL("DROP TABLE IF EXISTS `weather`"); } @Override protected void onCreate(SupportSQLiteDatabase _db) { if (mCallbacks != null) { for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) { mCallbacks.get(_i).onCreate(_db); } } } @Override public void onOpen(SupportSQLiteDatabase _db) { mDatabase = _db; internalInitInvalidationTracker(_db); if (mCallbacks != null) { for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) { mCallbacks.get(_i).onOpen(_db); } } } @Override protected void validateMigration(SupportSQLiteDatabase _db) { final HashMap<String, TableInfo.Column> _columnsWeather = new HashMap<String, TableInfo.Column>(9); _columnsWeather.put("id", new TableInfo.Column("id", "INTEGER", true, 1)); _columnsWeather.put("weatherIconId", new TableInfo.Column("weatherIconId", "INTEGER", true, 0)); _columnsWeather.put("date", new TableInfo.Column("date", "INTEGER", false, 0)); _columnsWeather.put("min", new TableInfo.Column("min", "REAL", true, 0)); _columnsWeather.put("max", new TableInfo.Column("max", "REAL", true, 0)); _columnsWeather.put("humidity", new TableInfo.Column("humidity", "REAL", true, 0)); _columnsWeather.put("pressure", new TableInfo.Column("pressure", "REAL", true, 0)); _columnsWeather.put("wind", new TableInfo.Column("wind", "REAL", true, 0)); _columnsWeather.put("degrees", new TableInfo.Column("degrees", "REAL", true, 0)); final HashSet<TableInfo.ForeignKey> _foreignKeysWeather = new HashSet<TableInfo.ForeignKey>(0); final HashSet<TableInfo.Index> _indicesWeather = new HashSet<TableInfo.Index>(1); _indicesWeather.add(new TableInfo.Index("index_weather_date", true, Arrays.asList("date"))); final TableInfo _infoWeather = new TableInfo("weather", _columnsWeather, _foreignKeysWeather, _indicesWeather); final TableInfo _existingWeather = TableInfo.read(_db, "weather"); if (! _infoWeather.equals(_existingWeather)) { throw new IllegalStateException("Migration didn't properly handle weather(com.example.android.sunshine.data.database.WeatherEntry).\n" + " Expected:\n" + _infoWeather + "\n" + " Found:\n" + _existingWeather); } } }, "9db8aa03c94807e7c867e1d94a9e0114", "23e8c00181f2568d630626c652daefdd"); final SupportSQLiteOpenHelper.Configuration _sqliteConfig = SupportSQLiteOpenHelper.Configuration.builder(configuration.context) .name(configuration.name) .callback(_openCallback) .build(); final SupportSQLiteOpenHelper _helper = configuration.sqliteOpenHelperFactory.create(_sqliteConfig); return _helper; } @Override protected InvalidationTracker createInvalidationTracker() { return new InvalidationTracker(this, "weather"); } @Override public void clearAllTables() { super.assertNotMainThread(); final SupportSQLiteDatabase _db = super.getOpenHelper().getWritableDatabase(); try { super.beginTransaction(); _db.execSQL("DELETE FROM `weather`"); super.setTransactionSuccessful(); } finally { super.endTransaction(); _db.query("PRAGMA wal_checkpoint(FULL)").close(); if (!_db.inTransaction()) { _db.execSQL("VACUUM"); } } } @Override public WeatherDao weatherDao() { if (_weatherDao != null) { return _weatherDao; } else { synchronized(this) { if(_weatherDao == null) { _weatherDao = new WeatherDao_Impl(this); } return _weatherDao; } } } }
package service.impl; import VO.ApplyVO; import entity.Apply; import mapper.ApplyMapper; import mapper.impl.ApplyMapperImpl; import service.ApplyService; import util.TrainingContext; import java.sql.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class ApplyServiceImpl implements ApplyService { private ApplyMapper applyMapper = new ApplyMapperImpl(); @Override public void addApply(ApplyVO applyVO) { Apply apply = new Apply(); apply.setCause(applyVO.getCause()); apply.setTime(new Date(System.currentTimeMillis())); apply.setUsername(TrainingContext.getLocal_User_Name()); apply.setActivityId(applyVO.getActivity_id()); applyMapper.insert(apply); } @Override public Map<String, Object> selectAllApply() { Map<String,Object> map = new HashMap<>(); List<Apply> applyList = applyMapper.selectAll(); StringBuilder builder = new StringBuilder(); if (applyList.isEmpty()){ map.put("value","No"); }else{ map.put("value","Yes"); for (Apply apply : applyList){ builder.append(apply.toString()); } map.put("data",builder.toString()); } return map; } }
package com.redis.service; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import com.redis.model.User; public interface UserService { @Cacheable(key="'user_'+#id",value="'user'+#id") User getUser(String id); @CacheEvict(key="'user_'+#id", value="users", condition="#id!=1") void deleteUser(String id); }
package ru.job4j.tracker; import java.util.List; import java.util.function.Consumer; public class FindItemsByName extends BaseAction { public FindItemsByName(int key, String name) { super(key, name); } @Override public void execute(Input input, Tracker tracker, Consumer<String> output) { output.accept("------------ Поиск заявки по имени --------------"); String name = input.ask("Введите имя заявки, которую хотите найти:", output); List<Item> found = tracker.findByName(name); if (found != null) { output.accept("------------ Найдены заявки: -----------"); for (Item item : found) { output.accept(item.toString()); } } else { output.accept("------------ Заявок с именем: '" + name + "' не существует. -----------"); } } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_06_01.implementation; import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; import com.microsoft.azure.management.network.v2019_06_01.NetworkWatcher; import rx.Observable; import com.microsoft.azure.management.network.v2019_06_01.ProvisioningState; class NetworkWatcherImpl extends GroupableResourceCoreImpl<NetworkWatcher, NetworkWatcherInner, NetworkWatcherImpl, NetworkManager> implements NetworkWatcher, NetworkWatcher.Definition, NetworkWatcher.Update { NetworkWatcherImpl(String name, NetworkWatcherInner inner, NetworkManager manager) { super(name, inner, manager); } @Override public Observable<NetworkWatcher> createResourceAsync() { NetworkWatchersInner client = this.manager().inner().networkWatchers(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(innerToFluentMap(this)); } @Override public Observable<NetworkWatcher> updateResourceAsync() { NetworkWatchersInner client = this.manager().inner().networkWatchers(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(innerToFluentMap(this)); } @Override protected Observable<NetworkWatcherInner> getInnerAsync() { NetworkWatchersInner client = this.manager().inner().networkWatchers(); return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } @Override public String etag() { return this.inner().etag(); } @Override public ProvisioningState provisioningState() { return this.inner().provisioningState(); } @Override public NetworkWatcherImpl withEtag(String etag) { this.inner().withEtag(etag); return this; } @Override public NetworkWatcherImpl withProvisioningState(ProvisioningState provisioningState) { this.inner().withProvisioningState(provisioningState); return this; } }
package io.jenkinsci.security; import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator; import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserPrivateKey; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.cloudbees.plugins.credentials.domains.DomainRequirement; import com.cloudbees.plugins.credentials.domains.SchemeRequirement; import com.jcraft.jsch.*; import hudson.EnvVars; import hudson.Extension; import hudson.Launcher; import hudson.model.*; import hudson.security.ACL; import hudson.slaves.EnvironmentVariablesNodeProperty; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.DescribableList; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.StreamTaskListener; import io.jenkinsci.security.analysis.DASTAnalysis; import io.jenkinsci.security.analysis.SASTAnalysis; import jenkins.model.Jenkins; import jenkins.tasks.SimpleBuildStep; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import org.jenkinsci.plugins.jsch.JSchConnector; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import java.io.*; import java.net.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; import static io.jenkinsci.security.Utils.isJSONValid; public class WsapBuilder extends Builder implements SimpleBuildStep,ConsoleSupport { private static final int SSH_PORT = 22; @Getter @Setter private String targetUrl; @Getter @Setter private String envVar; @Getter @Setter private String credentialsId; //Scan Properties @Getter @Setter private String wsapLocation; @Getter @Setter private String ipAddress; @Getter @Setter private int port; //Analysis Properties @Getter @Setter public SASTAnalysis sastAnalysis; @Getter @Setter public DASTAnalysis dastAnalysis; public static final SchemeRequirement SSH_SCHEME = new SchemeRequirement("ssh"); @DataBoundConstructor @SuppressWarnings("unused") public WsapBuilder(String wsapLocation, String envVar, String credentialsId, String targetUrl, String ipAddress, int port, String apiKey, SASTAnalysis sastAnalysis, DASTAnalysis dastAnalysis){ this.wsapLocation = wsapLocation; this.targetUrl = targetUrl; this.credentialsId = credentialsId; this.envVar = envVar; this.ipAddress = ipAddress; this.port = port; this.sastAnalysis = sastAnalysis; this.dastAnalysis = dastAnalysis; } @Override public JSONObject generateJSON(){ JSONObject json = new JSONObject(); json.put("target.url", targetUrl); json.put("scanner.ip", ipAddress); json.put("scanner.port", port); json.put("sastAnalysis", sastAnalysis.generateJSON()); json.put("dastAnalysis", dastAnalysis.generateJSON()); return json; } public void createGlobalEnvironmentVariables(String key, String value) throws IOException { Jenkins instance = Jenkins.getInstanceOrNull(); if (instance == null) throw new IOException("Unable to load Jenkins instance"); DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties(); if (globalNodeProperties == null) throw new IOException("Unable to load global node properties"); List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class); EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null; EnvVars envVars = null; if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) { newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty(); globalNodeProperties.add(newEnvVarsNodeProperty); envVars = newEnvVarsNodeProperty.getEnvVars(); } else { envVars = envVarsNodePropertyList.get(0).getEnvVars(); } envVars.put(key, value); instance.save(); } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { //Retrieve valid username StandardUsernameCredentials user = CredentialsProvider .findCredentialById(credentialsId, SSHUserPrivateKey.class, build, SSH_SCHEME); if (user == null) { String message = "Credentials with id '" + credentialsId + "', no longer exist!"; listener.getLogger().println(message); throw new InterruptedException(message); } String username = user.getUsername(); //Create SSH Session final JSchConnector connector = new JSchConnector(username, ipAddress, SSH_PORT); listener.getLogger().println("Successfully created Connector"); final SSHAuthenticator<JSchConnector, StandardUsernameCredentials> authenticator = SSHAuthenticator .newInstance(connector, user); authenticator.authenticate(new StreamTaskListener(listener.getLogger(), Charset.defaultCharset())); final Session session = connector.getSession(); final Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); config.put("PreferredAuthentications", "publickey"); session.setConfig(config); //Connect try { session.connect(); if (!session.isConnected()) throw new JSchException("Not connected to an open session"); //Launch WSAP instance launchWASPServer(listener, session, username); try { listener.getLogger().println("Waiting for server to be available"); Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } //Sends data by TCP Connection JSONObject vulnerabilityAudit = sendingWSAPParams(listener); if (vulnerabilityAudit != null){ //Stores the highest criticality vulnerabilities in Jenkins by scanner generateCriticalEnvVariables(listener, vulnerabilityAudit); } } catch (JSchException e) { throw new InterruptedException(e.getMessage()); } return true; } private void generateCriticalEnvVariables(BuildListener listener, JSONObject vulnerabilityAudit) throws IOException { createGlobalEnvironmentVariables(envVar.toUpperCase(), targetUrl); listener.getLogger().println(String.format("Created variable %s with the targetUrl",envVar.toUpperCase())); //Iterates through all tools names Iterator<String> keys = (Iterator<String>) vulnerabilityAudit.keys(); while (keys.hasNext()) { String key = keys.next(); //Gets an object with all security levels (High, Medium, Low, Info) JSONObject value = vulnerabilityAudit.getJSONObject(key); //Gets only the first security level (High) Iterator<String> levels = (Iterator<String>) value.keys(); String jenkinsVar = envVar+"_"+key; if (levels.hasNext()){ //Creates venv var containing the vulnerabilities present in High String level = levels.next(); String vulnerabilities = value.getString(level); //Adds var to jenkins variable createGlobalEnvironmentVariables(jenkinsVar.toUpperCase(), vulnerabilities); listener.getLogger().println(String.format("Created variable %s with the amount of critical vulnerabilities found",jenkinsVar.toUpperCase())); }else{ createGlobalEnvironmentVariables(jenkinsVar.toUpperCase(), "No data"); listener.getLogger().println(String.format("Created variable %s, but no report was found",jenkinsVar.toUpperCase())); } } } public void launchWASPServer(BuildListener listener, Session session, String username) throws JSchException { listener.getLogger().println(String.format("Attempting to ssh as: %s",username)); String command = String.format("python3 %s/main.py --server %s",wsapLocation,9999); listener.getLogger().println(command); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setPty(true); channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(System.err); //Creating channel channel.connect(); listener.getLogger().println("WASP instance was successfully initialized"); //Closing channel channel.disconnect(); } public JSONObject sendingWSAPParams(BuildListener listener) throws IOException, JSchException { JSONObject vulnerabilityAudit = null; listener.getLogger().println("Trying to connect on ip: " + ipAddress + ":" + 9999); Socket socket = new Socket(ipAddress, 9999); if (socket.isConnected()) { listener.getLogger().println("Connected"); //Create stream DataInputStream in = new DataInputStream(socket.getInputStream()); InputStreamReader stream = new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(stream); //Sending form data JSONObject sendData = generateJSON(); listener.getLogger().println("Sending defined parameters to WSAP instance"); OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8); out.write(sendData.toString()); out.flush(); //Receiving feedback listener.getLogger().println("Waiting for server response... May take a few hours"); StringBuffer buffer = new StringBuffer(); boolean interrupted = false; while (!interrupted) { int ch = br.read(); buffer.append((char) ch); if (Utils.isJSONValid(buffer.toString())) { JSONObject jsonObject = JSONObject.fromObject(buffer.toString()); if (jsonObject.containsKey("info")) { listener.getLogger().println(jsonObject.get("info")); } else { interrupted = true; if (jsonObject.containsKey("error")) { throw new IOException(jsonObject.get("error").toString()); } else { vulnerabilityAudit = jsonObject; } } buffer.setLength(0); } } br.close(); in.close(); socket.close(); //Process json report and present it Iterator<String> tools = (Iterator<String>) vulnerabilityAudit.keys(); while (tools.hasNext()) { String tool = tools.next(); listener.getLogger().println("\n" + tool); //Gets an object with all security levels (High, Medium, Low, Info) JSONObject securityLevels = vulnerabilityAudit.getJSONObject(tool); Iterator<String> levelsKeys = (Iterator<String>) securityLevels.keys(); if (!levelsKeys.hasNext()) listener.getLogger().println(String.format("- No report found")); while (levelsKeys.hasNext()) { String level = levelsKeys.next(); String value = String.valueOf(securityLevels.get(level)); listener.getLogger().println(String.format("- %s [%s]", level, value)); } } } return vulnerabilityAudit; } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { @Getter @Setter private String WSAP_LOCATION; @Getter @Setter private String TARGET_URL; @Getter @Setter private String ENV_VAR; @Getter @Setter private String SCANNER_IP; @Getter @Setter private String SCANNER_PORT; public DescriptorImpl() { load(); } @Override public synchronized void load() { WSAP_LOCATION = "WSAP_LOCATION_DIRECTORY/wsap"; TARGET_URL = "http://TARGET_URL"; ENV_VAR = "DEFINE_ME"; SCANNER_IP = "127.0.0.1"; SCANNER_PORT = "8010"; super.load(); } public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String credentialsId) { StandardListBoxModel result = new StandardListBoxModel(); return result .includeEmptyValue() .includeAs(ACL.SYSTEM, context, SSHUserPrivateKey.class, Collections.<DomainRequirement>singletonList(SSH_SCHEME)) .includeCurrentValue(credentialsId); } @Override public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } @NonNull @Override public String getDisplayName() { return "Web Security Application Project (WSAP)"; } public FormValidation doCheckPort(@QueryParameter String port){ try{ if (Long.parseLong(port)<0) { return FormValidation.error("Please enter a positive number"); }else{ return FormValidation.ok(); } }catch (Exception ex){ return FormValidation.error("Please enter a valid number"); } } public FormValidation doCheckScanMethod(@QueryParameter String value){ return FormValidation.error(value); } public FormValidation doCheckTargetUrl(@QueryParameter String targetUrl){ try { new URL(targetUrl).toURI(); return FormValidation.ok(); } catch (MalformedURLException | URISyntaxException e) { return FormValidation.error(e.getMessage()); } } public FormValidation doCheckCredentialId(@QueryParameter String credentialId){ if (credentialId == null || credentialId.isEmpty()){ return FormValidation.error("Please provide a credentialsID"); } return FormValidation.ok(); } } }
package com.oregonscientific.meep.youtube; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.FactoryConfigurationError; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.oregonscientific.meep.account.Account; import com.oregonscientific.meep.youtube.BuildConfig; import com.oregonscientific.meep.youtube.Consts; import com.oregonscientific.meep.youtube.R; import com.oregonscientific.meep.customdialog.CommonPopup; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.inputmethod.InputMethodManager; public class YouTubeUtility { public static boolean isValidDomain(String url) { String regex = new StringBuilder().append("((?:(http|https|Http|Https|rtsp|Rtsp):").append("\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)").append("\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_").append("\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?").append("((?:(?:[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}\\.)+") // named // host .append("(?:") // plus top level domain .append("(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])").append("|(?:biz|b[abdefghijmnorstvwyz])").append("|(?:cat|com|coop|c[acdfghiklmnoruvxyz])").append("|d[ejkmoz]").append("|(?:edu|e[cegrstu])").append("|f[ijkmor]").append("|(?:gov|g[abdefghilmnpqrstuwy])").append("|h[kmnrtu]").append("|(?:info|int|i[delmnoqrst])").append("|(?:jobs|j[emop])").append("|k[eghimnrwyz]").append("|l[abcikrstuvy]").append("|(?:mil|mobi|museum|m[acdghklmnopqrstuvwxyz])").append("|(?:name|net|n[acefgilopruz])").append("|(?:org|om)").append("|(?:pro|p[aefghklmnrstwy])").append("|qa").append("|r[eouw]").append("|s[abcdeghijklmnortuvyz]").append("|(?:tel|travel|t[cdfghjklmnoprtvwz])").append("|u[agkmsyz]").append("|v[aceginu]").append("|w[fs]").append("|y[etu]").append("|z[amw]))").append("|(?:(?:25[0-5]|2[0-4]") // or // ip // address .append("[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]").append("|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1]").append("[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}").append("|[1-9][0-9]|[0-9])))").append("(?:\\:\\d{1,5})?)") // plus // option // port // number .append("(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~") // plus // option // query // params .append("\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?").append("(?:\\b|$)").toString(); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(url); return matcher.matches(); } public static void hideKeyboard(Context context, View v) { // hide keyboard InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } public static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // networkInfo will be null if no network is available, otherwise // connected if (networkInfo != null && networkInfo.isConnected()) { return true; } return false; } public static String queryLatestPlaylistVideo(PlaylistId pPlaylistId) throws IOException, ClientProtocolException, FactoryConfigurationError { String lVideoId = null; HttpClient lClient = new DefaultHttpClient(); HttpGet lGetMethod = new HttpGet(OpenYouTubePlayerActivity.YOUTUBE_PLAYLIST_ATOM_FEED_URL + pPlaylistId.getId()+"?v=2&max-results=50&alt=json"); HttpResponse lResp = null; lResp = lClient.execute(lGetMethod); ByteArrayOutputStream lBOS = new ByteArrayOutputStream(); String lInfoStr = null; JSONObject lYouTubeResponse = null; try { lResp.getEntity().writeTo(lBOS); lInfoStr = lBOS.toString("UTF-8"); lYouTubeResponse = new JSONObject(lInfoStr); JSONArray lEntryArr = lYouTubeResponse.getJSONObject("feed").getJSONArray("entry"); JSONArray lLinkArr = lEntryArr.getJSONObject(lEntryArr.length()-1).getJSONArray("link"); for(int i=0; i<lLinkArr.length(); i++){ JSONObject lLinkObj = lLinkArr.getJSONObject(i);; String lRelVal = lLinkObj.optString("rel", null); if( lRelVal != null && lRelVal.equals("alternate")){ String lUriStr = lLinkObj.optString("href", null); Uri lVideoUri = Uri.parse(lUriStr); lVideoId = lVideoUri.getQueryParameter("v"); break; } } } catch (IllegalStateException e) { Log.i(YouTubeUtility.class.getSimpleName(), "Error retrieving content from YouTube", e); } catch (IOException e) { Log.i(YouTubeUtility.class.getSimpleName(), "Error retrieving content from YouTube", e); } catch(JSONException e){ Log.i(YouTubeUtility.class.getSimpleName(), "Error retrieving content from YouTube", e); } return lVideoId; } /** * Calculate the YouTube URL to load the video. Includes retrieving a token that YouTube * requires to play the video. * * @param pYouTubeFmtQuality quality of the video. 17=low, 18=high * @param bFallback whether to fallback to lower quality in case the supplied quality is not available * @param pYouTubeVideoId the id of the video * @return the url string that will retrieve the video * @throws IOException * @throws ClientProtocolException * @throws UnsupportedEncodingException */ public static String calculateYouTubeUrl(String pYouTubeFmtQuality, boolean pFallback, String pYouTubeVideoId) throws IOException, ClientProtocolException, UnsupportedEncodingException { String lUriStr = null; HttpClient lClient = new DefaultHttpClient(); HttpGet lGetMethod = new HttpGet(OpenYouTubePlayerActivity.YOUTUBE_VIDEO_INFORMATION_URL + pYouTubeVideoId); HttpResponse lResp = null; lResp = lClient.execute(lGetMethod); ByteArrayOutputStream lBOS = new ByteArrayOutputStream(); String lInfoStr = null; lResp.getEntity().writeTo(lBOS); lInfoStr = new String(lBOS.toString("UTF-8")); String[] lArgs=lInfoStr.split("&"); Map<String,String> lArgMap = new HashMap<String, String>(); for(int i=0; i<lArgs.length; i++){ String[] lArgValStrArr = lArgs[i].split("="); if(lArgValStrArr != null){ if(lArgValStrArr.length >= 2){ lArgMap.put(lArgValStrArr[0], URLDecoder.decode(lArgValStrArr[1])); } } } //Find out the URI string from the parameters //Populate the list of formats for the video String lFmtList = URLDecoder.decode(lArgMap.get("fmt_list")); ArrayList<Format> lFormats = new ArrayList<Format>(); if(null != lFmtList){ String lFormatStrs[] = lFmtList.split(","); for(String lFormatStr : lFormatStrs){ Format lFormat = new Format(lFormatStr); lFormats.add(lFormat); } } //Populate the list of streams for the video String lStreamList = lArgMap.get("url_encoded_fmt_stream_map"); if(null != lStreamList){ String lStreamStrs[] = lStreamList.split(","); ArrayList<VideoStream> lStreams = new ArrayList<VideoStream>(); for(String lStreamStr : lStreamStrs){ VideoStream lStream = new VideoStream(lStreamStr); lStreams.add(lStream); } //Search for the given format in the list of video formats // if it is there, select the corresponding stream // otherwise if fallback is requested, check for next lower format int lFormatId = Integer.parseInt(pYouTubeFmtQuality); Format lSearchFormat = new Format(lFormatId); while(!lFormats.contains(lSearchFormat) && pFallback ){ int lOldId = lSearchFormat.getId(); int lNewId = getSupportedFallbackId(lOldId); if(lOldId == lNewId){ break; } lSearchFormat = new Format(lNewId); } int lIndex = lFormats.indexOf(lSearchFormat); if(lIndex >= 0){ VideoStream lSearchStream = lStreams.get(lIndex); lUriStr = lSearchStream.getUrl(); } } //Return the URI string. It may be null if the format (or a fallback format if enabled) // is not found in the list of formats for the video return lUriStr; } public static boolean hasVideoBeenViewed(Context pCtxt, String pVideoId) { SharedPreferences lPrefs = PreferenceManager.getDefaultSharedPreferences(pCtxt); String lViewedVideoIds = lPrefs.getString("com.keyes.screebl.lastViewedVideoIds", null); if(lViewedVideoIds == null){ return false; } String[] lSplitIds =lViewedVideoIds.split(";"); if(lSplitIds == null || lSplitIds.length == 0){ return false; } for(int i=0; i<lSplitIds.length; i++){ if(lSplitIds[i] != null && lSplitIds[i].equals(pVideoId)){ return true; } } return false; } public static void markVideoAsViewed(Context pCtxt, String pVideoId){ SharedPreferences lPrefs = PreferenceManager.getDefaultSharedPreferences(pCtxt); if(pVideoId == null){ return; } String lViewedVideoIds = lPrefs.getString("com.keyes.screebl.lastViewedVideoIds", null); if(lViewedVideoIds == null){ lViewedVideoIds = ""; } String[] lSplitIds =lViewedVideoIds.split(";"); if(lSplitIds == null){ lSplitIds = new String[]{}; } // make a hash table of the ids to deal with duplicates Map<String, String> lMap = new HashMap<String, String>(); for(int i=0; i<lSplitIds.length; i++){ lMap.put(lSplitIds[i], lSplitIds[i]); } // recreate the viewed list String lNewIdList = ""; Set<String> lKeys = lMap.keySet(); Iterator<String> lIter = lKeys.iterator(); while(lIter.hasNext()){ String lId = lIter.next(); if( ! lId.trim().equals("")){ lNewIdList += lId + ";"; } } // add the new video id lNewIdList += pVideoId + ";"; Editor lPrefEdit = lPrefs.edit(); lPrefEdit.putString("com.keyes.screebl.lastViewedVideoIds", lNewIdList); lPrefEdit.commit(); } public static int getSupportedFallbackId(int pOldId){ final int lSupportedFormatIds[] = {13, //3GPP (MPEG-4 encoded) Low quality 17, //3GPP (MPEG-4 encoded) Medium quality 18, //MP4 (H.264 encoded) Normal quality 22, //MP4 (H.264 encoded) High quality 37 //MP4 (H.264 encoded) High quality }; int lFallbackId = pOldId; for(int i = lSupportedFormatIds.length - 1; i >= 0; i--){ if(pOldId == lSupportedFormatIds[i] && i > 0){ lFallbackId = lSupportedFormatIds[i-1]; } } return lFallbackId; } public static String getDirs(String path) { File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } return path; } public static String readFile(String path) { // Get the text file File file = new File(path); String line = null; // Read text from file StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { text.append(line); } } catch (IOException e) { // You'll need to add proper error handling here } Log.d("test", text.toString()); return text.toString(); } public static String getAccountToken(Context context) { SharedPreferences sp = context.getSharedPreferences(Consts.PREFERENCE_FILE_NAME, Context.MODE_PRIVATE); return sp.getString(Consts.PREFERENCE_KEY_TOKEN, ""); } // public static String getAccountMeeptag(Context context) { // SharedPreferences sp = context.getSharedPreferences(Consts.PREFERENCE_FILE_NAME, Context.MODE_PRIVATE); // return sp.getString(Consts.PREFERENCE_KEY_MEEPTAG, ""); // } public static String getAccountID(Context context) { SharedPreferences sp = context.getSharedPreferences(Consts.PREFERENCE_FILE_NAME, Context.MODE_PRIVATE); if(sp!=null){ return sp.getString(Consts.PREFERENCE_KEY_ID, ""); }else{ return ""; } } public static void setAccountInformation(Context context, Account account) { SharedPreferences sp = context.getSharedPreferences(Consts.PREFERENCE_FILE_NAME, Context.MODE_PRIVATE); Editor edit = sp.edit(); edit.clear(); edit.putString(Consts.PREFERENCE_KEY_TOKEN, account.getToken()); edit.putString(Consts.PREFERENCE_KEY_FIRSTNAME, account.getFirstName()); edit.putString(Consts.PREFERENCE_KEY_LASTNAME, account.getLastName()); edit.putString(Consts.PREFERENCE_KEY_MEEPTAG, account.getMeepTag()); edit.putString(Consts.PREFERENCE_KEY_ID, account.getId()); edit.commit(); } public static void alertMessage(Context context, String title, String message) { CommonPopup popup = new CommonPopup(context, title, message); // popup.show(); popup.setTextGravity(Gravity.CENTER_VERTICAL); popup.show(); } public static void alertMessage(Context context, int title, int message) { CommonPopup popup = new CommonPopup(context, title, message); // popup.show(); popup.setTextGravity(Gravity.CENTER_VERTICAL); popup.show(); } public static void alertDebugMessage(Context context, String message) { CommonPopup popup = new CommonPopup(context, "DEBUG", "FOR DEBUG: " + message); // popup.show(); popup.setTextGravity(Gravity.CENTER_VERTICAL); popup.show(); } public static void printLogcatDebugMessage(String text) { if(BuildConfig.DEBUG) Log.d("DEBUG", text); } public static Message generateAlertMessageObject() { Bundle bundle = new Bundle(); bundle.putInt(Consts.BUNDLE_KEY_ALERT_MESSAGE_CONTENT, R.string.cannot_use_now); Message message = new Message(); message.what = Consts.MESSAGE_WHAT_ALERT_MESSAGE_CONTENT; message.setData(bundle); return message; } public static void openWifiSettings(Context context) { final Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings"); intent.setComponent(cn); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }
package com.company.springboot.entities.dto; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; public class UserRegistrationDto { @NotBlank(message = "Enter first Name") @Size(min=6, max=15) private String firstName; @NotBlank(message = "Enter last Name") private String lastName; @NotBlank(message = "Enter your email.") @Email(message = "Enter a valid email address.") private String email; @NotBlank(message = "Enter your password.") @Size(min=6, max=30) private String password; public UserRegistrationDto() { } public UserRegistrationDto(String firstName, String lastName, String email, String password) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.quinn.framework.api.file; import com.quinn.util.base.model.BaseResult; import java.io.InputStream; /** * 文件存储业务接口 * * @author Qunhua.Liao * @since 2020-04-03 */ public interface StorageService { /** * 上传文件 * * @param fileInfoAdapter 文件信息 * @return 文件保存结果,同时补全了保存成功后的信息 */ BaseResult<FileInfoAdapter> upload(FileInfoAdapter fileInfoAdapter); /** * 下载文件 * * @param fileInfoAdapter 文件信息 */ void download(FileInfoAdapter fileInfoAdapter); /** * 将文件读如内存 * * @param fileInfoAdapter 文件信息 * @return 获取文件流 */ InputStream readAsStream(FileInfoAdapter fileInfoAdapter); /** * 判断文件是否存在 * * @param fileInfoAdapter 文件信息 * @return 文件是否存在 */ boolean exists(FileInfoAdapter fileInfoAdapter); /** * 删除文件 * * @param fileInfoAdapter 文件信息 * @return 删除文件结果 */ BaseResult<FileInfoAdapter> delete(FileInfoAdapter fileInfoAdapter); /** * 获取服务类型:一般对应一种不同的实现方式 * * @return 存储服务类型 */ String storageType(); }
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * An assortment of mainly legacy static utility methods that operate on or return objects of type * {@code Iterable}. Except as noted, each method has a corresponding {@link Iterator}-based method * in the {@link Iterators} class. * * <p><b>Java 8 users:</b> several common uses for this class are now more comprehensively addressed * by the new {@link java.util.stream.Stream} library. Read the method documentation below for * comparisons. This class is not being deprecated, but we gently encourage you to migrate to * streams. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables produced in this class * are <i>lazy</i>, which means that their iterators only advance the backing iteration when * absolutely necessary. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#iterables">{@code * Iterables}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Iterables { private Iterables() {} /** Returns an unmodifiable view of {@code iterable}. */ public static <T extends @Nullable Object> Iterable<T> unmodifiableIterable( final Iterable<? extends T> iterable) { checkNotNull(iterable); if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe Iterable<T> result = (Iterable<T>) iterable; return result; } return new UnmodifiableIterable<>(iterable); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <E> Iterable<E> unmodifiableIterable(ImmutableCollection<E> iterable) { return checkNotNull(iterable); } private static final class UnmodifiableIterable<T extends @Nullable Object> extends FluentIterable<T> { private final Iterable<? extends T> iterable; private UnmodifiableIterable(Iterable<? extends T> iterable) { this.iterable = iterable; } @Override public Iterator<T> iterator() { return Iterators.unmodifiableIterator(iterable.iterator()); } @Override public void forEach(Consumer<? super T> action) { iterable.forEach(action); } @SuppressWarnings("unchecked") // safe upcast, assuming no one has a crazy Spliterator subclass @Override public Spliterator<T> spliterator() { return (Spliterator<T>) iterable.spliterator(); } @Override public String toString() { return iterable.toString(); } // no equals and hashCode; it would break the contract! } /** Returns the number of elements in {@code iterable}. */ public static int size(Iterable<?> iterable) { return (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : Iterators.size(iterable.iterator()); } /** * Returns {@code true} if {@code iterable} contains any element {@code o} for which {@code * Objects.equals(o, element)} would return {@code true}. Otherwise returns {@code false}, even in * cases where {@link Collection#contains} might throw {@link NullPointerException} or {@link * ClassCastException}. */ // <? extends @Nullable Object> instead of <?> because of Kotlin b/189937072, discussed in Joiner. public static boolean contains( Iterable<? extends @Nullable Object> iterable, @CheckForNull Object element) { if (iterable instanceof Collection) { Collection<?> collection = (Collection<?>) iterable; return Collections2.safeContains(collection, element); } return Iterators.contains(iterable.iterator(), element); } /** * Removes, from an iterable, every element that belongs to the provided collection. * * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a collection, and * {@link Iterators#removeAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterable} */ @CanIgnoreReturnValue public static boolean removeAll(Iterable<?> removeFrom, Collection<?> elementsToRemove) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); } /** * Removes, from an iterable, every element that does not belong to the provided collection. * * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a collection, and * {@link Iterators#retainAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterable} */ @CanIgnoreReturnValue public static boolean retainAll(Iterable<?> removeFrom, Collection<?> elementsToRetain) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); } /** * Removes, from an iterable, every element that satisfies the provided predicate. * * <p>Removals may or may not happen immediately as each element is tested against the predicate. * The behavior of this method is not specified if {@code predicate} is dependent on {@code * removeFrom}. * * <p><b>Java 8 users:</b> if {@code removeFrom} is a {@link Collection}, use {@code * removeFrom.removeIf(predicate)} instead. * * @param removeFrom the iterable to (potentially) remove elements from * @param predicate a predicate that determines whether an element should be removed * @return {@code true} if any elements were removed from the iterable * @throws UnsupportedOperationException if the iterable does not support {@code remove()}. * @since 2.0 */ @CanIgnoreReturnValue public static <T extends @Nullable Object> boolean removeIf( Iterable<T> removeFrom, Predicate<? super T> predicate) { if (removeFrom instanceof Collection) { return ((Collection<T>) removeFrom).removeIf(predicate); } return Iterators.removeIf(removeFrom.iterator(), predicate); } /** Removes and returns the first matching element, or returns {@code null} if there is none. */ @CheckForNull static <T extends @Nullable Object> T removeFirstMatching( Iterable<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); Iterator<T> iterator = removeFrom.iterator(); while (iterator.hasNext()) { T next = iterator.next(); if (predicate.apply(next)) { iterator.remove(); return next; } } return null; } /** * Determines whether two iterables contain equal elements in the same order. More specifically, * this method returns {@code true} if {@code iterable1} and {@code iterable2} contain the same * number of elements and every element of {@code iterable1} is equal to the corresponding element * of {@code iterable2}. */ public static boolean elementsEqual(Iterable<?> iterable1, Iterable<?> iterable2) { if (iterable1 instanceof Collection && iterable2 instanceof Collection) { Collection<?> collection1 = (Collection<?>) iterable1; Collection<?> collection2 = (Collection<?>) iterable2; if (collection1.size() != collection2.size()) { return false; } } return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); } /** * Returns a string representation of {@code iterable}, with the format {@code [e1, e2, ..., en]} * (that is, identical to {@link java.util.Arrays Arrays}{@code * .toString(Iterables.toArray(iterable))}). Note that for <i>most</i> implementations of {@link * Collection}, {@code collection.toString()} also gives the same result, but that behavior is not * generally guaranteed. */ public static String toString(Iterable<?> iterable) { return Iterators.toString(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}. * * <p><b>Java 8 users:</b> the {@code Stream} equivalent to this method is {@code * stream.collect(MoreCollectors.onlyElement())}. * * @throws NoSuchElementException if the iterable is empty * @throws IllegalArgumentException if the iterable contains multiple elements */ @ParametricNullness public static <T extends @Nullable Object> T getOnlyElement(Iterable<T> iterable) { return Iterators.getOnlyElement(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}, or {@code defaultValue} if the * iterable is empty. * * <p><b>Java 8 users:</b> the {@code Stream} equivalent to this method is {@code * stream.collect(MoreCollectors.toOptional()).orElse(defaultValue)}. * * @throws IllegalArgumentException if the iterator contains multiple elements */ @ParametricNullness public static <T extends @Nullable Object> T getOnlyElement( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { return Iterators.getOnlyElement(iterable.iterator(), defaultValue); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @param type the type of the elements * @return a newly-allocated array into which all the elements of the iterable have been copied */ @GwtIncompatible // Array.newInstance(Class, int) /* * If we could express Class<@Nonnull T>, we could generalize the type parameter to <T extends * @Nullable Object>, and then we could accept an Iterable<? extends T> and return a plain T[] * instead of a @Nullable T[]. */ public static <T> @Nullable T[] toArray(Iterable<? extends @Nullable T> iterable, Class<T> type) { return toArray(iterable, ObjectArrays.newArray(type, 0)); } static <T extends @Nullable Object> T[] toArray(Iterable<? extends T> iterable, T[] array) { Collection<? extends T> collection = castOrCopyToCollection(iterable); return collection.toArray(array); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @return a newly-allocated array into which all the elements of the iterable have been copied */ static @Nullable Object[] toArray(Iterable<?> iterable) { return castOrCopyToCollection(iterable).toArray(); } /** * Converts an iterable into a collection. If the iterable is already a collection, it is * returned. Otherwise, an {@link java.util.ArrayList} is created with the contents of the * iterable in the same iteration order. */ private static <E extends @Nullable Object> Collection<E> castOrCopyToCollection( Iterable<E> iterable) { return (iterable instanceof Collection) ? (Collection<E>) iterable : Lists.newArrayList(iterable.iterator()); } /** * Adds all elements in {@code iterable} to {@code collection}. * * @return {@code true} if {@code collection} was modified as a result of this operation. */ @CanIgnoreReturnValue public static <T extends @Nullable Object> boolean addAll( Collection<T> addTo, Iterable<? extends T> elementsToAdd) { if (elementsToAdd instanceof Collection) { Collection<? extends T> c = (Collection<? extends T>) elementsToAdd; return addTo.addAll(c); } return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator()); } /** * Returns the number of elements in the specified iterable that equal the specified object. This * implementation avoids a full iteration when the iterable is a {@link Multiset} or {@link Set}. * * <p><b>Java 8 users:</b> In most cases, the {@code Stream} equivalent of this method is {@code * stream.filter(element::equals).count()}. If {@code element} might be null, use {@code * stream.filter(Predicate.isEqual(element)).count()} instead. * * @see java.util.Collections#frequency(Collection, Object) Collections.frequency(Collection, * Object) */ public static int frequency(Iterable<?> iterable, @CheckForNull Object element) { if ((iterable instanceof Multiset)) { return ((Multiset<?>) iterable).count(element); } else if ((iterable instanceof Set)) { return ((Set<?>) iterable).contains(element) ? 1 : 0; } return Iterators.frequency(iterable.iterator(), element); } /** * Returns an iterable whose iterators cycle indefinitely over the elements of {@code iterable}. * * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code * remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code * iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable} * is empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. * * <p>To cycle over the iterable {@code n} times, use the following: {@code * Iterables.concat(Collections.nCopies(n, iterable))} * * <p><b>Java 8 users:</b> The {@code Stream} equivalent of this method is {@code * Stream.generate(() -> iterable).flatMap(Streams::stream)}. */ public static <T extends @Nullable Object> Iterable<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.cycle(iterable); } @Override public Spliterator<T> spliterator() { return Stream.generate(() -> iterable).<T>flatMap(Streams::stream).spliterator(); } @Override public String toString() { return iterable.toString() + " (cycled)"; } }; } /** * Returns an iterable whose iterators cycle indefinitely over the provided elements. * * <p>After {@code remove} is invoked on a generated iterator, the removed element will no longer * appear in either that iterator or any other iterator created from the same source iterable. * That is, this method behaves exactly as {@code Iterables.cycle(Lists.newArrayList(elements))}. * The iterator's {@code hasNext} method returns {@code true} until all of the original elements * have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. * * <p>To cycle over the elements {@code n} times, use the following: {@code * Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} * * <p><b>Java 8 users:</b> If passing a single element {@code e}, the {@code Stream} equivalent of * this method is {@code Stream.generate(() -> e)}. Otherwise, put the elements in a collection * and use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}. */ @SafeVarargs public static <T extends @Nullable Object> Iterable<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}. The source * iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8 users:</b> The {@code Stream} equivalent of this method is {@code Stream.concat(a, * b)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b) { return FluentIterable.concat(a, b); } /** * Combines three iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the * elements in {@code c}. The source iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8 users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(a, b, c)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) { return FluentIterable.concat(a, b, c); } /** * Combines four iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the * elements in {@code c}, followed by the elements in {@code d}. The source iterators are not * polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8 users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(a, b, c, d)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c, Iterable<? extends T> d) { return FluentIterable.concat(a, b, c, d); } /** * Combines multiple iterables into a single iterable. The returned iterable has an iterator that * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled * until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8 users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(...)}. * * @throws NullPointerException if any of the provided iterables is null */ @SafeVarargs public static <T extends @Nullable Object> Iterable<T> concat(Iterable<? extends T>... inputs) { return FluentIterable.concat(inputs); } /** * Combines multiple iterables into a single iterable. The returned iterable has an iterator that * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled * until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. The methods of the returned iterable may throw {@code * NullPointerException} if any of the input iterators is null. * * <p><b>Java 8 users:</b> The {@code Stream} equivalent of this method is {@code * streamOfStreams.flatMap(s -> s)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends Iterable<? extends T>> inputs) { return FluentIterable.concat(inputs); } /** * Divides an iterable into unmodifiable sublists of the given size (the final iterable may be * smaller). For example, partitioning an iterable containing {@code [a, b, c, d, e]} with a * partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterable containing two * inner lists of three and two elements, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} * method. The returned lists implement {@link RandomAccess}, whether or not the input list does. * * <p><b>Note:</b> The current implementation eagerly allocates storage for {@code size} elements. * As a consequence, passing values like {@code Integer.MAX_VALUE} can lead to {@link * OutOfMemoryError}. * * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link Lists#partition(List, int)} * instead. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided * into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T extends @Nullable Object> Iterable<List<T>> partition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.partition(iterable.iterator(), size); } }; } /** * Divides an iterable into unmodifiable sublists of the given size, padding the final iterable * with null values if necessary. For example, partitioning an iterable containing {@code [a, b, * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer * iterable containing two inner lists of three elements each, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} * method. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided * into partitions (the final iterable may have trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T extends @Nullable Object> Iterable<List<@Nullable T>> paddedPartition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<@Nullable T>>() { @Override public Iterator<List<@Nullable T>> iterator() { return Iterators.paddedPartition(iterable.iterator(), size); } }; } /** * Returns a view of {@code unfiltered} containing all elements that satisfy the input predicate * {@code retainIfTrue}. The returned iterable's iterator does not support {@code remove()}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter}. */ public static <T extends @Nullable Object> Iterable<T> filter( final Iterable<T> unfiltered, final Predicate<? super T> retainIfTrue) { checkNotNull(unfiltered); checkNotNull(retainIfTrue); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), retainIfTrue); } @Override public void forEach(Consumer<? super T> action) { checkNotNull(action); unfiltered.forEach( (@ParametricNullness T a) -> { if (retainIfTrue.test(a)) { action.accept(a); } }); } @Override public Spliterator<T> spliterator() { return CollectSpliterators.filter(unfiltered.spliterator(), retainIfTrue); } }; } /** * Returns a view of {@code unfiltered} containing all elements that are of the type {@code * desiredType}. The returned iterable's iterator does not support {@code remove()}. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}. * This does perform a little more work than necessary, so another option is to insert an * unchecked cast at some later point: * * <pre> * {@code @SuppressWarnings("unchecked") // safe because of ::isInstance check * ImmutableList<NewType> result = * (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());} * </pre> */ @SuppressWarnings("unchecked") @GwtIncompatible // Class.isInstance public static <T> Iterable<T> filter(final Iterable<?> unfiltered, final Class<T> desiredType) { checkNotNull(unfiltered); checkNotNull(desiredType); return (Iterable<T>) filter(unfiltered, Predicates.instanceOf(desiredType)); } /** * Returns {@code true} if any element in {@code iterable} satisfies the predicate. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch}. */ public static <T extends @Nullable Object> boolean any( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.any(iterable.iterator(), predicate); } /** * Returns {@code true} if every element in {@code iterable} satisfies the predicate. If {@code * iterable} is empty, {@code true} is returned. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch}. */ public static <T extends @Nullable Object> boolean all( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.all(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given predicate; use this * method only when such an element is known to exist. If it is possible that <i>no</i> element * will match, use {@link #tryFind} or {@link #find(Iterable, Predicate, Object)} instead. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst().get()} * * @throws NoSuchElementException if no element in {@code iterable} matches the given predicate */ @ParametricNullness public static <T extends @Nullable Object> T find( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.find(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given predicate, or {@code * defaultValue} if none found. Note that this can usually be handled more naturally using {@code * tryFind(iterable, predicate).or(defaultValue)}. * * <p><b>{@code Stream} equivalent:</b> {@code * stream.filter(predicate).findFirst().orElse(defaultValue)} * * @since 7.0 */ // The signature we really want here is... // // <T extends @Nullable Object> @JointlyNullable T find( // Iterable<? extends T> iterable, // Predicate<? super T> predicate, // @JointlyNullable T defaultValue); // // ...where "@JointlyNullable" is similar to @PolyNull but slightly different: // // - @PolyNull means "@Nullable or @Nonnull" // (That would be unsound for an input Iterable<@Nullable Foo>. So, if we wanted to use // @PolyNull, we would have to restrict this method to non-null <T>. But it has users who pass // iterables with null elements.) // // - @JointlyNullable means "@Nullable or no annotation" @CheckForNull public static <T extends @Nullable Object> T find( Iterable<? extends T> iterable, Predicate<? super T> predicate, @CheckForNull T defaultValue) { return Iterators.find(iterable.iterator(), predicate, defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code iterable} that satisfies the * given predicate, if such an element exists. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} * is matched in {@code iterable}, a NullPointerException will be thrown. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()} * * @since 11.0 */ public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.tryFind(iterable.iterator(), predicate); } /** * Returns the index in {@code iterable} of the first element that satisfies the provided {@code * predicate}, or {@code -1} if the Iterable has no such elements. * * <p>More formally, returns the lowest index {@code i} such that {@code * predicate.apply(Iterables.get(iterable, i))} returns {@code true}, or {@code -1} if there is no * such index. * * @since 2.0 */ public static <T extends @Nullable Object> int indexOf( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.indexOf(iterable.iterator(), predicate); } /** * Returns a view containing the result of applying {@code function} to each element of {@code * fromIterable}. * * <p>The returned iterable's iterator supports {@code remove()} if {@code fromIterable}'s * iterator does. After a successful {@code remove()} call, {@code fromIterable} no longer * contains the corresponding element. * * <p>If the input {@code Iterable} is known to be a {@code List} or other {@code Collection}, * consider {@link Lists#transform} and {@link Collections2#transform}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#map} */ public static <F extends @Nullable Object, T extends @Nullable Object> Iterable<T> transform( final Iterable<F> fromIterable, final Function<? super F, ? extends T> function) { checkNotNull(fromIterable); checkNotNull(function); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.transform(fromIterable.iterator(), function); } @Override public void forEach(Consumer<? super T> action) { checkNotNull(action); fromIterable.forEach((F f) -> action.accept(function.apply(f))); } @Override public Spliterator<T> spliterator() { return CollectSpliterators.map(fromIterable.spliterator(), function); } }; } /** * Returns the element at the specified position in an iterable. * * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (throws * {@code NoSuchElementException} if out of bounds) * * @param position position of the element to return * @return the element at the specified position in {@code iterable} * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to * the size of {@code iterable} */ @ParametricNullness public static <T extends @Nullable Object> T get(Iterable<T> iterable, int position) { checkNotNull(iterable); return (iterable instanceof List) ? ((List<T>) iterable).get(position) : Iterators.get(iterable.iterator(), position); } /** * Returns the element at the specified position in an iterable or a default value otherwise. * * <p><b>{@code Stream} equivalent:</b> {@code * stream.skip(position).findFirst().orElse(defaultValue)} (returns the default value if the index * is out of bounds) * * @param position position of the element to return * @param defaultValue the default value to return if {@code position} is greater than or equal to * the size of the iterable * @return the element at the specified position in {@code iterable} or {@code defaultValue} if * {@code iterable} contains fewer than {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @ParametricNullness public static <T extends @Nullable Object> T get( Iterable<? extends T> iterable, int position, @ParametricNullness T defaultValue) { checkNotNull(iterable); Iterators.checkNonnegative(position); if (iterable instanceof List) { List<? extends T> list = Lists.cast(iterable); return (position < list.size()) ? list.get(position) : defaultValue; } else { Iterator<? extends T> iterator = iterable.iterator(); Iterators.advance(iterator, position); return Iterators.getNext(iterator, defaultValue); } } /** * Returns the first element in {@code iterable} or {@code defaultValue} if the iterable is empty. * The {@link Iterators} analog to this method is {@link Iterators#getNext}. * * <p>If no default value is desired (and the caller instead wants a {@link * NoSuchElementException} to be thrown), it is recommended that {@code * iterable.iterator().next()} is used instead. * * <p>To get the only element in a single-element {@code Iterable}, consider using {@link * #getOnlyElement(Iterable)} or {@link #getOnlyElement(Iterable, Object)} instead. * * <p><b>{@code Stream} equivalent:</b> {@code stream.findFirst().orElse(defaultValue)} * * @param defaultValue the default value to return if the iterable is empty * @return the first element of {@code iterable} or the default value * @since 7.0 */ @ParametricNullness public static <T extends @Nullable Object> T getFirst( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { return Iterators.getNext(iterable.iterator(), defaultValue); } /** * Returns the last element of {@code iterable}. If {@code iterable} is a {@link List} with {@link * RandomAccess} support, then this operation is guaranteed to be {@code O(1)}. * * <p><b>{@code Stream} equivalent:</b> {@link Streams#findLast Streams.findLast(stream).get()} * * @return the last element of {@code iterable} * @throws NoSuchElementException if the iterable is empty */ @ParametricNullness public static <T extends @Nullable Object> T getLast(Iterable<T> iterable) { // TODO(kevinb): Support a concurrently modified collection? if (iterable instanceof List) { List<T> list = (List<T>) iterable; if (list.isEmpty()) { throw new NoSuchElementException(); } return getLastInNonemptyList(list); } return Iterators.getLast(iterable.iterator()); } /** * Returns the last element of {@code iterable} or {@code defaultValue} if the iterable is empty. * If {@code iterable} is a {@link List} with {@link RandomAccess} support, then this operation is * guaranteed to be {@code O(1)}. * * <p><b>{@code Stream} equivalent:</b> {@code Streams.findLast(stream).orElse(defaultValue)} * * @param defaultValue the value to return if {@code iterable} is empty * @return the last element of {@code iterable} or the default value * @since 3.0 */ @ParametricNullness public static <T extends @Nullable Object> T getLast( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { if (iterable instanceof Collection) { Collection<? extends T> c = (Collection<? extends T>) iterable; if (c.isEmpty()) { return defaultValue; } else if (iterable instanceof List) { return getLastInNonemptyList(Lists.cast(iterable)); } } return Iterators.getLast(iterable.iterator(), defaultValue); } @ParametricNullness private static <T extends @Nullable Object> T getLastInNonemptyList(List<T> list) { return list.get(list.size() - 1); } /** * Returns a view of {@code iterable} that skips its first {@code numberToSkip} elements. If * {@code iterable} contains fewer than {@code numberToSkip} elements, the returned iterable skips * all of its elements. * * <p>Modifications to the underlying {@link Iterable} before a call to {@code iterator()} are * reflected in the returned iterator. That is, the iterator skips the first {@code numberToSkip} * elements that exist when the {@code Iterator} is created, not when {@code skip()} is called. * * <p>The returned iterable's iterator supports {@code remove()} if the iterator of the underlying * iterable supports it. Note that it is <i>not</i> possible to delete the last skipped element by * immediately calling {@code remove()} on that iterator, as the {@code Iterator} contract states * that a call to {@code remove()} before a call to {@code next()} will throw an {@link * IllegalStateException}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#skip} * * @since 3.0 */ public static <T extends @Nullable Object> Iterable<T> skip( final Iterable<T> iterable, final int numberToSkip) { checkNotNull(iterable); checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { if (iterable instanceof List) { final List<T> list = (List<T>) iterable; int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).iterator(); } final Iterator<T> iterator = iterable.iterator(); Iterators.advance(iterator, numberToSkip); /* * We can't just return the iterator because an immediate call to its * remove() method would remove one of the skipped elements instead of * throwing an IllegalStateException. */ return new Iterator<T>() { boolean atStart = true; @Override public boolean hasNext() { return iterator.hasNext(); } @Override @ParametricNullness public T next() { T result = iterator.next(); atStart = false; // not called if next() fails return result; } @Override public void remove() { checkRemove(!atStart); iterator.remove(); } }; } @Override public Spliterator<T> spliterator() { if (iterable instanceof List) { final List<T> list = (List<T>) iterable; int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).spliterator(); } else { return Streams.stream(iterable).skip(numberToSkip).spliterator(); } } }; } /** * Returns a view of {@code iterable} containing its first {@code limitSize} elements. If {@code * iterable} contains fewer than {@code limitSize} elements, the returned view contains all of its * elements. The returned iterable's iterator supports {@code remove()} if {@code iterable}'s * iterator does. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#limit} * * @param iterable the iterable to limit * @param limitSize the maximum number of elements in the returned iterable * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T extends @Nullable Object> Iterable<T> limit( final Iterable<T> iterable, final int limitSize) { checkNotNull(iterable); checkArgument(limitSize >= 0, "limit is negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.limit(iterable.iterator(), limitSize); } @Override public Spliterator<T> spliterator() { return Streams.stream(iterable).limit(limitSize).spliterator(); } }; } /** * Returns a view of the supplied iterable that wraps each generated {@link Iterator} through * {@link Iterators#consumingIterator(Iterator)}. * * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will get entries from * {@link Queue#remove()} since {@link Queue}'s iteration order is undefined. Calling {@link * Iterator#hasNext()} on a generated iterator from the returned iterable may cause an item to be * immediately dequeued for return on a subsequent call to {@link Iterator#next()}. * * @param iterable the iterable to wrap * @return a view of the supplied iterable that wraps each generated iterator through {@link * Iterators#consumingIterator(Iterator)}; for queues, an iterable that generates iterators * that return and consume the queue's elements in queue order * @see Iterators#consumingIterator(Iterator) * @since 2.0 */ public static <T extends @Nullable Object> Iterable<T> consumingIterable( final Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return (iterable instanceof Queue) ? new ConsumingQueueIterator<>((Queue<T>) iterable) : Iterators.consumingIterator(iterable.iterator()); } @Override public String toString() { return "Iterables.consumingIterable(...)"; } }; } // Methods only in Iterables, not in Iterators /** * Determines if the given iterable contains no elements. * * <p>There is no precise {@link Iterator} equivalent to this method, since one can only ask an * iterator whether it has any elements <i>remaining</i> (which one does using {@link * Iterator#hasNext}). * * <p><b>{@code Stream} equivalent:</b> {@code !stream.findAny().isPresent()} * * @return {@code true} if the iterable contains no elements */ public static boolean isEmpty(Iterable<?> iterable) { if (iterable instanceof Collection) { return ((Collection<?>) iterable).isEmpty(); } return !iterable.iterator().hasNext(); } /** * Returns an iterable over the merged contents of all given {@code iterables}. Equivalent entries * will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterables} are in non-descending order as this * method does not sort its input. * * <p>For any equivalent elements across all {@code iterables}, it is undefined which element is * returned first. * * @since 11.0 */ @Beta public static <T extends @Nullable Object> Iterable<T> mergeSorted( final Iterable<? extends Iterable<? extends T>> iterables, final Comparator<? super T> comparator) { checkNotNull(iterables, "iterables"); checkNotNull(comparator, "comparator"); Iterable<T> iterable = new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.mergeSorted( Iterables.transform(iterables, Iterables.<T>toIterator()), comparator); } }; return new UnmodifiableIterable<>(iterable); } // TODO(user): Is this the best place for this? Move to fluent functions? // Useful as a public method? static <T extends @Nullable Object> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() { return new Function<Iterable<? extends T>, Iterator<? extends T>>() { @Override public Iterator<? extends T> apply(Iterable<? extends T> iterable) { return iterable.iterator(); } }; } }
package algorithms.associationrules.closedrules; /* This file is copyright (c) 2008-2012 Philippe Fournier-Viger * * This file is part of the SPMF DATA MINING SOFTWARE * (http://www.philippe-fournier-viger.com/spmf). * * SPMF 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 3 of the License, or (at your option) any later * version. * SPMF 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 * SPMF. If not, see <http://www.gnu.org/licenses/>. */ import algorithms.ArraysAlgos; import algorithms.associationrules.agrawal94_association_rules.AlgoAgrawalFaster94; import algorithms.associationrules.agrawal94_association_rules.AssocRule; import algorithms.associationrules.agrawal94_association_rules.AssocRules; import patterns.itemset_array_integers_with_tids_bitset.Itemset; import patterns.itemset_array_integers_with_tids_bitset.Itemsets; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * This is an implementation of the "faster algorithm" for generating association rules, * described in Agrawal & * al. 1994, IBM Research Report RJ9839, June 1994. * Here it is adapted for mining closed rules. * The main difference with AlgoAgrawalFaster94.java, is that this implementation takes * a different type of Itemset object as input. Moreover, the method CALCULATESUPPORT() is * different because if an itemset is not closed, we must find its closure to determine * its support. To avoid redundancy as much * as possible, this class is a subclass of AlgoAgrawalFaster94.java and share * several methods. * <br/><br/> * <p> * This implementation saves the result to a file * or can alternatively keep it into memory if no output * path is provided by the user when the runAlgorithm() * method is called. * * @author Philippe Fournier-Viger * @see AssocRule * @see AssocRules **/ public class AlgoClosedRules extends AlgoAgrawalFaster94 { // the frequent itemsets that will be used to generate the rules private Itemsets patterns; /** * Default constructor */ public AlgoClosedRules() { } /** * Run the algorithm * * @param patterns a set of frequent itemsets * @param output an output file path for writing the result or null if the user want this method to return the result * @param databaseSize the number of transactions in the database * @param minconf the minconf threshold * @return the set of association rules if the user wished to save them into memory * @throws IOException exception if error writing to the output file */ public AssocRules runAlgorithm(Itemsets patterns, String output, int databaseSize, double minconf) throws IOException { // save the parameters this.minconf = minconf; this.minlift = 0; usingLift = false; // start the algorithm return runAlgorithm(patterns, output, databaseSize); } /** * Run the algorithm * * @param patterns a set of frequent itemsets * @param output an output file path for writing the result or null if the user want this method to return the result * @param databaseSize the number of transactions in the database * @param minconf the minconf threshold * @param minlift the minlift threshold * @return the set of association rules if the user wished to save them into memory * @throws IOException exception if error writing to the output file */ public AssocRules runAlgorithm(Itemsets patterns, String output, int databaseSize, double minconf, double minlift) throws IOException { // save the parameters this.minconf = minconf; this.minlift = minlift; usingLift = true; // start the algorithm return runAlgorithm(patterns, output, databaseSize); } /** * Run the algorithm for generating association rules from a set of itemsets. * * @param patterns the set of itemsets * @param output the output file path. If null the result is saved in memory and returned by the method. * @param databaseSize the number of transactions in the original database * @return the set of rules found if the user chose to save the result to memory * @throws IOException exception if error while writting to file */ private AssocRules runAlgorithm(Itemsets patterns, String output, int databaseSize) throws IOException { // if the user want to keep the result into memory if (output == null) { writer = null; rules = new AssocRules("ASSOCIATION RULES"); } else { // if the user want to save the result to a file rules = null; writer = new BufferedWriter(new FileWriter(output)); } this.databaseSize = databaseSize; // record the time when the algorithm starts startTimestamp = System.currentTimeMillis(); // initialize variable to count the number of rules found ruleCount = 0; // save itemsets in a member variable this.patterns = patterns; // SORTING // First, we sort all itemsets having the same size by lexical order // We do this for optimization purposes. If the itemsets are sorted, it allows to // perform two optimizations: // 1) When we need to calculate the support of an itemset (in the method // "calculateSupport()") we can use a binary search instead of browsing the whole list. // 2) When combining itemsets to generate candidate, we can use the // lexical order to avoid comparisons (in the method "generateCandidates()"). // For itemsets of the same size for (List<Itemset> itemsetsSameSize : patterns.getLevels()) { // Sort by lexicographical order using a Comparator Collections.sort(itemsetsSameSize, new Comparator<Itemset>() { @Override public int compare(Itemset o1, Itemset o2) { // The following code assume that itemsets are the same size return ArraysAlgos.comparatorItemsetSameSize.compare(o1.getItems(), o2.getItems()); } }); } // END OF SORTING // Now we will generate the rules. // For each frequent itemset of size >=2 that we will name "lk" for (int k = 2; k < patterns.getLevels().size(); k++) { for (Itemset lk : patterns.getLevels().get(k)) { // create a variable H1 for recursion List<int[]> H1_for_recursion = new ArrayList<int[]>(); // For each itemset "itemsetSize1" of size 1 that is member of lk for (int item : lk.getItems()) { int itemsetHm_P_1[] = new int[]{item}; // make a copy of lk without items from hm_P_1 int[] itemset_Lk_minus_hm_P_1 = ArraysAlgos.cloneItemSetMinusOneItem(lk.getItems(), item); // Now we will calculate the support and confidence // of the rule: itemset_Lk_minus_hm_P_1 ==> hm_P_1 int support = calculateSupport(itemset_Lk_minus_hm_P_1); // THIS COULD BE // OPTIMIZED ? double supportAsDouble = (double) support; // calculate the confidence of the rule : itemset_Lk_minus_hm_P_1 ==> hm_P_1 double conf = lk.getAbsoluteSupport() / supportAsDouble; // if the confidence is lower than minconf if (conf < minconf || Double.isInfinite(conf)) { continue; } double lift = 0; int supportHm_P_1 = 0; // if the user is using the minlift threshold, we will need // to also calculate the lift of the rule: itemset_Lk_minus_hm_P_1 ==> hm_P_1 if (usingLift) { // if we want to calculate the lift, we need the support of hm_P_1 supportHm_P_1 = calculateSupport(itemsetHm_P_1); // if we want to calculate the lift, we need to add this. // calculate the lift double term1 = ((double) lk.getAbsoluteSupport()) / databaseSize; double term2 = supportAsDouble / databaseSize; double term3 = ((double) supportHm_P_1 / databaseSize); lift = term1 / (term2 * term3); // if the lift is not enough if (lift < minlift) { continue; } } // If we are here, it means that the rule respect the minconf and minlift parameters. // Therefore, we output the rule. saveRule(itemset_Lk_minus_hm_P_1, support, itemsetHm_P_1, supportHm_P_1, lk.getAbsoluteSupport(), conf, lift); // Then we keep the itemset hm_P_1 to find more rules using this itemset and lk. H1_for_recursion.add(itemsetHm_P_1); // ================ END OF WHAT I HAVE ADDED } // Finally, we make a recursive call to continue explores rules that can be made with "lk" apGenrules(k, 1, lk, H1_for_recursion); } } // close the file if we saved the result to a file if (writer != null) { writer.close(); } // record the end time of the algorithm execution endTimeStamp = System.currentTimeMillis(); // Return the rules found if the user chose to save the result to memory rather than a file. // Otherwise, null will be returned return rules; } /** * The ApGenRules as described in p.14 of the paper by Agrawal. * (see the Agrawal paper for more details). * * @param k the size of the first itemset used to generate rules * @param m the recursive depth of the call to this method (first time 1, then 2...) * @param lk the itemset that is used to generate rules * @param Hm a set of itemsets that can be used with lk to generate rules * @throws IOException exception if error while writing output file */ private void apGenrules(int k, int m, Itemset lk, List<int[]> Hm) throws IOException { // if the itemset "lk" that is used to generate rules is larger than the size of itemsets in "Hm" if (k > m + 1) { // Create a list that we will be used to store itemsets for the recursive call List<int[]> Hm_plus_1_for_recursion = new ArrayList<int[]>(); // generate candidates using Hm List<int[]> Hm_plus_1 = generateCandidateSizeK(Hm); // for each such candidates for (int[] hm_P_1 : Hm_plus_1) { // We subtract the candidate from the itemset "lk" int[] itemset_Lk_minus_hm_P_1 = ArraysAlgos.cloneItemSetMinusAnItemset(lk.getItems(), hm_P_1); // We will now calculate the support of the rule Lk/(hm_P_1) ==> hm_P_1 // we need it to calculate the confidence int support = calculateSupport(itemset_Lk_minus_hm_P_1); double supportAsDouble = (double) support; // calculate the confidence of the rule Lk/(hm_P_1) ==> hm_P_1 double conf = lk.getAbsoluteSupport() / supportAsDouble; // if the confidence is not enough than we don't need to consider // the rule Lk/(hm_P_1) ==> hm_P_1 anymore so we continue if (conf < minconf || Double.isInfinite(conf)) { continue; } double lift = 0; int supportHm_P_1 = 0; // if the user is using the minlift threshold, then we will need to calculate the lift of the // rule as well and check if the lift is higher or equal to minlift. if (usingLift) { // if we want to calculate the lift, we need the support of Hm+1 supportHm_P_1 = calculateSupport(hm_P_1); // calculate the lift of the rule: Lk/(hm_P_1) ==> hm_P_1 double term1 = ((double) lk.getAbsoluteSupport()) / databaseSize; double term2 = (supportAsDouble) / databaseSize; lift = term1 / (term2 * ((double) supportHm_P_1 / databaseSize)); // if the lift is not enough if (lift < minlift) { continue; } } // The rule has passed the confidence and lift threshold requirements, // so we can output it saveRule(itemset_Lk_minus_hm_P_1, support, hm_P_1, supportHm_P_1, lk.getAbsoluteSupport(), conf, lift); // if k == m+1, then we cannot explore further rules using Lk since Lk will be too small. if (k != m + 1) { Hm_plus_1_for_recursion.add(hm_P_1); } } // recursive call to apGenRules to find more rules using "lk" apGenrules(k, m + 1, lk, Hm_plus_1_for_recursion); } } /** * Calculate the support of an itemset by looking at the frequent patterns * of the same size. * Because patterns are sorted by lexical order, we use a binary search. * This is MUCH MORE efficient than just browsing the full list of patterns. * An alternative would be to use a trie to store patterns but it may require a bit more memory. * * @param itemset the itemset. * @return the support of the itemset */ private int calculateSupport(int[] itemset) { // We first get the list of patterns having the same size as "itemset" List<Itemset> patternsSameSize = patterns.getLevels().get(itemset.length); // // We perform a binary search to find the position of itemset in this list int first = 0; int last = patternsSameSize.size() - 1; while (first <= last) { int middle = (first + last) >> 1; // >>1 means to divide by 2 int[] itemsetMiddle = patternsSameSize.get(middle).getItems(); int comparison = ArraysAlgos.comparatorItemsetSameSize.compare(itemset, itemsetMiddle); if (comparison > 0) { first = middle + 1; // the itemset compared is larger than the subset according to the lexical order } else if (comparison < 0) { last = middle - 1; // the itemset compared is smaller than the subset is smaller according to the lexical order } else { // we have found the itemset, so we return its support. return patternsSameSize.get(middle).getAbsoluteSupport(); } } // If the itemset is not found in this list, it means that the itemset // is not closed, so we need to find the smallest superset (its closure) to // determine its support. // We start from itemset of length |itemset|+1 and increase the size of itemset after each // while loop. int size = itemset.length; loop: while (true) { size++; List<Itemset> patternsList = patterns.getLevels().get(size); // For each pattern of a given size for (Itemset pattern : patternsList) { int[] patternArray = pattern.getItems(); // If the first item of the pattern is larger than the first item of the itemset, // we don't need to compare with following patterns. if (patternArray[0] > itemset[0]) { continue loop; } // Otherwise, we check if itemset is contained in pattern int posItemset = 0; int posPattern = 0; while (posPattern < patternArray.length) { if (patternArray[posPattern] == itemset[posItemset]) { posItemset++; // if it is contained completely if (posItemset == itemset.length) { return pattern.getAbsoluteSupport(); } } else if (patternArray[posPattern] >= itemset[posItemset]) { // if the current item of pattern is larger than the current item in pattern, // then itemset cannot be contained in pattern so we stop considering it break; } posPattern++; } } } } }
package com.yunhui.bean; import lombok.Data; @Data public class Account { private String account; private String passwd; }
package top.srsea.capture.core.tunnel; import android.os.Handler; import android.os.Looper; import android.util.Log; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import top.srsea.capture.core.nat.NatSessionManager; import top.srsea.capture.struct.Packet; import top.srsea.capture.core.forward.UdpProxyServer; import top.srsea.capture.core.nat.NatSession; import top.srsea.capture.core.util.android.PortHostService; import top.srsea.capture.core.util.common.ACache; import top.srsea.capture.core.util.common.ThreadPool; import top.srsea.capture.core.util.common.TimeFormatter; import top.srsea.capture.core.util.net.TcpDataSaver; import top.srsea.capture.core.vpn.VpnServiceProxy; import top.srsea.torque.common.IOUtils; public class UdpTunnel implements KeyHandler { private static final String TAG = "UdpTunnel"; private static final int HEADER_SIZE = Packet.IP4_HEADER_SIZE + Packet.UDP_HEADER_SIZE; private final Selector selector; private final UdpProxyServer udpProxyServer; private final Queue<Packet> outputQueue; private final ConcurrentLinkedQueue<Packet> toNetWorkPackets = new ConcurrentLinkedQueue<>(); private final NatSession session; private final Handler handler; private String ipAndPort; private TcpDataSaver tcpDataSaver; private Packet referencePacket; private SelectionKey selectionKey; private DatagramChannel channel; private Short portKey; public UdpTunnel(Selector selector, UdpProxyServer udpProxyServer, Packet packet, Queue<Packet> outputQueue, short portKey) { this.selector = selector; this.udpProxyServer = udpProxyServer; this.referencePacket = packet; ipAndPort = packet.getIpAndPort(); this.outputQueue = outputQueue; this.portKey = portKey; session = NatSessionManager.getSession(portKey); handler = new Handler(Looper.getMainLooper()); String dir = new StringBuilder() .append(TcpDataSaver.DATA_DIR) .append(TimeFormatter.formatToYYMMDDHHMMSS(session.vpnStartTime)) .append("/") .append(session.getUniqueName()) .toString(); tcpDataSaver = new TcpDataSaver(dir); } private void processKey(SelectionKey key) { if (key.isWritable()) { processSend(); } else if (key.isReadable()) { processReceived(); } updateInterests(); } private void processReceived() { ByteBuffer receiveBuffer = ByteBuffer.allocate(VpnServiceProxy.getMtu()); receiveBuffer.position(HEADER_SIZE); int readBytes; try { readBytes = channel.read(receiveBuffer); } catch (Exception e) { udpProxyServer.closeUdpTunnel(this); return; } if (readBytes == -1) { udpProxyServer.closeUdpTunnel(this); } else if (readBytes == 0) { Log.d(TAG, "read no data :" + ipAndPort); } else { Log.d(TAG, "read readBytes:" + readBytes + " ipAndPort:" + ipAndPort); Packet newPacket = referencePacket.duplicated(); newPacket.updateUDPBuffer(receiveBuffer, readBytes); receiveBuffer.position(HEADER_SIZE + readBytes); outputQueue.offer(newPacket); session.receivePacketNum++; session.receiveByteNum += readBytes; session.lastRefreshTime = System.currentTimeMillis(); if (tcpDataSaver != null) { saveData(receiveBuffer.array(), readBytes, false); } } } private void saveData(byte[] array, int saveSize, boolean isRequest) { TcpDataSaver.TcpData saveTcpData = new TcpDataSaver.TcpData .Builder() .offSet(HEADER_SIZE) .length(saveSize) .needParseData(array) .isRequest(isRequest) .build(); tcpDataSaver.addData(saveTcpData); } private void processSend() { Log.d(TAG, "processWriteUDPData " + ipAndPort); Packet toNetWorkPacket = getToNetWorkPackets(); if (toNetWorkPacket == null) { Log.d(TAG, "write data no packet "); return; } try { ByteBuffer payloadBuffer = toNetWorkPacket.backingBuffer; session.packetSent++; int sendSize = payloadBuffer.limit() - payloadBuffer.position(); session.bytesSent += sendSize; if (tcpDataSaver != null) { saveData(payloadBuffer.array(), sendSize, true); } session.lastRefreshTime = System.currentTimeMillis(); while (payloadBuffer.hasRemaining()) { channel.write(payloadBuffer); } } catch (IOException e) { Log.w(TAG, "Network write error: " + ipAndPort, e); udpProxyServer.closeUdpTunnel(this); } } public void initConnection() { Log.d(TAG, "init ipAndPort:" + ipAndPort); InetAddress destinationAddress = referencePacket.ip4Header.destinationAddress; int destinationPort = referencePacket.udpHeader.destinationPort; try { channel = DatagramChannel.open(); VpnServiceProxy.protect(channel.socket()); channel.configureBlocking(false); channel.connect(new InetSocketAddress(destinationAddress, destinationPort)); selector.wakeup(); selectionKey = channel.register(selector, SelectionKey.OP_READ, this); } catch (IOException e) { IOUtils.close(channel); return; } referencePacket.swapSourceAndDestination(); addToNetWorkPacket(referencePacket); } public void processPacket(Packet packet) { addToNetWorkPacket(packet); updateInterests(); } public void close() { try { if (selectionKey != null) { selectionKey.cancel(); } if (channel != null) { channel.close(); } if (session.appInfo == null && PortHostService.getInstance() != null) { PortHostService.getInstance().refreshSessionInfo(); } handler.postDelayed(new Runnable() { @Override public void run() { ThreadPool.getInstance().execute(new Runnable() { @Override public void run() { if (session.receiveByteNum == 0 && session.bytesSent == 0) { return; } String configFileDir = TcpDataSaver.CONFIG_DIR + TimeFormatter.formatToYYMMDDHHMMSS(session.vpnStartTime); File parentFile = new File(configFileDir); if (!parentFile.exists()) { parentFile.mkdirs(); } File file = new File(parentFile, session.getUniqueName()); if (file.exists()) { return; } ACache configACache = ACache.get(parentFile); configACache.put(session.getUniqueName(), session); } }); } }, 1000); } catch (Exception e) { Log.w(TAG, "error to close UDP channel IpAndPort" + ipAndPort + ",error is " + e.getMessage()); } } public Packet getToNetWorkPackets() { return toNetWorkPackets.poll(); } private void addToNetWorkPacket(Packet packet) { toNetWorkPackets.offer(packet); updateInterests(); } DatagramChannel getChannel() { return channel; } private void updateInterests() { int ops; if (toNetWorkPackets.isEmpty()) { ops = SelectionKey.OP_READ; } else { ops = SelectionKey.OP_WRITE | SelectionKey.OP_READ; } selector.wakeup(); selectionKey.interestOps(ops); } public Packet getReferencePacket() { return referencePacket; } @Override public void onKeyReady(SelectionKey key) { processKey(key); } public Short getPortKey() { return portKey; } }
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.coprocessor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Collections; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MediumTests; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.regionserver.wal.WALEdit; import org.apache.hadoop.hbase.util.Threads; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Test that a coprocessor can open a connection and write to another table, inside a hook. */ @Category(MediumTests.class) public class TestOpenTableInCoprocessor { private static final TableName otherTable = TableName.valueOf("otherTable"); private static final TableName primaryTable = TableName.valueOf("primary"); private static final byte[] family = new byte[] { 'f' }; private static boolean[] completed = new boolean[1]; /** * Custom coprocessor that just copies the write to another table. */ public static class SendToOtherTableCoprocessor extends BaseRegionObserver { @Override public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e, final Put put, final WALEdit edit, final Durability durability) throws IOException { HTableInterface table = e.getEnvironment().getTable(otherTable); table.put(put); table.flushCommits(); completed[0] = true; table.close(); } } private static boolean[] completedWithPool = new boolean[1]; /** * Coprocessor that creates an HTable with a pool to write to another table */ public static class CustomThreadPoolCoprocessor extends BaseRegionObserver { /** * Get a pool that has only ever one thread. A second action added to the pool (running * concurrently), will cause an exception. * @return */ private ExecutorService getPool() { int maxThreads = 1; long keepAliveTime = 60; ThreadPoolExecutor pool = new ThreadPoolExecutor(1, maxThreads, keepAliveTime, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Threads.newDaemonThreadFactory("hbase-table")); pool.allowCoreThreadTimeOut(true); return pool; } @Override public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e, final Put put, final WALEdit edit, final Durability durability) throws IOException { HTableInterface table = e.getEnvironment().getTable(otherTable, getPool()); Put p = new Put(new byte[] { 'a' }); p.add(family, null, new byte[] { 'a' }); try { table.batch(Collections.singletonList(put)); } catch (InterruptedException e1) { throw new IOException(e1); } completedWithPool[0] = true; table.close(); } } private static HBaseTestingUtility UTIL = new HBaseTestingUtility(); @BeforeClass public static void setupCluster() throws Exception { UTIL.startMiniCluster(); } @After public void cleanupTestTable() throws Exception { UTIL.getHBaseAdmin().disableTable(primaryTable); UTIL.getHBaseAdmin().deleteTable(primaryTable); UTIL.getHBaseAdmin().disableTable(otherTable); UTIL.getHBaseAdmin().deleteTable(otherTable); } @AfterClass public static void teardownCluster() throws Exception { UTIL.shutdownMiniCluster(); } @Test public void testCoprocessorCanCreateConnectionToRemoteTable() throws Throwable { runCoprocessorConnectionToRemoteTable(SendToOtherTableCoprocessor.class, completed); } @Test public void testCoprocessorCanCreateConnectionToRemoteTableWithCustomPool() throws Throwable { runCoprocessorConnectionToRemoteTable(CustomThreadPoolCoprocessor.class, completedWithPool); } private void runCoprocessorConnectionToRemoteTable(Class<? extends BaseRegionObserver> clazz, boolean[] completeCheck) throws Throwable { HTableDescriptor primary = new HTableDescriptor(primaryTable); primary.addFamily(new HColumnDescriptor(family)); // add our coprocessor primary.addCoprocessor(clazz.getName()); HTableDescriptor other = new HTableDescriptor(otherTable); other.addFamily(new HColumnDescriptor(family)); HBaseAdmin admin = UTIL.getHBaseAdmin(); admin.createTable(primary); admin.createTable(other); HTable table = new HTable(UTIL.getConfiguration(), "primary"); Put p = new Put(new byte[] { 'a' }); p.add(family, null, new byte[] { 'a' }); table.put(p); table.flushCommits(); table.close(); HTable target = new HTable(UTIL.getConfiguration(), otherTable); assertTrue("Didn't complete update to target table!", completeCheck[0]); assertEquals("Didn't find inserted row", 1, getKeyValueCount(target)); target.close(); } /** * Count the number of keyvalue in the table. Scans all possible versions * @param table table to scan * @return number of keyvalues over all rows in the table * @throws IOException */ private int getKeyValueCount(HTable table) throws IOException { Scan scan = new Scan(); scan.setMaxVersions(Integer.MAX_VALUE - 1); ResultScanner results = table.getScanner(scan); int count = 0; for (Result res : results) { count += res.listCells().size(); System.out.println(count + ") " + res); } results.close(); return count; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.07.07 at 04:11:25 PM BRT // package net.sf.jabref.logic.importer.fileformat.medline; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{}text"> * &lt;attGroup ref="{}attlist.Param"/> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "Param") public class Param extends Text { @XmlAttribute(name = "Name", required = true) @XmlSchemaType(name = "anySimpleType") protected String name; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } }
package com.github.fantasticlab.rpc.core.exception; public class FrpcZookeeperException extends Exception { public FrpcZookeeperException(String message, Throwable cause) { super(message, cause); } }
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.car.app.activity; import static android.content.pm.PackageManager.NameNotFoundException; import static java.util.Objects.requireNonNull; import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.car.app.activity.renderer.ICarAppActivity; import androidx.car.app.activity.renderer.IRendererCallback; import androidx.car.app.activity.renderer.IRendererService; import androidx.car.app.activity.renderer.surface.ISurfaceListener; import androidx.car.app.activity.renderer.surface.OnBackPressedListener; import androidx.car.app.activity.renderer.surface.SurfaceHolderListener; import androidx.car.app.activity.renderer.surface.SurfaceWrapperProvider; import androidx.car.app.activity.renderer.surface.TemplateSurfaceView; import androidx.car.app.serialization.Bundleable; import androidx.car.app.utils.ThreadUtils; import androidx.fragment.app.FragmentActivity; import java.util.List; /** * The class representing a car app activity. * * <p>This class is responsible for binding to the host and rendering the content given by a {@link * androidx.car.app.CarAppService}. * * <p>Usage of {@link CarAppActivity} is only required for applications targeting Automotive OS. * * <h4>Activity Declaration</h4> * * <p>The app must declare an {@code activity-alias} for a {@link CarAppActivity} providing its * associated {@link androidx.car.app.CarAppService} as meta-data. For example: * * <pre>{@code * <activity-alias * android:enabled="true" * android:exported="true" * android:label="@string/your_app_label" * android:name=".YourActivityAliasName" * android:targetActivity="androidx.car.app.activity.CarAppActivity" > * <intent-filter> * <action android:name="android.intent.action.MAIN" /> * <category android:name="android.intent.category.LAUNCHER" /> * </intent-filter> * <meta-data * android:name="androidx.car.app.CAR_APP_SERVICE" * android:value=".YourCarAppService" /> * <meta-data android:name="distractionOptimized" android:value="true"/> * </activity-alias> * }</pre> * * <p>See {@link androidx.car.app.CarAppService} for how to declare your app's car app service in * the manifest. * * <p>Note the name of the alias should be unique and resemble a fully qualified class name, but * unlike the name of the target activity, the alias name is arbitrary; it does not refer to an * actual class. */ // TODO(b/179225768): Remove distractionOptimized from the javadoc above if we can make that // implicit for car apps. @SuppressLint({"ForbiddenSuperClass"}) public final class CarAppActivity extends FragmentActivity { @VisibleForTesting static final String SERVICE_METADATA_KEY = "androidx.car.app.CAR_APP_SERVICE"; private static final String TAG = "CarAppActivity"; @SuppressLint({"ActionValue"}) @VisibleForTesting static final String ACTION_RENDER = "android.car.template.host.RendererService"; @Nullable private ComponentName mServiceComponentName; TemplateSurfaceView mSurfaceView; SurfaceHolderListener mSurfaceHolderListener; ActivityLifecycleDelegate mActivityLifecycleDelegate; @Nullable OnBackPressedListener mOnBackPressedListener; @Nullable IRendererService mRendererService; private int mDisplayId; /** * {@link ICarAppActivity} implementation that allows the {@link IRendererService} to * communicate with this {@link CarAppActivity}. */ private final ICarAppActivity.Stub mCarActivity = new ICarAppActivity.Stub() { @Override public void setSurfacePackage(@NonNull Bundleable surfacePackage) { requireNonNull(surfacePackage); ThreadUtils.runOnMain(() -> mSurfaceView.setSurfacePackage(surfacePackage)); } @Override public void registerRendererCallback(@NonNull IRendererCallback callback) { requireNonNull(callback); ThreadUtils.runOnMain( () -> { mSurfaceView.setOnCreateInputConnectionListener( editorInfo -> { try { return callback.onCreateInputConnection(editorInfo); } catch (RemoteException e) { onServiceConnectionError( "Failed to send onCreateInputConnection" + " event to renderer: " + e.getMessage(), ErrorActionType.FINISH); } return null; }); mOnBackPressedListener = () -> { try { callback.onBackPressed(); } catch (RemoteException e) { onServiceConnectionError( "Failed to send onBackPressed event to" + " renderer: " + e.getMessage(), ErrorActionType.FINISH); } }; mActivityLifecycleDelegate.registerRendererCallback(callback); }); } @Override public void setSurfaceListener(@NonNull ISurfaceListener listener) { requireNonNull(listener); ThreadUtils.runOnMain( () -> mSurfaceHolderListener.setSurfaceListener(listener)); } @Override public void onStartInput() { ThreadUtils.runOnMain(() -> mSurfaceView.onStartInput()); } @Override public void onStopInput() { ThreadUtils.runOnMain(() -> mSurfaceView.onStopInput()); } @Override public void startCarApp(@NonNull Intent intent) { startActivity(intent); } @Override public void finishCarApp() { finish(); } }; /** The service connection for the renderer service. */ private ServiceConnection mServiceConnectionImpl = new ServiceConnection() { @Override public void onServiceConnected( @NonNull ComponentName name, @NonNull IBinder service) { requireNonNull(name); requireNonNull(service); IRendererService rendererService = IRendererService.Stub.asInterface(service); if (rendererService == null) { onServiceConnectionError( String.format( "Failed to get IRenderService binder from host: %s", name.flattenToShortString()), ErrorActionType.FINISH); return; } verifyServiceVersion(rendererService); initializeService(rendererService); updateIntent(rendererService); CarAppActivity.this.mRendererService = rendererService; } @Override public void onServiceDisconnected(@NonNull ComponentName name) { onServiceConnectionError( String.format("Host service %s is disconnected", requireNonNull(name)), ErrorActionType.DISCONNECT); } }; @SuppressWarnings("deprecation") @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_template); mSurfaceView = requireViewById(R.id.template_view_surface); mActivityLifecycleDelegate = new ActivityLifecycleDelegate(); mSurfaceHolderListener = new SurfaceHolderListener(new SurfaceWrapperProvider(mSurfaceView)); mServiceComponentName = serviceComponentName(); if (mServiceComponentName == null) { Log.e(TAG, "Unspecified service class name"); finish(); return; } registerActivityLifecycleCallbacks(mActivityLifecycleDelegate); // Set the z-order to receive the UI events on the surface. mSurfaceView.setZOrderOnTop(true); mSurfaceView.getHolder().addCallback(mSurfaceHolderListener); mDisplayId = getWindowManager().getDefaultDisplay().getDisplayId(); bindService(); } @Override protected void onPause() { super.onPause(); if (mSurfaceView != null) { mSurfaceView.setVisibility(View.GONE); } } @Override protected void onResume() { super.onResume(); if (mSurfaceView != null) { mSurfaceView.setVisibility(View.VISIBLE); } } @Override protected void onDestroy() { if (isFinishing()) { unbindService(); } super.onDestroy(); } @Override public void onBackPressed() { if (mOnBackPressedListener != null) { mOnBackPressedListener.onBackPressed(); } } @Override protected void onNewIntent(@NonNull Intent intent) { super.onNewIntent(intent); if (mRendererService == null) { bindService(); } else { updateIntent(mRendererService); } } @VisibleForTesting ServiceConnection getServiceConnection() { return mServiceConnectionImpl; } @VisibleForTesting void setServiceConnection(ServiceConnection serviceConnection) { mServiceConnectionImpl = serviceConnection; } @VisibleForTesting int getDisplayId() { return mDisplayId; } @Nullable private ComponentName serviceComponentName() { ActivityInfo activityInfo = null; try { activityInfo = getPackageManager() .getActivityInfo(getComponentName(), PackageManager.GET_META_DATA); } catch (NameNotFoundException e) { Log.e(TAG, "Unable to find component: " + getComponentName(), e); } if (activityInfo == null) { return null; } String serviceName = activityInfo.metaData.getString(SERVICE_METADATA_KEY); if (serviceName == null) { Log.e( TAG, "Unable to find required metadata tag with name " + SERVICE_METADATA_KEY + ". App manifest must include metadata tag with name " + SERVICE_METADATA_KEY + " and the name of the car app service as the value"); return null; } return new ComponentName(this, serviceName); } /** Binds to the renderer service. */ private void bindService() { Intent rendererIntent = new Intent(ACTION_RENDER); List<ResolveInfo> resolveInfoList = getPackageManager() .queryIntentServices(rendererIntent, PackageManager.GET_META_DATA); if (resolveInfoList.size() == 1) { rendererIntent.setPackage(resolveInfoList.get(0).serviceInfo.packageName); if (!bindService( rendererIntent, mServiceConnectionImpl, Context.BIND_AUTO_CREATE | Context.BIND_INCLUDE_CAPABILITIES)) { onServiceConnectionError( "Cannot bind to the renderer host with intent: " + rendererIntent, ErrorActionType.FINISH); } } else if (resolveInfoList.isEmpty()) { onServiceConnectionError("Host was not found", ErrorActionType.REDIRECT); } else { StringBuilder logMessage = new StringBuilder("Multiple hosts found, only one is allowed"); for (ResolveInfo resolveInfo : resolveInfoList) { logMessage.append( String.format("\nFound host %s", resolveInfo.serviceInfo.packageName)); } onServiceConnectionError(logMessage.toString(), ErrorActionType.FINISH); // TODO("b/177083268: Multiple hosts support is not implemented") } } /** * Handles the service connection errors by unbinding from the service and finishing the * activity. * * @param errorMessage the error message to be shown in the logs */ void onServiceConnectionError(@Nullable String errorMessage, ErrorActionType type) { if (type == ErrorActionType.DISCONNECT) { Log.d(TAG, "Disconnect by user, don't kill the CarAppActivity"); return; } // Remove the renderer callback since there is no need to communicate the state with // the host. mActivityLifecycleDelegate.registerRendererCallback(null); unbindService(); if (errorMessage != null && type != null && !isFinishing()) { getSupportFragmentManager() .beginTransaction() .add( R.id.error_message_container, ErrorMessageFragment.newInstance(errorMessage, type)) .commit(); } else { finish(); } } /** * Verifies that the renderer service supports the current version. * * @param rendererService the renderer service which should verify the version */ void verifyServiceVersion(IRendererService rendererService) { // TODO(169604451) Add version support logic boolean isCompatible = true; if (!isCompatible) { onServiceConnectionError("Renderer service unsupported", ErrorActionType.REDIRECT); } } /** * Initializes the {@code rendererService} for the current activity with {@code carActivity}, * {@code serviceComponentName} and {@code displayId}. * * @param rendererService the renderer service that needs to be initialized */ void initializeService(@NonNull IRendererService rendererService) { requireNonNull(rendererService); requireNonNull(mServiceComponentName); try { if (!rendererService.initialize(mCarActivity, mServiceComponentName, mDisplayId)) { throw new IllegalArgumentException( "Cannot create renderer for" + mServiceComponentName); } } catch (RemoteException e) { onServiceConnectionError( "Failed to call onCreateActivity on renderer: " + e.getMessage(), ErrorActionType.FINISH); } } /** Closes the connection to the connected {@code rendererService} if any. */ private void unbindService() { mSurfaceView.getHolder().removeCallback(mSurfaceHolderListener); // If host has already disconnected, there is no need for an unbind. if (mRendererService == null) { return; } try { mRendererService.terminate(requireNonNull(mServiceComponentName)); } catch (RemoteException e) { // We are already unbinding (maybe because the host has already cut the connection) // Let's not log more errors unnecessarily. } unbindService(mServiceConnectionImpl); mRendererService = null; } /** * Updates the activity intent for the {@code rendererService}. * * @param rendererService the renderer service that needs to handle the new intent */ void updateIntent(@NonNull IRendererService rendererService) { requireNonNull(rendererService); requireNonNull(mServiceComponentName); Intent intent = getIntent(); try { if (!rendererService.onNewIntent(intent, mServiceComponentName, mDisplayId)) { throw new IllegalArgumentException("Renderer cannot handle the intent: " + intent); } } catch (RemoteException e) { onServiceConnectionError( "Failed to send new intent to renderer: " + e.getMessage(), ErrorActionType.FINISH); } } /** Indicate the action type when server connection hit error */ enum ErrorActionType { /** Redirect to PlayStore */ REDIRECT, /** Finish the CarAppActivity */ FINISH, /** Finish the CarAppActivity */ DISCONNECT, } }
/* * 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. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.ad.transport; import java.time.Instant; import java.util.Map; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.opensearch.action.support.WriteRequest; import org.opensearch.ad.TestHelpers; import org.opensearch.ad.model.AnomalyDetector; import org.opensearch.ad.util.RestHandlerUtils; import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.common.io.stream.NamedWriteableAwareStreamInput; import org.opensearch.common.io.stream.NamedWriteableRegistry; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.xcontent.ToXContent; import org.opensearch.common.xcontent.XContentBuilder; import org.opensearch.rest.RestRequest; import org.opensearch.rest.RestStatus; import org.opensearch.test.OpenSearchSingleNodeTestCase; import com.google.common.collect.ImmutableMap; public class IndexAnomalyDetectorActionTests extends OpenSearchSingleNodeTestCase { @Before public void setUp() throws Exception { super.setUp(); } @Override protected NamedWriteableRegistry writableRegistry() { return getInstanceFromNode(NamedWriteableRegistry.class); } @Test public void testIndexRequest() throws Exception { BytesStreamOutput out = new BytesStreamOutput(); AnomalyDetector detector = TestHelpers.randomAnomalyDetector(ImmutableMap.of("testKey", "testValue"), Instant.now()); IndexAnomalyDetectorRequest request = new IndexAnomalyDetectorRequest( "1234", 4321, 5678, WriteRequest.RefreshPolicy.NONE, detector, RestRequest.Method.PUT, TimeValue.timeValueSeconds(60), 1000, 10, 5 ); request.writeTo(out); NamedWriteableAwareStreamInput input = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), writableRegistry()); IndexAnomalyDetectorRequest newRequest = new IndexAnomalyDetectorRequest(input); Assert.assertEquals(request.getDetectorID(), newRequest.getDetectorID()); Assert.assertNull(newRequest.validate()); } @Test public void testIndexResponse() throws Exception { BytesStreamOutput out = new BytesStreamOutput(); AnomalyDetector detector = TestHelpers.randomAnomalyDetector(ImmutableMap.of("testKey", "testValue"), Instant.now()); IndexAnomalyDetectorResponse response = new IndexAnomalyDetectorResponse("1234", 56, 78, 90, detector, RestStatus.OK); response.writeTo(out); NamedWriteableAwareStreamInput input = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), writableRegistry()); IndexAnomalyDetectorResponse newResponse = new IndexAnomalyDetectorResponse(input); Assert.assertEquals(response.getId(), newResponse.getId()); XContentBuilder builder = TestHelpers.builder(); Assert.assertNotNull(newResponse.toXContent(builder, ToXContent.EMPTY_PARAMS)); Map<String, Object> map = TestHelpers.XContentBuilderToMap(builder); Assert.assertEquals(map.get(RestHandlerUtils._ID), "1234"); } }
package caf.war.wm_opencaf_showcase.controls.caf_h; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.component.UIComponent; import com.webmethods.caf.faces.annotations.ExpireWithPageFlow; import com.webmethods.caf.faces.bean.search.BaseSearchBarPageBean; import com.webmethods.caf.faces.component.search.SearchBar; import com.webmethods.caf.faces.search.options.ISearchOptionsManager; import com.webmethods.caf.faces.search.options.InMemorySearchOptionsManager; import com.webmethods.caf.faces.search.saved.ISavedSearchProvider; import com.webmethods.caf.faces.search.saved.InMemorySavedSearchProvider; @ManagedBean(name="searchBean") @SessionScoped @ExpireWithPageFlow public class Search extends BaseSearchBarPageBean { private static final long serialVersionUID = -382020462368979368L; @Override public ISavedSearchProvider getSavedSearchProvider() { if (fSavedSearchProvider == null) { //create an in-memory saved search provider for testing // this would be a different implementation in a real scenario fSavedSearchProvider = new InMemorySavedSearchProvider(getSearchQueryFactory()); } return fSavedSearchProvider; } @Override public ISearchOptionsManager getSearchOptionsManager() { if (fSearchOptionsManager == null) { //create an in-memory saved options manager for testing // this would be a different implementation in a real scenario fSearchOptionsManager = new InMemorySearchOptionsManager(); } return fSearchOptionsManager; } @Override public SearchBar getSearchBarControl() { UIComponent component = getFacesContext().getViewRoot().findComponent(":form:searchBar"); if (component instanceof SearchBar) { return (SearchBar)component; } return null; } }
/* * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must 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.oracle.truffle.js.builtins; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Cached.Shared; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.object.DynamicObject; import com.oracle.truffle.api.profiles.BranchProfile; import com.oracle.truffle.api.profiles.ConditionProfile; import com.oracle.truffle.js.builtins.JSONBuiltinsFactory.JSONParseNodeGen; import com.oracle.truffle.js.builtins.JSONBuiltinsFactory.JSONStringifyNodeGen; import com.oracle.truffle.js.builtins.helper.JSONData; import com.oracle.truffle.js.builtins.helper.JSONStringifyStringNode; import com.oracle.truffle.js.builtins.helper.TruffleJSONParser; import com.oracle.truffle.js.nodes.access.CreateDataPropertyNode; import com.oracle.truffle.js.nodes.cast.JSToIntegerAsIntNode; import com.oracle.truffle.js.nodes.cast.JSToNumberNode; import com.oracle.truffle.js.nodes.cast.JSToStringNode; import com.oracle.truffle.js.nodes.function.JSBuiltin; import com.oracle.truffle.js.nodes.function.JSBuiltinNode; import com.oracle.truffle.js.nodes.unary.IsCallableNode; import com.oracle.truffle.js.nodes.unary.JSIsArrayNode; import com.oracle.truffle.js.runtime.JSContext; import com.oracle.truffle.js.runtime.JSRuntime; import com.oracle.truffle.js.runtime.builtins.BuiltinEnum; import com.oracle.truffle.js.runtime.builtins.JSArray; import com.oracle.truffle.js.runtime.builtins.JSNumber; import com.oracle.truffle.js.runtime.builtins.JSString; import com.oracle.truffle.js.runtime.builtins.JSOrdinary; import com.oracle.truffle.js.runtime.objects.JSAttributes; import com.oracle.truffle.js.runtime.objects.JSDynamicObject; import com.oracle.truffle.js.runtime.objects.JSObject; import com.oracle.truffle.js.runtime.objects.JSObjectUtil; import com.oracle.truffle.js.runtime.objects.Undefined; import com.oracle.truffle.js.runtime.util.StringBuilderProfile; /** * Contains builtins for {@linkplain JSON} function (constructor). */ public final class JSONBuiltins extends JSBuiltinsContainer.SwitchEnum<JSONBuiltins.JSON> { public static final JSBuiltinsContainer BUILTINS = new JSONBuiltins(); protected JSONBuiltins() { super(com.oracle.truffle.js.runtime.builtins.JSON.CLASS_NAME, JSON.class); } public enum JSON implements BuiltinEnum<JSON> { parse(2), stringify(3); private final int length; JSON(int length) { this.length = length; } @Override public int getLength() { return length; } } @Override protected Object createNode(JSContext context, JSBuiltin builtin, boolean construct, boolean newTarget, JSON builtinEnum) { switch (builtinEnum) { case parse: return JSONParseNodeGen.create(context, builtin, args().fixedArgs(2).createArgumentNodes(context)); case stringify: return JSONStringifyNodeGen.create(context, builtin, args().fixedArgs(3).createArgumentNodes(context)); } return null; } public abstract static class JSONOperation extends JSBuiltinNode { public JSONOperation(JSContext context, JSBuiltin builtin) { super(context, builtin); } @Child private JSToStringNode toStringNode; protected String toString(Object target) { if (toStringNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); toStringNode = insert(JSToStringNode.create()); } return toStringNode.executeString(target); } protected boolean isArray(Object replacer) { return JSRuntime.isArray(replacer); } } public abstract static class JSONParseNode extends JSONOperation { public JSONParseNode(JSContext context, JSBuiltin builtin) { super(context, builtin); } @Specialization(guards = "isCallable.executeBoolean(reviver)", limit = "1") protected Object parse(Object text, Object reviver, @Cached @Shared("isCallable") @SuppressWarnings("unused") IsCallableNode isCallable) { Object unfiltered = parseIntl(toString(text)); DynamicObject root = JSOrdinary.create(getContext(), getRealm()); JSObjectUtil.putDataProperty(getContext(), root, "", unfiltered, JSAttributes.getDefault()); return walk((DynamicObject) reviver, root, ""); } @Specialization(guards = "!isCallable.executeBoolean(reviver)", limit = "1") protected Object parseUnfiltered(Object text, @SuppressWarnings("unused") Object reviver, @Cached @Shared("isCallable") @SuppressWarnings("unused") IsCallableNode isCallable) { return parseIntl(toString(text)); } @TruffleBoundary(transferToInterpreterOnException = false) private Object parseIntl(String jsonString) { return new TruffleJSONParser(getContext()).parse(jsonString, getRealm()); } @TruffleBoundary private Object walk(DynamicObject reviverFn, DynamicObject holder, String property) { Object value = JSObject.get(holder, property); if (JSRuntime.isObject(value)) { DynamicObject object = (DynamicObject) value; if (isArray(object)) { int len = (int) JSRuntime.toLength(JSObject.get(object, JSArray.LENGTH)); for (int i = 0; i < len; i++) { String stringIndex = String.valueOf(i); Object newElement = walk(reviverFn, object, stringIndex); if (newElement == Undefined.instance) { JSObject.delete(object, i); } else { JSRuntime.createDataProperty(object, stringIndex, newElement); } } } else { for (String p : JSObject.enumerableOwnNames(object)) { Object newElement = walk(reviverFn, object, p); if (newElement == Undefined.instance) { JSObject.delete(object, p); } else { JSRuntime.createDataProperty(object, p, newElement); } } } } return JSRuntime.call(reviverFn, holder, new Object[]{property, value}); } } public abstract static class JSONStringifyNode extends JSONOperation { public JSONStringifyNode(JSContext context, JSBuiltin builtin) { super(context, builtin); } @Child private JSONStringifyStringNode jsonStringifyStringNode; @Child private CreateDataPropertyNode createWrapperPropertyNode; @Child private JSToIntegerAsIntNode toIntegerNode; @Child private JSToNumberNode toNumberNode; @Child private JSIsArrayNode isArrayNode; @Child private IsCallableNode isCallableNode; private final BranchProfile spaceIsStringBranch = BranchProfile.create(); private final ConditionProfile spaceIsUndefinedProfile = ConditionProfile.createBinaryProfile(); protected Object jsonStr(Object jsonData, String key, DynamicObject holder) { if (jsonStringifyStringNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); jsonStringifyStringNode = insert(JSONStringifyStringNode.create(getContext())); } return jsonStringifyStringNode.execute(jsonData, key, holder); } @Override protected boolean isArray(Object replacer) { if (isArrayNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); isArrayNode = insert(JSIsArrayNode.createIsArrayLike()); } return isArrayNode.execute(replacer); } protected boolean isCallable(Object obj) { if (isCallableNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); isCallableNode = insert(IsCallableNode.create()); } return isCallableNode.executeBoolean(obj); } @Specialization(guards = "isCallable(replacerFn)") protected Object stringify(Object value, DynamicObject replacerFn, Object spaceParam) { assert JSRuntime.isCallable(replacerFn); return stringifyIntl(value, spaceParam, replacerFn, null); } @Specialization(guards = "isArray(replacerObj)") protected Object stringifyReplacerArray(Object value, DynamicObject replacerObj, Object spaceParam) { int len = (int) JSRuntime.toLength(JSObject.get(replacerObj, JSArray.LENGTH)); List<String> replacerList = new ArrayList<>(); for (int i = 0; i < len; i++) { // harmony/proxies-json.js requires toString() Object v = JSObject.get(replacerObj, JSRuntime.toString(i)); String item = null; // Let item be undefined. if (JSRuntime.isString(v)) { item = JSRuntime.toStringIsString(v); } else if (JSRuntime.isNumber(v) || JSNumber.isJSNumber(v) || JSString.isJSString(v)) { item = toString(v); } if (item != null) { // If item is not undefined ... addToReplacer(replacerList, item); } } return stringifyIntl(value, spaceParam, null, replacerList); } @TruffleBoundary private static void addToReplacer(List<String> replacerList, String item) { if (!replacerList.contains(item)) { replacerList.add(item); } } @SuppressWarnings("unused") @Specialization(guards = {"isString(value)", "!isCallable(replacer)", "!isArray(replacer)"}) // GR-24628: JSON.stringify is frequently called with (just) a String argument protected Object stringifyAStringNoReplacer(Object value, Object replacer, Object spaceParam, @Cached("createStringBuilderProfile()") StringBuilderProfile stringBuilderProfile) { String str = JSRuntime.toStringIsString(value); StringBuilder builder = new StringBuilder(str.length() + 8); JSONStringifyStringNode.jsonQuote(stringBuilderProfile, builder, str); return stringBuilderProfile.toString(builder); } protected StringBuilderProfile createStringBuilderProfile() { return StringBuilderProfile.create(getContext().getStringLengthLimit()); } @SuppressWarnings("unused") @Specialization(guards = {"!isString(value)", "!isCallable(replacer)", "!isArray(replacer)"}) protected Object stringifyNoReplacer(Object value, Object replacer, Object spaceParam) { return stringifyIntl(value, spaceParam, null, null); } private Object stringifyIntl(Object value, Object spaceParam, DynamicObject replacerFnObj, List<String> replacerList) { final String gap = spaceIsUndefinedProfile.profile(spaceParam == Undefined.instance) ? "" : getGap(spaceParam); DynamicObject wrapper = JSOrdinary.create(getContext(), getRealm()); if (createWrapperPropertyNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); createWrapperPropertyNode = insert(CreateDataPropertyNode.create(getContext(), "")); } createWrapperPropertyNode.executeVoid(wrapper, value); return jsonStr(new JSONData(gap, replacerFnObj, replacerList), "", wrapper); } private String getGap(Object spaceParam) { Object space = spaceParam; if (JSDynamicObject.isJSDynamicObject(space)) { if (JSNumber.isJSNumber(space)) { space = toNumber(space); } else if (JSString.isJSString(space)) { space = toString(space); } } if (JSRuntime.isNumber(space)) { if (toIntegerNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); toIntegerNode = insert(JSToIntegerAsIntNode.create()); } int newSpace = Math.max(0, Math.min(10, toIntegerNode.executeInt(space))); return makeGap(newSpace); } else if (JSRuntime.isString(space)) { spaceIsStringBranch.enter(); return makeGap(JSRuntime.toStringIsString(space)); } else { return ""; } } @TruffleBoundary private static String makeGap(String spaceStr) { if (spaceStr.length() <= 10) { return spaceStr; } else { return spaceStr.substring(0, 10); } } @TruffleBoundary private static String makeGap(int spaceValue) { char[] ar = new char[spaceValue]; Arrays.fill(ar, ' '); return new String(ar); } protected Number toNumber(Object target) { if (toNumberNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); toNumberNode = insert(JSToNumberNode.create()); } return toNumberNode.executeNumber(target); } } }
package benchmark.testdriver; import java.io.*; import java.util.*; public class Query { private int nr; private Object[] parameters; private Integer[] parameterFills; private Byte[] parameterTypes; // Some parameters define additional information that will be stored here private Object[] additionalParameterInfo; private Vector<String> queryStrings; private Byte queryType; private QueryMix queryMix; private String parameterChar; private String[] rowNames;// which rows to look at for validation private static Map<String, Byte> parameterMapping; // Parameter constants public static final byte PRODUCT_PROPERTY_NUMERIC = 1; public static final byte PRODUCT_FEATURE_URI = 2; public static final byte PRODUCT_TYPE_URI = 3; public static final byte CURRENT_DATE = 4; public static final byte WORD_FROM_DICTIONARY1 = 5; public static final byte PRODUCT_URI = 6; public static final byte REVIEW_URI = 7; public static final byte COUNTRY_URI = 8; public static final byte OFFER_URI = 9; public static final byte CONSECUTIVE_MONTH = 10; public static final byte UPDATE_TRANSACTION_DATA = 11; public static final byte PRODUCER_URI = 12; public static final byte PRODUCT_TYPE_RANGE = 13; // Initialize Parameter mappings static { parameterMapping = new HashMap<String, Byte>(); parameterMapping.put("ProductPropertyNumericValue", PRODUCT_PROPERTY_NUMERIC); parameterMapping.put("ProductFeatureURI", PRODUCT_FEATURE_URI); parameterMapping.put("ProductTypeURI", PRODUCT_TYPE_URI); parameterMapping.put("CurrentDate", CURRENT_DATE); parameterMapping.put("Dictionary1", WORD_FROM_DICTIONARY1); parameterMapping.put("ProductURI", PRODUCT_URI); parameterMapping.put("ReviewURI", REVIEW_URI); parameterMapping.put("CountryURI", COUNTRY_URI); parameterMapping.put("OfferURI", OFFER_URI); parameterMapping.put("ConsecutiveMonth", CONSECUTIVE_MONTH); parameterMapping.put("UpdateTransactionData", UPDATE_TRANSACTION_DATA); parameterMapping.put("ProducerURI", PRODUCER_URI); parameterMapping.put("ProductTypeRangeURI", PRODUCT_TYPE_RANGE); } // query type constants public static final byte SELECT_TYPE = 1; public static final byte DESCRIBE_TYPE = 2; public static final byte CONSTRUCT_TYPE = 3; public static final byte UPDATE_TYPE = 4; public Query(String queryString, String parameterDescription, String c) { parameterChar = c; init(queryString, parameterDescription); } public Query(File queryFile, File parameterDescriptionFile, String c) { parameterChar = c; String queryString = ""; String parameterDescriptionString = ""; BufferedReader descriptionReader = null; BufferedReader queryReader = null; try { InputStream queryIn = Query.class.getResourceAsStream("/" + queryFile); queryReader = new BufferedReader(new InputStreamReader(queryIn)); StringBuffer sb = new StringBuffer(); while (true) { String line = queryReader.readLine(); if (line == null) break; else { sb.append(line); sb.append("\n"); } } queryString = sb.toString(); // Now the parameter description InputStream descIn = Query.class.getResourceAsStream("/" + parameterDescriptionFile); descriptionReader = new BufferedReader(new InputStreamReader( descIn)); sb = new StringBuffer(); while (true) { String line = descriptionReader.readLine(); if (line == null) break; else { sb.append(line); sb.append("\n"); } } parameterDescriptionString = sb.toString(); } catch (IOException e) { throw new RuntimeException(e); //System.err.println(e.getMessage()); //System.exit(-1); } finally { try { if (descriptionReader != null) descriptionReader.close(); if (queryReader != null) queryReader.close(); } catch (IOException e) { e.printStackTrace(); } } init(queryString, parameterDescriptionString); } /* * Initialize the Query */ private void init(String queryString, String parameterDescription) { queryStrings = processQueryString(queryString); queryType = SELECT_TYPE;// default: Select query if (queryStrings == null) { System.err.println("Error in Query"); System.exit(-1); } processParameters(queryString, parameterDescription); parameters = new Object[parameterTypes.length]; } /* * Sets the Query Parameter Types and their places in the query, namely the * two arrays parameterFills and parameterTypes */ private void processParameters(String queryString, String parameterDescription) { // parameterType Array Vector<Byte> parameterT = new Vector<Byte>(); Vector<Object> additionalP = new Vector<Object>(); // StringTokenizer for the parameter description String StringTokenizer paramTokenizer = new StringTokenizer( parameterDescription); // Mapping of Parameter names to their array position HashMap<String, Integer> mapping = new HashMap<String, Integer>(); Integer index = 0;// Array index for ParameterTypes // Read Query Description while (paramTokenizer.hasMoreTokens()) { String line = paramTokenizer.nextToken(); // Skip uninteresting lines if (!line.contains("=")) continue; int offset = line.indexOf("="); // Parameter name String parameter = line.substring(0, offset); offset++; // Parameter Type String paramType = line.substring(offset); // If special parameter querytype is given save query type for later // use if (parameter.toLowerCase().equals("querytype")) { byte qType = getQueryType(paramType); if (qType == 0) { System.err.println("Invalid query type chosen." + " Using default: Select"); } else queryType = qType; }// else get Parameter else { String addPI = null; if(paramType.contains("_")) { String[] paramSplit = paramType.split("_", 2); paramType = paramSplit[0]; addPI = paramSplit[1]; } Byte byteType = getParamType(paramType); Object additionParameterInfo = null; if(addPI != null) additionParameterInfo = getAdditionParameterInfo(byteType, addPI); if (byteType == 0) { System.err.println("Unknown Type: " + paramType); System.exit(-1); } mapping.put(parameter, index++); additionalP.add(additionParameterInfo); parameterT.add(byteType); } } parameterTypes = new Byte[parameterT.size()]; additionalParameterInfo = new Object[parameterT.size()]; for (int i = 0; i < parameterT.size(); i++) { parameterTypes[i] = parameterT.elementAt(i); additionalParameterInfo[i] = additionalP.elementAt(i); } // fill parameterFills Vector<Integer> paramFills = new Vector<Integer>(); int index1 = 0; int index2 = -1; while (queryString.indexOf(parameterChar, index2 + 1) != -1) { index1 = queryString.indexOf(parameterChar, index2 + 1); index2 = queryString.indexOf(parameterChar, index1 + 1); String parameter = queryString.substring(index1 + 1, index2); paramFills.add(mapping.get(parameter)); } parameterFills = new Integer[paramFills.size()]; for (int i = 0; i < paramFills.size(); i++) parameterFills[i] = paramFills.elementAt(i); } /* * For some parameter types additional information can be defined */ private Object getAdditionParameterInfo(byte type, String additionalInfo) { Object returnValue = additionalInfo; if(type==Query.CONSECUTIVE_MONTH) { try { returnValue = Integer.parseInt(additionalInfo); } catch(NumberFormatException e) { System.err.println("Illegal parameter for ConsecutiveMonth: " + additionalInfo); System.exit(-1); } } else if(type==Query.PRODUCT_TYPE_RANGE) { try { Integer[] params = new Integer[3]; String[] splitString = additionalInfo.split("_"); if(splitString.length<2 || splitString.length>3) { System.err.println("Illegal parameters for ProductTypeRange: " + additionalInfo); System.exit(-1); } params[0] = Integer.parseInt(splitString[0]); params[1] = Integer.parseInt(splitString[1]); // a "lvleq"-suffix means that each level in the product type hierarchy is chosen equally if(splitString.length==3 && splitString[2].equals("lvleq")) params[2] = 1; else params[2] = 0; returnValue = params; } catch(NumberFormatException e) { System.err.println("Illegal parameters for ProductTypeRange: " + additionalInfo); System.exit(-1); } } return returnValue; } /* * get the byte type representation of this parameter string */ private byte getParamType(String stringType) { Byte param = parameterMapping.get(stringType); if (param != null) return param; else return 0; } /* * get the byte type representation of this query type string */ private byte getQueryType(String stringType) { if (stringType.toLowerCase().equals("select")) return SELECT_TYPE; else if (stringType.toLowerCase().equals("describe")) return DESCRIBE_TYPE; else if (stringType.toLowerCase().equals("construct")) return CONSTRUCT_TYPE; else if (stringType.toLowerCase().equals("update")) return UPDATE_TYPE; else return 0; } /* * Get the Query String components without the parameter Strings */ private Vector<String> processQueryString(String queryString) { Vector<String> queryStrings = new Vector<String>(); int index1 = 0; int index2 = -1; while (queryString.contains(parameterChar)) { index1 = queryString.indexOf(parameterChar, index2 + 1); if (index1 == -1) { index2++; break; } queryStrings.add(queryString.substring(index2 + 1, index1)); index2 = queryString.indexOf(parameterChar, index1 + 1); if (index2 == -1) return null;// Error: Shouldn't happen } if (index2 == -1) index2++; queryStrings.add(queryString.substring(index2)); return queryStrings; } public void setParameters(Object[] param) { if (parameters.length == param.length) parameters = param; else { System.err.println("Invalid parameter count."); System.exit(-1); } } /* * returns a String of the Query with query parameters filled in. */ public String getQueryString() { StringBuilder s = new StringBuilder(); s.append(queryStrings.get(0)); for (int i = 1; i < queryStrings.size(); i++) { s.append(parameters[parameterFills[i - 1]]); s.append(queryStrings.get(i)); } return s.toString(); } public Byte[] getParameterTypes() { return parameterTypes; } public Object getAdditionalParameterInfo(int indexOfParameter) { return additionalParameterInfo[indexOfParameter]; } public int getNr() { return nr; } public void setNr(int nr) { this.nr = nr; } public Byte getQueryType() { return queryType; } public QueryMix getQueryMix() { return queryMix; } public void setQueryMix(QueryMix queryMix) { this.queryMix = queryMix; } public String[] getRowNames() { return rowNames; } public void setRowNames(String rowNames[]) { this.rowNames = rowNames; } }
/* */ package edu.drexel.cis.dragon.config; /* */ /* */ import edu.drexel.cis.dragon.onlinedb.ArticleParser; /* */ import edu.drexel.cis.dragon.onlinedb.BasicCollectionReader; /* */ import edu.drexel.cis.dragon.onlinedb.CollectionReader; /* */ import edu.drexel.cis.dragon.onlinedb.SimpleCollectionReader; /* */ import edu.drexel.cis.dragon.onlinedb.trec.EarlyTrecTopicReader; /* */ import edu.drexel.cis.dragon.onlinedb.trec.Genomics2004TopicReader; /* */ import edu.drexel.cis.dragon.onlinedb.trec.Genomics2005TopicReader; /* */ import edu.drexel.cis.dragon.onlinedb.trec.TrecCollectionReader; /* */ import edu.drexel.cis.dragon.onlinedb.trec.TrecFileReader; /* */ import java.io.File; /* */ import java.io.PrintStream; /* */ /* */ public class CollectionReaderConfig extends ConfigUtil /* */ { /* */ public CollectionReaderConfig() /* */ { /* */ } /* */ /* */ public CollectionReaderConfig(ConfigureNode root) /* */ { /* 22 */ super(root); /* */ } /* */ /* */ public CollectionReaderConfig(String configFile) { /* 26 */ super(configFile); /* */ } /* */ /* */ public CollectionReader getCollectionReader(int collectionID) { /* 30 */ return loadCollectionReader(this.root, collectionID); /* */ } /* */ /* */ public CollectionReader getCollectionReader(ConfigureNode node, int extractorID) { /* 34 */ return loadCollectionReader(node, extractorID); /* */ } /* */ /* */ private CollectionReader loadCollectionReader(ConfigureNode node, int extractorID) /* */ { /* 41 */ ConfigureNode extractorNode = getConfigureNode(node, "collectionreader", extractorID); /* 42 */ if (extractorNode == null) /* 43 */ return null; /* 44 */ String extractorName = extractorNode.getNodeName(); /* 45 */ return loadCollectionReader(extractorName, extractorNode); /* */ } /* */ /* */ protected CollectionReader loadCollectionReader(String collectionName, ConfigureNode collectionNode) { /* 49 */ if (collectionName.equalsIgnoreCase("BasicCollectionReader")) /* 50 */ return loadBasicCollectionReader(collectionNode); /* 51 */ if (collectionName.equalsIgnoreCase("SimpleCollectionReader")) /* 52 */ return loadSimpleCollectionReader(collectionNode); /* 53 */ if (collectionName.equalsIgnoreCase("TrecCollectionReader")) /* 54 */ return loadTrecCollectionReader(collectionNode); /* 55 */ if (collectionName.equalsIgnoreCase("TrecFileReader")) /* 56 */ return loadTrecFileReader(collectionNode); /* 57 */ if (collectionName.equalsIgnoreCase("EarlyTrecTopicReader")) /* 58 */ return new EarlyTrecTopicReader(collectionNode.getString("topicfile")); /* 59 */ if (collectionName.equalsIgnoreCase("Genomics2005TopicReader")) /* 60 */ return new Genomics2005TopicReader(collectionNode.getString("topicfile")); /* 61 */ if (collectionName.equalsIgnoreCase("Genomics2004TopicReader")) { /* 62 */ return new Genomics2004TopicReader(collectionNode.getString("topicfile")); /* */ } /* 64 */ return (CollectionReader)loadResource(collectionNode); /* */ } /* */ /* */ private CollectionReader loadBasicCollectionReader(ConfigureNode curNode) /* */ { /* */ try /* */ { /* 74 */ String collectionPath = curNode.getString("collectionpath"); /* 75 */ String collectionName = curNode.getString("collectionname"); /* 76 */ String collectionFile = curNode.getString("collectionfile"); /* 77 */ String indexFile = curNode.getString("indexfile"); /* 78 */ String articleParser = curNode.getString("articleparser", "dragon.onlinedb.BasicArticleParser"); /* */ CollectionReader reader; /* 79 */ if (collectionFile == null) { /* 80 */ collectionFile = collectionPath + "/" + collectionName + ".collection"; /* 81 */ indexFile = collectionPath + "/" + collectionName + ".index"; /* 82 */ reader = new BasicCollectionReader(collectionFile, indexFile); /* */ } /* */ else { /* 85 */ reader = new BasicCollectionReader(collectionFile, indexFile); /* 86 */ }ArticleParser parser = getArticleParser(articleParser); /* 87 */ if (parser == null) { /* 88 */ System.out.println("Can not load the article parser."); /* 89 */ return null; /* */ } /* 91 */ reader.setArticleParser(parser); /* 92 */ return reader; /* */ } /* */ catch (Exception e) { /* 95 */ e.printStackTrace(); /* 96 */ }return null; /* */ } /* */ /* */ private CollectionReader loadSimpleCollectionReader(ConfigureNode curNode) /* */ { /* */ try /* */ { /* 107 */ String collectionPath = curNode.getString("collectionpath", null); /* 108 */ String articleParser = curNode.getString("articleparser", "dragon.onlinedb.SimpleArticleParser"); /* 109 */ ArticleParser parser = getArticleParser(articleParser); /* 110 */ if (parser == null) { /* 111 */ System.out.println("Can not load the article parser."); /* 112 */ return null; /* */ } /* */ CollectionReader reader; /* 115 */ if (collectionPath == null) { /* 116 */ reader = new SimpleCollectionReader(parser); /* */ } /* 118 */ return new SimpleCollectionReader(collectionPath, parser); /* */ } /* */ catch (Exception e) /* */ { /* 122 */ e.printStackTrace(); /* 123 */ }return null; /* */ } /* */ /* */ private CollectionReader loadTrecCollectionReader(ConfigureNode curNode) /* */ { /* */ try /* */ { /* 134 */ String articleRoot = curNode.getString("articleroot", "DOC"); /* 135 */ String collectionPath = curNode.getString("collectionpath", null); /* 136 */ String indexFile = curNode.getString("indexfile", null); /* 137 */ String articleParser = curNode.getString("articleparser", "dragon.onlinedb.BasicArticleParser"); /* 138 */ ArticleParser parser = getArticleParser(articleParser); /* 139 */ if (parser == null) { /* 140 */ System.out.println("Can not load the article parser."); /* 141 */ return null; /* */ } /* */ CollectionReader reader; /* 143 */ if ((collectionPath == null) && (indexFile == null)) { /* 144 */ reader = new TrecCollectionReader(parser, articleRoot); /* */ } /* */ else /* */ { /* 145 */ if (indexFile == null) /* 146 */ reader = new TrecCollectionReader(collectionPath, parser, articleRoot); /* */ } /* 148 */ return new TrecCollectionReader(collectionPath, indexFile, parser, articleRoot); /* */ } /* */ catch (Exception e) /* */ { /* 152 */ e.printStackTrace(); /* 153 */ }return null; /* */ } /* */ /* */ private CollectionReader loadTrecFileReader(ConfigureNode curNode) /* */ { /* */ try /* */ { /* 164 */ String articleRoot = curNode.getString("articleroot", "DOC"); /* 165 */ String filename = curNode.getString("filename", null); /* 166 */ String articleParser = curNode.getString("articleparser", "dragon.onlinedb.BasicArticleParser"); /* 167 */ ArticleParser parser = getArticleParser(articleParser); /* 168 */ if (parser == null) { /* 169 */ System.out.println("Can not load the article parser."); /* 170 */ return null; /* */ } /* */ CollectionReader reader; /* 172 */ if (filename == null) { /* 173 */ reader = new TrecFileReader(parser, articleRoot); /* */ } /* 175 */ return new TrecFileReader(new File(filename), parser, articleRoot); /* */ } /* */ catch (Exception e) /* */ { /* 179 */ e.printStackTrace(); /* 180 */ }return null; /* */ } /* */ /* */ protected ArticleParser getArticleParser(String className) /* */ { /* */ try /* */ { /* 189 */ Class myClass = Class.forName(className); /* 190 */ return (ArticleParser)myClass.newInstance(); /* */ } /* */ catch (Exception e) { /* 193 */ e.printStackTrace(); /* 194 */ }return null; /* */ } /* */ } /* Location: C:\dragontoolikt\dragontool.jar * Qualified Name: dragon.config.CollectionReaderConfig * JD-Core Version: 0.6.2 */
/* * This file is part of Discord4J. * * Discord4J is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Discord4J is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Discord4J. If not, see <http://www.gnu.org/licenses/>. */ package discord4j.command; import discord4j.command.util.CommandException; import discord4j.core.event.domain.message.MessageCreateEvent; import reactor.core.publisher.Mono; /** * An interface called when an error is encountered. * * @see CommandException */ @FunctionalInterface public interface CommandErrorHandler { /** * Called when an error is encountered. * * @param event The event of where this error occurred. * @param error The error encountered. It should be noted that this throwable will be a subclass of * {@link CommandException} if an error was due to end-user error, and not an internal issue. As * a result it will usually contain a user-friendly message which can simply be reported to the author of the * message attempting to invoke a command. */ Mono<Void> handle(MessageCreateEvent event, Throwable error); }
/* * Copyright (C) 2008 FoxLabs * * 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.foxlabs.etk.support; import java.util.List; import java.util.Map; public abstract class Indexer extends Operator { Indexer() {} public abstract Class<?> getType(); public abstract Object lookup(Object collection, Object key); public static final Indexer getInstance(Class<?> collectionType, Class<?> keyType) { if (collectionType == null || keyType == null) return null; if (Map.class.isAssignableFrom(collectionType)) return MapIndexer.singleInstance; if (keyType == Integer.class) { if (collectionType.isArray()) return new ArrayIndexer(collectionType.getComponentType()); if (List.class.isAssignableFrom(collectionType)) return ListIndexer.singleInstance; if (collectionType == String.class) return StringIndexer.singleInstance; } return null; } public static final Class<?> getKeyType(Class<?> collectionType) { if (collectionType == null) return null; if (collectionType.isArray() || String.class.isAssignableFrom(collectionType) || List.class.isAssignableFrom(collectionType)) return Integer.class; if (Map.class.isAssignableFrom(collectionType)) return Object.class; return null; } } final class ArrayIndexer extends Indexer { private final Class<?> type; ArrayIndexer(Class<?> type) { this.type = type; } public Class<?> getType() { return type; } public Object lookup(Object array, Object index) { Object[] c = safeValueOf((Object[]) array); return c[safeIndexOf((Integer) index, c.length)]; } } final class ListIndexer extends Indexer { static final Indexer singleInstance = new ListIndexer(); private ListIndexer() {} public Class<?> getType() { return Object.class; } public Object lookup(Object list, Object index) { List<?> c = safeValueOf((List<?>) list); return c.get(safeIndexOf((Integer) index, c.size())); } } final class MapIndexer extends Indexer { static final Indexer singleInstance = new MapIndexer(); private MapIndexer() {} public Class<?> getType() { return Object.class; } public Object lookup(Object map, Object key) { return safeValueOf((Map<?, ?>) map).get(key); } } final class StringIndexer extends Indexer { static final Indexer singleInstance = new StringIndexer(); private StringIndexer() {} public Class<?> getType() { return Character.class; } public Object lookup(Object string, Object index) { String c = safeValueOf((String) string); return c.charAt(safeIndexOf((Integer) index, c.length())); } }
package io.codejournal.codingbat.string1; import java.util.Optional; public class Left2 { public final String left2(final String str) { final String returnStr = Optional.ofNullable(str).orElse(""); if (returnStr.length() <= 2) { return returnStr; } return returnStr.substring(2) + returnStr.substring(0, 2); } }
/* * Copyright © 2022 Cask 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 io.cdap.cdap.common.leveldb; import org.iq80.leveldb.impl.InternalKey; import org.iq80.leveldb.util.Slice; import javax.annotation.Nullable; /** * Utility class for trimming down storage of keys passed to {@link org.iq80.leveldb.impl.FileMetaData#FileMetaData} */ public final class FileMetaDataUtil { private FileMetaDataUtil() { } /** * Check if value holds a reference to a big array (more than needed to store a key) and create a copy of the key * with minimum storage needed if so. * @param value original key to be analyzed * @return original key of it uses minimum storage, copy of the key if storage had to be trimmed, * null if input is null */ @Nullable public static InternalKey normalize(@Nullable InternalKey value) { if (value == null) { return null; } Slice userKey = value.getUserKey(); if (userKey.getRawArray().length <= userKey.length()) { return value; } return new InternalKey(value.getUserKey().copySlice(), value.getSequenceNumber(), value.getValueType()); } }
package org.springframeword.test.demo.test.impl; import org.springframeword.test.demo.test.TestAaaaService; import org.springframeword.test.demo.test.TestBbbbbService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author zhangwangfa * @DATE 2021/9/15 14:26 */ @Service public class TestBbbbbServiceImpl implements TestBbbbbService { @Autowired private TestAaaaService testAaaaService; private static Integer a= 1; @Override public void bbbbb() { System.out.println("this is TestBbbbbServiceImpl for bbbbb() "); if(a<2) { a++; testAaaaService.aaa(); } } public TestBbbbbServiceImpl(){ System.out.println("this is TestBbbbbServiceImpl for Construct"); } }
package com.chinalwb.are.styles; import android.graphics.Typeface; import android.text.Editable; import android.text.Spanned; import android.text.style.StyleSpan; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import com.chinalwb.are.AREditText; import com.chinalwb.are.Util; import com.chinalwb.are.spans.AreItalicSpan; public class ARE_Italic extends ARE_ABS_Style<AreItalicSpan> { private ImageView mItalicImageView; private boolean mItalicChecked; private AREditText mEditText; /** * * @param italicImage */ public ARE_Italic(ImageView italicImage) { this.mItalicImageView = italicImage; setListenerForImageView(this.mItalicImageView); } /** * * @param editText */ public void setEditText(AREditText editText) { this.mEditText = editText; } @Override public void setListenerForImageView(final ImageView imageView) { imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mItalicChecked = !mItalicChecked; ARE_Helper.updateCheckStatus(ARE_Italic.this, mItalicChecked); if (null != mEditText) { applyStyle(mEditText.getEditableText(), mEditText.getSelectionStart(), mEditText.getSelectionEnd()); } } }); } @Override public ImageView getImageView() { return this.mItalicImageView; } @Override public void setChecked(boolean isChecked) { this.mItalicChecked = isChecked; } @Override public boolean getIsChecked() { return this.mItalicChecked; } @Override public AreItalicSpan newSpan() { return new AreItalicSpan(); } }
package br.com.everis.projetobeca.locadora.repository; import br.com.everis.projetobeca.locadora.model.Cliente; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ClienteRepository extends JpaRepository<Cliente, Long> { }
package org.psutil4j.common.enums; import java.util.HashMap; import java.util.Map; /** * @author zhangguohao */ public enum State { /** * process state */ RUNNING(0, "running"), SLEEPING(1, "sleeping"), DISK_SLEEP(2, "disk-sleep"), STOPPED(3, "stopped"), TRACING_STOP(4, "tracing-stop"), ZOMBIE(5, "zombie"), DEAD(6, "dead"), WAKE_KILL(7, "wake-kill"), WAKING(8, "waking"), // Linux, macOS, FreeBSD IDLE(9, "idle"), // FreeBSD LOCKED(10, "locked"), WAITING(11, "waiting"), // NetBSD SUSPENDED(12, "suspended"), // Linux PARKED(13, "parked"), OTHER(14, "OTHER"), ; State(int code, String state) { this.code = code; this.state = state; } private final int code; private final String state; public int getCode() { return code; } public String getState() { return state; } private static final Map<Integer, State> STATE_MAP = new HashMap<>(); static { for (State state : State.values()) { STATE_MAP.put(state.code, state); } } public static State of(Integer code) { if (STATE_MAP.containsKey(code)) { return STATE_MAP.get(code); } throw new IllegalArgumentException("invalid code : " + code); } }
/* * Copyright (c) 2017 Antony Esik * * 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.ae.camunda.dispatcher.processor; import com.ae.camunda.dispatcher.api.annotation.CamundaTask; import com.ae.camunda.dispatcher.api.mapper.TaskMapper; import com.ae.camunda.dispatcher.api.processor.TaskProcessor; import com.ae.camunda.dispatcher.api.processor.TaskProcessorRegistry; import com.ae.camunda.dispatcher.util.JavaUtils; import com.google.common.base.Strings; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.lang.reflect.ParameterizedType; import java.util.List; import java.util.stream.Stream; @Component public class TaskProcessorRegistryImpl implements TaskProcessorRegistry { private static final Logger LOG = LoggerFactory.getLogger(TaskProcessorRegistryImpl.class); @Autowired private TaskMapper taskMapper; @Autowired private List<TaskProcessor> taskProcessors; private Multimap<String, Pair<Class<?>, TaskProcessor>> taskProcessorMap; @PostConstruct public void init() { ImmutableListMultimap.Builder<String, Pair<Class<?>, TaskProcessor>> builder = ImmutableListMultimap.builder(); taskProcessors.forEach(processor -> Stream.of(processor.getClass().getGenericInterfaces()) .filter(ParameterizedType.class::isInstance) .map(ParameterizedType.class::cast) .filter(iface -> iface.getRawType() != null && TaskProcessor.class.getName().equals(iface.getRawType().getTypeName())) .map(iface -> iface.getActualTypeArguments()[0].getTypeName()) .findFirst() .ifPresent(taskClassName -> { Class<?> taskClass = JavaUtils.callWithoutCheckedException(() -> Class.forName(taskClassName)); CamundaTask camundaTask = taskClass.getAnnotation(CamundaTask.class); if (camundaTask == null) { LOG.warn("Task processor [{}] processes task class [{}] without annotation [{}]" , processor.getClass().getName(), taskClassName, CamundaTask.class.getName()); return; } String taskName = camundaTask.value(); if (Strings.isNullOrEmpty(taskName)) { taskName = taskClass.getName(); } LOG.debug("Register processor [{}] for task [{}]", processor.getClass().getName(), taskName); builder.put(taskName, Pair.of(taskClass, processor)); }) ); taskProcessorMap = builder.build(); } @Override public void process(String taskName, String taskBody) { if (!taskProcessorMap.containsKey(taskName)) { LOG.warn("No processor bound to task: {}", taskName); return; } taskProcessorMap.get(taskName).forEach(pair -> { Object command = taskMapper.map(taskBody, pair.getKey()); LOG.debug("Recv command: {}", command); pair.getValue().process(command); }); } public Multimap<String, Pair<Class<?>, TaskProcessor>> getTaskProcessorMap() { return Multimaps.unmodifiableMultimap(taskProcessorMap); } }
/* * 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.zto.zms.collector.model; import com.google.common.collect.Lists; import java.util.List; public class ConsumerInfo { private long latency; private double tps; private long lastConsumingTime; private List<String> consumers = Lists.newArrayList(); public ConsumerInfo(long latency, double tps) { this.latency = latency; this.tps = tps; } public void add(long latency, double tps) { this.tps = this.tps + tps; this.latency = this.latency + latency; } public long getLatency() { return latency; } public void setLatency(long latency) { this.latency = latency; } public double getTps() { return tps; } public void setTps(double tps) { this.tps = tps; } public List<String> getConsumers() { return consumers; } public void setConsumers(List<String> consumers) { this.consumers = consumers; } public long getLastConsumingTime() { return lastConsumingTime; } public void setLastConsumingTime(long lastConsumingTime) { this.lastConsumingTime = lastConsumingTime; } public void updateLastConsumingTime(long lastConsumingTime) { if (this.lastConsumingTime < lastConsumingTime) { this.lastConsumingTime = lastConsumingTime; } } }
/* * 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. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: http://www.jooq.org/licenses * * * * * * * * * * * * * * * * */ package org.jooq.impl; import static org.jooq.impl.DSL.row; import static org.jooq.impl.DSL.val; import java.util.Arrays; import java.util.Collection; import org.jooq.BetweenAndStep12; import org.jooq.Comparator; import org.jooq.Condition; import org.jooq.DataType; import org.jooq.Field; import org.jooq.QuantifiedSelect; import org.jooq.Record; import org.jooq.Record12; import org.jooq.Row; import org.jooq.Row12; import org.jooq.Result; import org.jooq.Select; /** * @author Lukas Eder */ final class RowImpl12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> extends AbstractRow implements Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> { /** * Generated UID */ private static final long serialVersionUID = -929427349071556318L; RowImpl12(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { super(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } // ------------------------------------------------------------------------ // XXX: Row accessor API // ------------------------------------------------------------------------ @Override public final Field<T1> field1() { return (Field<T1>) fields.field(0); } @Override public final Field<T2> field2() { return (Field<T2>) fields.field(1); } @Override public final Field<T3> field3() { return (Field<T3>) fields.field(2); } @Override public final Field<T4> field4() { return (Field<T4>) fields.field(3); } @Override public final Field<T5> field5() { return (Field<T5>) fields.field(4); } @Override public final Field<T6> field6() { return (Field<T6>) fields.field(5); } @Override public final Field<T7> field7() { return (Field<T7>) fields.field(6); } @Override public final Field<T8> field8() { return (Field<T8>) fields.field(7); } @Override public final Field<T9> field9() { return (Field<T9>) fields.field(8); } @Override public final Field<T10> field10() { return (Field<T10>) fields.field(9); } @Override public final Field<T11> field11() { return (Field<T11>) fields.field(10); } @Override public final Field<T12> field12() { return (Field<T12>) fields.field(11); } // ------------------------------------------------------------------------ // Generic comparison predicates // ------------------------------------------------------------------------ @Override public final Condition compare(Comparator comparator, Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return new RowCondition(this, row, comparator); } @Override public final Condition compare(Comparator comparator, Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return new RowCondition(this, record.valuesRow(), comparator); } @Override public final Condition compare(Comparator comparator, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return compare(comparator, row(val(t1, (DataType<T1>) dataType(0)), val(t2, (DataType<T2>) dataType(1)), val(t3, (DataType<T3>) dataType(2)), val(t4, (DataType<T4>) dataType(3)), val(t5, (DataType<T5>) dataType(4)), val(t6, (DataType<T6>) dataType(5)), val(t7, (DataType<T7>) dataType(6)), val(t8, (DataType<T8>) dataType(7)), val(t9, (DataType<T9>) dataType(8)), val(t10, (DataType<T10>) dataType(9)), val(t11, (DataType<T11>) dataType(10)), val(t12, (DataType<T12>) dataType(11)))); } @Override public final Condition compare(Comparator comparator, Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return compare(comparator, row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } @Override public final Condition compare(Comparator comparator, Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return new RowSubqueryCondition(this, select, comparator); } @Override public final Condition compare(Comparator comparator, QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return new RowSubqueryCondition(this, select, comparator); } // ------------------------------------------------------------------------ // Equal / Not equal comparison predicates // ------------------------------------------------------------------------ @Override public final Condition equal(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return compare(Comparator.EQUALS, row); } @Override public final Condition equal(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return compare(Comparator.EQUALS, record); } @Override public final Condition equal(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return compare(Comparator.EQUALS, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition equal(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return compare(Comparator.EQUALS, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition eq(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return equal(row); } @Override public final Condition eq(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return equal(record); } @Override public final Condition eq(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return equal(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition eq(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return equal(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition notEqual(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return compare(Comparator.NOT_EQUALS, row); } @Override public final Condition notEqual(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return compare(Comparator.NOT_EQUALS, record); } @Override public final Condition notEqual(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return compare(Comparator.NOT_EQUALS, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition notEqual(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return compare(Comparator.NOT_EQUALS, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition ne(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return notEqual(row); } @Override public final Condition ne(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return notEqual(record); } @Override public final Condition ne(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return notEqual(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition ne(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return notEqual(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } // ------------------------------------------------------------------------ // Ordering comparison predicates // ------------------------------------------------------------------------ @Override public final Condition lessThan(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return compare(Comparator.LESS, row); } @Override public final Condition lessThan(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return compare(Comparator.LESS, record); } @Override public final Condition lessThan(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return compare(Comparator.LESS, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition lessThan(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return compare(Comparator.LESS, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition lt(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return lessThan(row); } @Override public final Condition lt(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return lessThan(record); } @Override public final Condition lt(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return lessThan(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition lt(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return lessThan(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition lessOrEqual(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return compare(Comparator.LESS_OR_EQUAL, row); } @Override public final Condition lessOrEqual(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return compare(Comparator.LESS_OR_EQUAL, record); } @Override public final Condition lessOrEqual(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return compare(Comparator.LESS_OR_EQUAL, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition lessOrEqual(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return compare(Comparator.LESS_OR_EQUAL, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition le(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return lessOrEqual(row); } @Override public final Condition le(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return lessOrEqual(record); } @Override public final Condition le(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return lessOrEqual(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition le(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return lessOrEqual(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition greaterThan(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return compare(Comparator.GREATER, row); } @Override public final Condition greaterThan(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return compare(Comparator.GREATER, record); } @Override public final Condition greaterThan(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return compare(Comparator.GREATER, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition greaterThan(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return compare(Comparator.GREATER, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition gt(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return greaterThan(row); } @Override public final Condition gt(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return greaterThan(record); } @Override public final Condition gt(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return greaterThan(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition gt(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return greaterThan(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition greaterOrEqual(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return compare(Comparator.GREATER_OR_EQUAL, row); } @Override public final Condition greaterOrEqual(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return compare(Comparator.GREATER_OR_EQUAL, record); } @Override public final Condition greaterOrEqual(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return compare(Comparator.GREATER_OR_EQUAL, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition greaterOrEqual(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return compare(Comparator.GREATER_OR_EQUAL, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition ge(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return greaterOrEqual(row); } @Override public final Condition ge(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return greaterOrEqual(record); } @Override public final Condition ge(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return greaterOrEqual(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } @Override public final Condition ge(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return greaterOrEqual(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12); } // ------------------------------------------------------------------------ // [NOT] BETWEEN predicates // ------------------------------------------------------------------------ @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> between(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return between(row(val(t1, (DataType) dataType(0)), val(t2, (DataType) dataType(1)), val(t3, (DataType) dataType(2)), val(t4, (DataType) dataType(3)), val(t5, (DataType) dataType(4)), val(t6, (DataType) dataType(5)), val(t7, (DataType) dataType(6)), val(t8, (DataType) dataType(7)), val(t9, (DataType) dataType(8)), val(t10, (DataType) dataType(9)), val(t11, (DataType) dataType(10)), val(t12, (DataType) dataType(11)))); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> between(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return between(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> between(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return new RowBetweenCondition<>(this, row, false, false); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> between(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return between(record.valuesRow()); } @Override public final Condition between(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> minValue, Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> maxValue) { return between(minValue).and(maxValue); } @Override public final Condition between(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> minValue, Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> maxValue) { return between(minValue).and(maxValue); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> betweenSymmetric(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return betweenSymmetric(row(val(t1, (DataType) dataType(0)), val(t2, (DataType) dataType(1)), val(t3, (DataType) dataType(2)), val(t4, (DataType) dataType(3)), val(t5, (DataType) dataType(4)), val(t6, (DataType) dataType(5)), val(t7, (DataType) dataType(6)), val(t8, (DataType) dataType(7)), val(t9, (DataType) dataType(8)), val(t10, (DataType) dataType(9)), val(t11, (DataType) dataType(10)), val(t12, (DataType) dataType(11)))); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> betweenSymmetric(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return betweenSymmetric(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> betweenSymmetric(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return new RowBetweenCondition<>(this, row, false, true); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> betweenSymmetric(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return betweenSymmetric(record.valuesRow()); } @Override public final Condition betweenSymmetric(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> minValue, Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> maxValue) { return betweenSymmetric(minValue).and(maxValue); } @Override public final Condition betweenSymmetric(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> minValue, Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> maxValue) { return betweenSymmetric(minValue).and(maxValue); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> notBetween(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return notBetween(row(val(t1, (DataType) dataType(0)), val(t2, (DataType) dataType(1)), val(t3, (DataType) dataType(2)), val(t4, (DataType) dataType(3)), val(t5, (DataType) dataType(4)), val(t6, (DataType) dataType(5)), val(t7, (DataType) dataType(6)), val(t8, (DataType) dataType(7)), val(t9, (DataType) dataType(8)), val(t10, (DataType) dataType(9)), val(t11, (DataType) dataType(10)), val(t12, (DataType) dataType(11)))); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> notBetween(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return notBetween(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> notBetween(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return new RowBetweenCondition<>(this, row, true, false); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> notBetween(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return notBetween(record.valuesRow()); } @Override public final Condition notBetween(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> minValue, Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> maxValue) { return notBetween(minValue).and(maxValue); } @Override public final Condition notBetween(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> minValue, Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> maxValue) { return notBetween(minValue).and(maxValue); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> notBetweenSymmetric(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return notBetweenSymmetric(row(val(t1, (DataType) dataType(0)), val(t2, (DataType) dataType(1)), val(t3, (DataType) dataType(2)), val(t4, (DataType) dataType(3)), val(t5, (DataType) dataType(4)), val(t6, (DataType) dataType(5)), val(t7, (DataType) dataType(6)), val(t8, (DataType) dataType(7)), val(t9, (DataType) dataType(8)), val(t10, (DataType) dataType(9)), val(t11, (DataType) dataType(10)), val(t12, (DataType) dataType(11)))); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> notBetweenSymmetric(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return notBetweenSymmetric(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> notBetweenSymmetric(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return new RowBetweenCondition<>(this, row, true, true); } @Override public final BetweenAndStep12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> notBetweenSymmetric(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return notBetweenSymmetric(record.valuesRow()); } @Override public final Condition notBetweenSymmetric(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> minValue, Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> maxValue) { return notBetweenSymmetric(minValue).and(maxValue); } @Override public final Condition notBetweenSymmetric(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> minValue, Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> maxValue) { return notBetweenSymmetric(minValue).and(maxValue); } // ------------------------------------------------------------------------ // [NOT] DISTINCT predicates // ------------------------------------------------------------------------ @Override public final Condition isNotDistinctFrom(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return new RowIsDistinctFrom(this, row, true); } @Override public final Condition isNotDistinctFrom(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return isNotDistinctFrom(record.valuesRow()); } @Override public final Condition isNotDistinctFrom(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return isNotDistinctFrom(val(t1, (DataType<T1>) dataType(0)), val(t2, (DataType<T2>) dataType(1)), val(t3, (DataType<T3>) dataType(2)), val(t4, (DataType<T4>) dataType(3)), val(t5, (DataType<T5>) dataType(4)), val(t6, (DataType<T6>) dataType(5)), val(t7, (DataType<T7>) dataType(6)), val(t8, (DataType<T8>) dataType(7)), val(t9, (DataType<T9>) dataType(8)), val(t10, (DataType<T10>) dataType(9)), val(t11, (DataType<T11>) dataType(10)), val(t12, (DataType<T12>) dataType(11))); } @Override public final Condition isNotDistinctFrom(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return isNotDistinctFrom(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } @Override public final Condition isDistinctFrom(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> row) { return new RowIsDistinctFrom(this, row, false); } @Override public final Condition isDistinctFrom(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> record) { return isDistinctFrom(record.valuesRow()); } @Override public final Condition isDistinctFrom(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) { return isDistinctFrom(val(t1, (DataType<T1>) dataType(0)), val(t2, (DataType<T2>) dataType(1)), val(t3, (DataType<T3>) dataType(2)), val(t4, (DataType<T4>) dataType(3)), val(t5, (DataType<T5>) dataType(4)), val(t6, (DataType<T6>) dataType(5)), val(t7, (DataType<T7>) dataType(6)), val(t8, (DataType<T8>) dataType(7)), val(t9, (DataType<T9>) dataType(8)), val(t10, (DataType<T10>) dataType(9)), val(t11, (DataType<T11>) dataType(10)), val(t12, (DataType<T12>) dataType(11))); } @Override public final Condition isDistinctFrom(Field<T1> t1, Field<T2> t2, Field<T3> t3, Field<T4> t4, Field<T5> t5, Field<T6> t6, Field<T7> t7, Field<T8> t8, Field<T9> t9, Field<T10> t10, Field<T11> t11, Field<T12> t12) { return isDistinctFrom(row(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12)); } // ------------------------------------------------------------------------ // [NOT] IN predicates // ------------------------------------------------------------------------ @Override public final Condition in(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>... rows) { return in(Arrays.asList(rows)); } @Override public final Condition in(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>... records) { QueryPartList<Row> rows = new QueryPartList<>(); for (Record record : records) rows.add(record.valuesRow()); return new RowInCondition(this, rows, false); } @Override public final Condition notIn(Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>... rows) { return notIn(Arrays.asList(rows)); } @Override public final Condition notIn(Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>... records) { QueryPartList<Row> rows = new QueryPartList<>(); for (Record record : records) rows.add(record.valuesRow()); return new RowInCondition(this, rows, true); } @Override public final Condition in(Collection<? extends Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> rows) { return new RowInCondition(this, new QueryPartList<Row>(rows), false); } @Override public final Condition in(Result<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> result) { return new RowInCondition(this, new QueryPartList<Row>(Tools.rows(result)), false); } @Override public final Condition notIn(Collection<? extends Row12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> rows) { return new RowInCondition(this, new QueryPartList<Row>(rows), true); } @Override public final Condition notIn(Result<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> result) { return new RowInCondition(this, new QueryPartList<Row>(Tools.rows(result)), true); } // ------------------------------------------------------------------------ // Predicates involving subqueries // ------------------------------------------------------------------------ @Override public final Condition equal(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.EQUALS, select); } @Override public final Condition equal(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.EQUALS, select); } @Override public final Condition eq(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return equal(select); } @Override public final Condition eq(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return equal(select); } @Override public final Condition notEqual(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.NOT_EQUALS, select); } @Override public final Condition notEqual(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.NOT_EQUALS, select); } @Override public final Condition ne(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return notEqual(select); } @Override public final Condition ne(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return notEqual(select); } @Override public final Condition greaterThan(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.GREATER, select); } @Override public final Condition greaterThan(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.GREATER, select); } @Override public final Condition gt(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return greaterThan(select); } @Override public final Condition gt(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return greaterThan(select); } @Override public final Condition greaterOrEqual(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.GREATER_OR_EQUAL, select); } @Override public final Condition greaterOrEqual(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.GREATER_OR_EQUAL, select); } @Override public final Condition ge(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return greaterOrEqual(select); } @Override public final Condition ge(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return greaterOrEqual(select); } @Override public final Condition lessThan(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.LESS, select); } @Override public final Condition lessThan(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.LESS, select); } @Override public final Condition lt(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return lessThan(select); } @Override public final Condition lt(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return lessThan(select); } @Override public final Condition lessOrEqual(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.LESS_OR_EQUAL, select); } @Override public final Condition lessOrEqual(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.LESS_OR_EQUAL, select); } @Override public final Condition le(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return lessOrEqual(select); } @Override public final Condition le(QuantifiedSelect<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return lessOrEqual(select); } @Override public final Condition in(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.IN, select); } @Override public final Condition notIn(Select<? extends Record12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> select) { return compare(Comparator.NOT_IN, select); } }
package depth.first.search; class Node{ int label; /*vertex label*/ Node next; /* next node in list*/ Node(int b){ label = b; //constructor } } class Graph{ int size; Node adjList[]; int mark[]; Graph(int n){//constructur size = n; adjList = new Node[size]; mark = new int[size]; //elements of mark are initialized to 0 } public void createAdjList(int a[][]){//create adjacent lists Node p; int i,k; for(i = 0; i < size; i++){ p = adjList[i] = new Node(i); //create first node of ith adj. list for(k = 0; k < size; k++ ){ if (a[i][k] == 1){ p.next = new Node(k); /** create next node of ith adj. List*/ } } } } public void dfs(int head){ // recursive depth-first search Node w; int v; mark[head] = 1; System.out.print(head + " "); w=adjList[head]; while( w != null){ v = w.label; if(mark[v] == 0) dfs(v); w = w.next; } } } public class DepthFirstSearch { public static void main(String[] args) { Graph g= new Graph(5); // graph is created with 5 nodes int a[][] = {{0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1}, {1,1,1,0,0}, {1,0,1,0,0}}; g.createAdjList(a); g.dfs(0); //starting node to dfs is0(i.e,.A) } }
/*L * Copyright Georgetown University, Washington University. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cab2b/LICENSE.txt for details. */ package edu.wustl.cab2b.server.util; import static edu.wustl.cab2b.common.util.Constants.TYPE_DERIVED; import java.util.ArrayList; import java.util.List; import edu.common.dynamicextensions.domain.DomainObjectFactory; import edu.common.dynamicextensions.domaininterface.AbstractMetadataInterface; import edu.common.dynamicextensions.domaininterface.AssociationInterface; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.EntityGroupInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.common.dynamicextensions.domaininterface.RoleInterface; import edu.common.dynamicextensions.domaininterface.TaggedValueInterface; import edu.common.dynamicextensions.util.global.Constants; import edu.wustl.common.querysuite.metadata.associations.IAssociation; import edu.wustl.common.querysuite.metadata.path.Path; public class TestUtil { private static DomainObjectFactory deFactory = DomainObjectFactory.getInstance(); public static EntityInterface getEntity(String entityName, String attrName, EntityInterface parent) { AttributeInterface a = getAttribute(attrName); EntityInterface e1 = deFactory.createEntity(); e1.setName(entityName); if (parent != null) { e1.setParentEntity(parent); markInherited(a); } e1.addAttribute(a); return e1; } public static EntityInterface getEntity(String entityName, String attrName) { AttributeInterface a = getAttribute(attrName); EntityInterface e1 = getEntity(entityName); e1.addAttribute(a); a.setEntity(e1); return e1; } public static AttributeInterface getAttribute(String entityName, long entityId, String attrName,long attrId) { EntityInterface e = getEntity(entityName,attrName); AttributeInterface a = e.getAttributeCollection().iterator().next(); e.setId(entityId); a.setId(attrId); return a; } public static EntityInterface getEntity(String entityName) { EntityInterface e1 = deFactory.createEntity(); e1.setName(entityName); return e1; } public static EntityInterface getEntity(String entityName, long id) { EntityInterface e1 = deFactory.createEntity(); e1.setId(id); e1.setName(entityName); return e1; } public static EntityGroupInterface getEntityGroup(String name, long id) { EntityGroupInterface e1 = deFactory.createEntityGroup(); e1.setId(id); e1.setName(name); e1.setLongName(name); return e1; } public static void markInherited(AbstractMetadataInterface owner) { TaggedValueInterface taggedValue = deFactory.createTaggedValue(); taggedValue.setKey(TYPE_DERIVED); taggedValue.setValue(TYPE_DERIVED); owner.addTaggedValue(taggedValue); } public static AssociationInterface getAssociation(String srcEntityName, String targetEntityName) { EntityInterface src = getEntity(srcEntityName); EntityInterface target = getEntity(targetEntityName); return getAssociation(src,target); } public static AssociationInterface getAssociation(EntityInterface src, EntityInterface target) { AssociationInterface association = deFactory.createAssociation(); association.setName("AssociationName_" + src.getAssociationCollection().size() + 1); association.setEntity(src); src.addAssociation(association); association.setSourceRole(getRole("srcRole")); association.setTargetEntity(target); association.setTargetRole(getRole("tgtRole")); association.setAssociationDirection(Constants.AssociationDirection.BI_DIRECTIONAL); return association; } private static RoleInterface getRole(String roleName) { RoleInterface role = deFactory.createRole(); role.setAssociationsType(Constants.AssociationType.ASSOCIATION); role.setName(roleName); role.setMaximumCardinality(Constants.Cardinality.MANY); role.setMinimumCardinality(Constants.Cardinality.MANY); return role; } public static AttributeInterface getAttribute(String name) { AttributeInterface a = deFactory.createStringAttribute(); a.setName(name); return a; } public static EntityInterface getEntityWithGrp(String groupName, String entityName, String attrName) { AttributeInterface a = getAttribute(attrName); EntityInterface e1 = getEntity(entityName); e1.addAttribute(a); a.setEntity(e1); EntityGroupInterface eg = DomainObjectFactory.getInstance().createEntityGroup(); eg.setName(groupName); eg.addEntity(e1); e1.addEntityGroupInterface(eg); return e1; } public static EntityInterface getEntityWithCaB2BGrp(String groupName, String entityName, String attrName) { AttributeInterface a = getAttribute(attrName); EntityInterface e1 = getEntity(entityName); e1.addAttribute(a); a.setEntity(e1); EntityGroupInterface eg = DomainObjectFactory.getInstance().createEntityGroup(); DynamicExtensionUtility.addTaggedValue(eg,edu.wustl.cab2b.common.util.Constants.CAB2B_ENTITY_GROUP, edu.wustl.cab2b.common.util.Constants.CAB2B_ENTITY_GROUP); eg.setName(groupName); eg.addEntity(e1); e1.addEntityGroupInterface(eg); return e1; } public static Path getPath(IAssociation association) { List<IAssociation> allAssociation = new ArrayList<IAssociation>(1); allAssociation.add(association); return new Path(association.getSourceEntity(), association.getTargetEntity(), allAssociation); } }
/******************************************************************************* * Copyright (c) 2014, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Martin Vojtek - 2.6.0 - initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.perf.largexml.bigpo.common_basic_components; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import org.eclipse.persistence.testing.perf.largexml.bigpo.specialized_data_types.UBLAmountType; /** * <p>Java class for ExtensionTotalAmountType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ExtensionTotalAmountType"> * &lt;simpleContent> * &lt;extension base="&lt;urn:oasis:names:specification:ubl:schema:xsd:SpecializedDatatypes-1.0>UBLAmountType"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ExtensionTotalAmountType") public class ExtensionTotalAmountType extends UBLAmountType { }